SemaTemplate.cpp revision 201361
1168515Sgshapiro//===------- SemaTemplate.cpp - Semantic Analysis for C++ Templates -------===/
2168515Sgshapiro//
3168515Sgshapiro//                     The LLVM Compiler Infrastructure
4132943Sgshapiro//
5266527Sgshapiro// This file is distributed under the University of Illinois Open Source
6132943Sgshapiro// License. See LICENSE.TXT for details.
7168515Sgshapiro//===----------------------------------------------------------------------===/
890792Sgshapiro//
9168515Sgshapiro//  This file implements semantic analysis for C++ templates.
1090792Sgshapiro//===----------------------------------------------------------------------===/
11168515Sgshapiro
12168515Sgshapiro#include "Sema.h"
1390792Sgshapiro#include "Lookup.h"
1490792Sgshapiro#include "TreeTransform.h"
1590792Sgshapiro#include "clang/AST/ASTContext.h"
1690792Sgshapiro#include "clang/AST/Expr.h"
17168515Sgshapiro#include "clang/AST/ExprCXX.h"
18168515Sgshapiro#include "clang/AST/DeclTemplate.h"
19168515Sgshapiro#include "clang/Parse/DeclSpec.h"
2090792Sgshapiro#include "clang/Parse/Template.h"
2190792Sgshapiro#include "clang/Basic/LangOptions.h"
22168515Sgshapiro#include "clang/Basic/PartialDiagnostic.h"
23168515Sgshapiro#include "llvm/ADT/StringExtras.h"
24168515Sgshapirousing namespace clang;
25168515Sgshapiro
26168515Sgshapiro/// \brief Determine whether the declaration found is acceptable as the name
27168515Sgshapiro/// of a template and, if so, return that template declaration. Otherwise,
28168515Sgshapiro/// returns NULL.
29168515Sgshapirostatic NamedDecl *isAcceptableTemplateName(ASTContext &Context, NamedDecl *D) {
30168515Sgshapiro  if (!D)
31168515Sgshapiro    return 0;
32110560Sgshapiro
33168515Sgshapiro  if (isa<TemplateDecl>(D))
34168515Sgshapiro    return D;
35168515Sgshapiro
3690792Sgshapiro  if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
3790792Sgshapiro    // C++ [temp.local]p1:
38168515Sgshapiro    //   Like normal (non-template) classes, class templates have an
39168515Sgshapiro    //   injected-class-name (Clause 9). The injected-class-name
40168515Sgshapiro    //   can be used with or without a template-argument-list. When
41168515Sgshapiro    //   it is used without a template-argument-list, it is
42168515Sgshapiro    //   equivalent to the injected-class-name followed by the
43168515Sgshapiro    //   template-parameters of the class template enclosed in
44168515Sgshapiro    //   <>. When it is used with a template-argument-list, it
45168515Sgshapiro    //   refers to the specified class template specialization,
46168515Sgshapiro    //   which could be the current specialization or another
4790792Sgshapiro    //   specialization.
4890792Sgshapiro    if (Record->isInjectedClassName()) {
49168515Sgshapiro      Record = cast<CXXRecordDecl>(Record->getDeclContext());
50168515Sgshapiro      if (Record->getDescribedClassTemplate())
5190792Sgshapiro        return Record->getDescribedClassTemplate();
52168515Sgshapiro
53168515Sgshapiro      if (ClassTemplateSpecializationDecl *Spec
5490792Sgshapiro            = dyn_cast<ClassTemplateSpecializationDecl>(Record))
55244833Sgshapiro        return Spec->getSpecializedTemplate();
56244833Sgshapiro    }
57244833Sgshapiro
58244833Sgshapiro    return 0;
59244833Sgshapiro  }
60244833Sgshapiro
61244833Sgshapiro  return 0;
62244833Sgshapiro}
63244833Sgshapiro
64244833Sgshapirostatic void FilterAcceptableTemplateNames(ASTContext &C, LookupResult &R) {
65168515Sgshapiro  LookupResult::Filter filter = R.makeFilter();
6690792Sgshapiro  while (filter.hasNext()) {
67244833Sgshapiro    NamedDecl *Orig = filter.next();
68244833Sgshapiro    NamedDecl *Repl = isAcceptableTemplateName(C, Orig->getUnderlyingDecl());
69244833Sgshapiro    if (!Repl)
70168515Sgshapiro      filter.erase();
71168515Sgshapiro    else if (Repl != Orig)
72261194Sgshapiro      filter.replace(Repl);
7390792Sgshapiro  }
74168515Sgshapiro  filter.done();
7590792Sgshapiro}
76112810Sgshapiro
77168515SgshapiroTemplateNameKind Sema::isTemplateName(Scope *S,
78168515Sgshapiro                                      const CXXScopeSpec &SS,
79168515Sgshapiro                                      UnqualifiedId &Name,
80                                      TypeTy *ObjectTypePtr,
81                                      bool EnteringContext,
82                                      TemplateTy &TemplateResult) {
83  DeclarationName TName;
84
85  switch (Name.getKind()) {
86  case UnqualifiedId::IK_Identifier:
87    TName = DeclarationName(Name.Identifier);
88    break;
89
90  case UnqualifiedId::IK_OperatorFunctionId:
91    TName = Context.DeclarationNames.getCXXOperatorName(
92                                              Name.OperatorFunctionId.Operator);
93    break;
94
95  case UnqualifiedId::IK_LiteralOperatorId:
96    TName = Context.DeclarationNames.getCXXLiteralOperatorName(Name.Identifier);
97    break;
98
99  default:
100    return TNK_Non_template;
101  }
102
103  QualType ObjectType = QualType::getFromOpaquePtr(ObjectTypePtr);
104
105  LookupResult R(*this, TName, Name.getSourceRange().getBegin(),
106                 LookupOrdinaryName);
107  R.suppressDiagnostics();
108  LookupTemplateName(R, S, SS, ObjectType, EnteringContext);
109  if (R.empty())
110    return TNK_Non_template;
111
112  TemplateName Template;
113  TemplateNameKind TemplateKind;
114
115  unsigned ResultCount = R.end() - R.begin();
116  if (ResultCount > 1) {
117    // We assume that we'll preserve the qualifier from a function
118    // template name in other ways.
119    Template = Context.getOverloadedTemplateName(R.begin(), R.end());
120    TemplateKind = TNK_Function_template;
121  } else {
122    TemplateDecl *TD = cast<TemplateDecl>((*R.begin())->getUnderlyingDecl());
123
124    if (SS.isSet() && !SS.isInvalid()) {
125      NestedNameSpecifier *Qualifier
126        = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
127      Template = Context.getQualifiedTemplateName(Qualifier, false, TD);
128    } else {
129      Template = TemplateName(TD);
130    }
131
132    if (isa<FunctionTemplateDecl>(TD))
133      TemplateKind = TNK_Function_template;
134    else {
135      assert(isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD));
136      TemplateKind = TNK_Type_template;
137    }
138  }
139
140  TemplateResult = TemplateTy::make(Template);
141  return TemplateKind;
142}
143
144void Sema::LookupTemplateName(LookupResult &Found,
145                              Scope *S, const CXXScopeSpec &SS,
146                              QualType ObjectType,
147                              bool EnteringContext) {
148  // Determine where to perform name lookup
149  DeclContext *LookupCtx = 0;
150  bool isDependent = false;
151  if (!ObjectType.isNull()) {
152    // This nested-name-specifier occurs in a member access expression, e.g.,
153    // x->B::f, and we are looking into the type of the object.
154    assert(!SS.isSet() && "ObjectType and scope specifier cannot coexist");
155    LookupCtx = computeDeclContext(ObjectType);
156    isDependent = ObjectType->isDependentType();
157    assert((isDependent || !ObjectType->isIncompleteType()) &&
158           "Caller should have completed object type");
159  } else if (SS.isSet()) {
160    // This nested-name-specifier occurs after another nested-name-specifier,
161    // so long into the context associated with the prior nested-name-specifier.
162    LookupCtx = computeDeclContext(SS, EnteringContext);
163    isDependent = isDependentScopeSpecifier(SS);
164
165    // The declaration context must be complete.
166    if (LookupCtx && RequireCompleteDeclContext(SS))
167      return;
168  }
169
170  bool ObjectTypeSearchedInScope = false;
171  if (LookupCtx) {
172    // Perform "qualified" name lookup into the declaration context we
173    // computed, which is either the type of the base of a member access
174    // expression or the declaration context associated with a prior
175    // nested-name-specifier.
176    LookupQualifiedName(Found, LookupCtx);
177
178    if (!ObjectType.isNull() && Found.empty()) {
179      // C++ [basic.lookup.classref]p1:
180      //   In a class member access expression (5.2.5), if the . or -> token is
181      //   immediately followed by an identifier followed by a <, the
182      //   identifier must be looked up to determine whether the < is the
183      //   beginning of a template argument list (14.2) or a less-than operator.
184      //   The identifier is first looked up in the class of the object
185      //   expression. If the identifier is not found, it is then looked up in
186      //   the context of the entire postfix-expression and shall name a class
187      //   or function template.
188      //
189      // FIXME: When we're instantiating a template, do we actually have to
190      // look in the scope of the template? Seems fishy...
191      if (S) LookupName(Found, S);
192      ObjectTypeSearchedInScope = true;
193    }
194  } else if (isDependent) {
195    // We cannot look into a dependent object type or
196    return;
197  } else {
198    // Perform unqualified name lookup in the current scope.
199    LookupName(Found, S);
200  }
201
202  // FIXME: Cope with ambiguous name-lookup results.
203  assert(!Found.isAmbiguous() &&
204         "Cannot handle template name-lookup ambiguities");
205
206  if (Found.empty()) {
207    // If we did not find any names, attempt to correct any typos.
208    DeclarationName Name = Found.getLookupName();
209    if (CorrectTypo(Found, S, &SS, LookupCtx)) {
210      FilterAcceptableTemplateNames(Context, Found);
211      if (!Found.empty() && isa<TemplateDecl>(*Found.begin())) {
212        if (LookupCtx)
213          Diag(Found.getNameLoc(), diag::err_no_member_template_suggest)
214            << Name << LookupCtx << Found.getLookupName() << SS.getRange()
215            << CodeModificationHint::CreateReplacement(Found.getNameLoc(),
216                                          Found.getLookupName().getAsString());
217        else
218          Diag(Found.getNameLoc(), diag::err_no_template_suggest)
219            << Name << Found.getLookupName()
220            << CodeModificationHint::CreateReplacement(Found.getNameLoc(),
221                                          Found.getLookupName().getAsString());
222      } else
223        Found.clear();
224    } else {
225      Found.clear();
226    }
227  }
228
229  FilterAcceptableTemplateNames(Context, Found);
230  if (Found.empty())
231    return;
232
233  if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope) {
234    // C++ [basic.lookup.classref]p1:
235    //   [...] If the lookup in the class of the object expression finds a
236    //   template, the name is also looked up in the context of the entire
237    //   postfix-expression and [...]
238    //
239    LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(),
240                            LookupOrdinaryName);
241    LookupName(FoundOuter, S);
242    FilterAcceptableTemplateNames(Context, FoundOuter);
243    // FIXME: Handle ambiguities in this lookup better
244
245    if (FoundOuter.empty()) {
246      //   - if the name is not found, the name found in the class of the
247      //     object expression is used, otherwise
248    } else if (!FoundOuter.getAsSingle<ClassTemplateDecl>()) {
249      //   - if the name is found in the context of the entire
250      //     postfix-expression and does not name a class template, the name
251      //     found in the class of the object expression is used, otherwise
252    } else {
253      //   - if the name found is a class template, it must refer to the same
254      //     entity as the one found in the class of the object expression,
255      //     otherwise the program is ill-formed.
256      if (!Found.isSingleResult() ||
257          Found.getFoundDecl()->getCanonicalDecl()
258            != FoundOuter.getFoundDecl()->getCanonicalDecl()) {
259        Diag(Found.getNameLoc(),
260             diag::err_nested_name_member_ref_lookup_ambiguous)
261          << Found.getLookupName();
262        Diag(Found.getRepresentativeDecl()->getLocation(),
263             diag::note_ambig_member_ref_object_type)
264          << ObjectType;
265        Diag(FoundOuter.getFoundDecl()->getLocation(),
266             diag::note_ambig_member_ref_scope);
267
268        // Recover by taking the template that we found in the object
269        // expression's type.
270      }
271    }
272  }
273}
274
275/// ActOnDependentIdExpression - Handle a dependent id-expression that
276/// was just parsed.  This is only possible with an explicit scope
277/// specifier naming a dependent type.
278Sema::OwningExprResult
279Sema::ActOnDependentIdExpression(const CXXScopeSpec &SS,
280                                 DeclarationName Name,
281                                 SourceLocation NameLoc,
282                                 bool isAddressOfOperand,
283                           const TemplateArgumentListInfo *TemplateArgs) {
284  NestedNameSpecifier *Qualifier
285    = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
286
287  if (!isAddressOfOperand &&
288      isa<CXXMethodDecl>(CurContext) &&
289      cast<CXXMethodDecl>(CurContext)->isInstance()) {
290    QualType ThisType = cast<CXXMethodDecl>(CurContext)->getThisType(Context);
291
292    // Since the 'this' expression is synthesized, we don't need to
293    // perform the double-lookup check.
294    NamedDecl *FirstQualifierInScope = 0;
295
296    return Owned(CXXDependentScopeMemberExpr::Create(Context,
297                                                     /*This*/ 0, ThisType,
298                                                     /*IsArrow*/ true,
299                                                     /*Op*/ SourceLocation(),
300                                                     Qualifier, SS.getRange(),
301                                                     FirstQualifierInScope,
302                                                     Name, NameLoc,
303                                                     TemplateArgs));
304  }
305
306  return BuildDependentDeclRefExpr(SS, Name, NameLoc, TemplateArgs);
307}
308
309Sema::OwningExprResult
310Sema::BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
311                                DeclarationName Name,
312                                SourceLocation NameLoc,
313                                const TemplateArgumentListInfo *TemplateArgs) {
314  return Owned(DependentScopeDeclRefExpr::Create(Context,
315               static_cast<NestedNameSpecifier*>(SS.getScopeRep()),
316                                                 SS.getRange(),
317                                                 Name, NameLoc,
318                                                 TemplateArgs));
319}
320
321/// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
322/// that the template parameter 'PrevDecl' is being shadowed by a new
323/// declaration at location Loc. Returns true to indicate that this is
324/// an error, and false otherwise.
325bool Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
326  assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
327
328  // Microsoft Visual C++ permits template parameters to be shadowed.
329  if (getLangOptions().Microsoft)
330    return false;
331
332  // C++ [temp.local]p4:
333  //   A template-parameter shall not be redeclared within its
334  //   scope (including nested scopes).
335  Diag(Loc, diag::err_template_param_shadow)
336    << cast<NamedDecl>(PrevDecl)->getDeclName();
337  Diag(PrevDecl->getLocation(), diag::note_template_param_here);
338  return true;
339}
340
341/// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
342/// the parameter D to reference the templated declaration and return a pointer
343/// to the template declaration. Otherwise, do nothing to D and return null.
344TemplateDecl *Sema::AdjustDeclIfTemplate(DeclPtrTy &D) {
345  if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D.getAs<Decl>())) {
346    D = DeclPtrTy::make(Temp->getTemplatedDecl());
347    return Temp;
348  }
349  return 0;
350}
351
352static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef,
353                                            const ParsedTemplateArgument &Arg) {
354
355  switch (Arg.getKind()) {
356  case ParsedTemplateArgument::Type: {
357    TypeSourceInfo *DI;
358    QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI);
359    if (!DI)
360      DI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getLocation());
361    return TemplateArgumentLoc(TemplateArgument(T), DI);
362  }
363
364  case ParsedTemplateArgument::NonType: {
365    Expr *E = static_cast<Expr *>(Arg.getAsExpr());
366    return TemplateArgumentLoc(TemplateArgument(E), E);
367  }
368
369  case ParsedTemplateArgument::Template: {
370    TemplateName Template
371      = TemplateName::getFromVoidPointer(Arg.getAsTemplate().get());
372    return TemplateArgumentLoc(TemplateArgument(Template),
373                               Arg.getScopeSpec().getRange(),
374                               Arg.getLocation());
375  }
376  }
377
378  llvm_unreachable("Unhandled parsed template argument");
379  return TemplateArgumentLoc();
380}
381
382/// \brief Translates template arguments as provided by the parser
383/// into template arguments used by semantic analysis.
384void Sema::translateTemplateArguments(const ASTTemplateArgsPtr &TemplateArgsIn,
385                                      TemplateArgumentListInfo &TemplateArgs) {
386 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
387   TemplateArgs.addArgument(translateTemplateArgument(*this,
388                                                      TemplateArgsIn[I]));
389}
390
391/// ActOnTypeParameter - Called when a C++ template type parameter
392/// (e.g., "typename T") has been parsed. Typename specifies whether
393/// the keyword "typename" was used to declare the type parameter
394/// (otherwise, "class" was used), and KeyLoc is the location of the
395/// "class" or "typename" keyword. ParamName is the name of the
396/// parameter (NULL indicates an unnamed template parameter) and
397/// ParamName is the location of the parameter name (if any).
398/// If the type parameter has a default argument, it will be added
399/// later via ActOnTypeParameterDefault.
400Sema::DeclPtrTy Sema::ActOnTypeParameter(Scope *S, bool Typename, bool Ellipsis,
401                                         SourceLocation EllipsisLoc,
402                                         SourceLocation KeyLoc,
403                                         IdentifierInfo *ParamName,
404                                         SourceLocation ParamNameLoc,
405                                         unsigned Depth, unsigned Position) {
406  assert(S->isTemplateParamScope() &&
407         "Template type parameter not in template parameter scope!");
408  bool Invalid = false;
409
410  if (ParamName) {
411    NamedDecl *PrevDecl = LookupSingleName(S, ParamName, LookupTagName);
412    if (PrevDecl && PrevDecl->isTemplateParameter())
413      Invalid = Invalid || DiagnoseTemplateParameterShadow(ParamNameLoc,
414                                                           PrevDecl);
415  }
416
417  SourceLocation Loc = ParamNameLoc;
418  if (!ParamName)
419    Loc = KeyLoc;
420
421  TemplateTypeParmDecl *Param
422    = TemplateTypeParmDecl::Create(Context, CurContext, Loc,
423                                   Depth, Position, ParamName, Typename,
424                                   Ellipsis);
425  if (Invalid)
426    Param->setInvalidDecl();
427
428  if (ParamName) {
429    // Add the template parameter into the current scope.
430    S->AddDecl(DeclPtrTy::make(Param));
431    IdResolver.AddDecl(Param);
432  }
433
434  return DeclPtrTy::make(Param);
435}
436
437/// ActOnTypeParameterDefault - Adds a default argument (the type
438/// Default) to the given template type parameter (TypeParam).
439void Sema::ActOnTypeParameterDefault(DeclPtrTy TypeParam,
440                                     SourceLocation EqualLoc,
441                                     SourceLocation DefaultLoc,
442                                     TypeTy *DefaultT) {
443  TemplateTypeParmDecl *Parm
444    = cast<TemplateTypeParmDecl>(TypeParam.getAs<Decl>());
445
446  TypeSourceInfo *DefaultTInfo;
447  GetTypeFromParser(DefaultT, &DefaultTInfo);
448
449  assert(DefaultTInfo && "expected source information for type");
450
451  // C++0x [temp.param]p9:
452  // A default template-argument may be specified for any kind of
453  // template-parameter that is not a template parameter pack.
454  if (Parm->isParameterPack()) {
455    Diag(DefaultLoc, diag::err_template_param_pack_default_arg);
456    return;
457  }
458
459  // C++ [temp.param]p14:
460  //   A template-parameter shall not be used in its own default argument.
461  // FIXME: Implement this check! Needs a recursive walk over the types.
462
463  // Check the template argument itself.
464  if (CheckTemplateArgument(Parm, DefaultTInfo)) {
465    Parm->setInvalidDecl();
466    return;
467  }
468
469  Parm->setDefaultArgument(DefaultTInfo, false);
470}
471
472/// \brief Check that the type of a non-type template parameter is
473/// well-formed.
474///
475/// \returns the (possibly-promoted) parameter type if valid;
476/// otherwise, produces a diagnostic and returns a NULL type.
477QualType
478Sema::CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc) {
479  // C++ [temp.param]p4:
480  //
481  // A non-type template-parameter shall have one of the following
482  // (optionally cv-qualified) types:
483  //
484  //       -- integral or enumeration type,
485  if (T->isIntegralType() || T->isEnumeralType() ||
486      //   -- pointer to object or pointer to function,
487      (T->isPointerType() &&
488       (T->getAs<PointerType>()->getPointeeType()->isObjectType() ||
489        T->getAs<PointerType>()->getPointeeType()->isFunctionType())) ||
490      //   -- reference to object or reference to function,
491      T->isReferenceType() ||
492      //   -- pointer to member.
493      T->isMemberPointerType() ||
494      // If T is a dependent type, we can't do the check now, so we
495      // assume that it is well-formed.
496      T->isDependentType())
497    return T;
498  // C++ [temp.param]p8:
499  //
500  //   A non-type template-parameter of type "array of T" or
501  //   "function returning T" is adjusted to be of type "pointer to
502  //   T" or "pointer to function returning T", respectively.
503  else if (T->isArrayType())
504    // FIXME: Keep the type prior to promotion?
505    return Context.getArrayDecayedType(T);
506  else if (T->isFunctionType())
507    // FIXME: Keep the type prior to promotion?
508    return Context.getPointerType(T);
509
510  Diag(Loc, diag::err_template_nontype_parm_bad_type)
511    << T;
512
513  return QualType();
514}
515
516/// ActOnNonTypeTemplateParameter - Called when a C++ non-type
517/// template parameter (e.g., "int Size" in "template<int Size>
518/// class Array") has been parsed. S is the current scope and D is
519/// the parsed declarator.
520Sema::DeclPtrTy Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
521                                                    unsigned Depth,
522                                                    unsigned Position) {
523  TypeSourceInfo *TInfo = 0;
524  QualType T = GetTypeForDeclarator(D, S, &TInfo);
525
526  assert(S->isTemplateParamScope() &&
527         "Non-type template parameter not in template parameter scope!");
528  bool Invalid = false;
529
530  IdentifierInfo *ParamName = D.getIdentifier();
531  if (ParamName) {
532    NamedDecl *PrevDecl = LookupSingleName(S, ParamName, LookupTagName);
533    if (PrevDecl && PrevDecl->isTemplateParameter())
534      Invalid = Invalid || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
535                                                           PrevDecl);
536  }
537
538  T = CheckNonTypeTemplateParameterType(T, D.getIdentifierLoc());
539  if (T.isNull()) {
540    T = Context.IntTy; // Recover with an 'int' type.
541    Invalid = true;
542  }
543
544  NonTypeTemplateParmDecl *Param
545    = NonTypeTemplateParmDecl::Create(Context, CurContext, D.getIdentifierLoc(),
546                                      Depth, Position, ParamName, T, TInfo);
547  if (Invalid)
548    Param->setInvalidDecl();
549
550  if (D.getIdentifier()) {
551    // Add the template parameter into the current scope.
552    S->AddDecl(DeclPtrTy::make(Param));
553    IdResolver.AddDecl(Param);
554  }
555  return DeclPtrTy::make(Param);
556}
557
558/// \brief Adds a default argument to the given non-type template
559/// parameter.
560void Sema::ActOnNonTypeTemplateParameterDefault(DeclPtrTy TemplateParamD,
561                                                SourceLocation EqualLoc,
562                                                ExprArg DefaultE) {
563  NonTypeTemplateParmDecl *TemplateParm
564    = cast<NonTypeTemplateParmDecl>(TemplateParamD.getAs<Decl>());
565  Expr *Default = static_cast<Expr *>(DefaultE.get());
566
567  // C++ [temp.param]p14:
568  //   A template-parameter shall not be used in its own default argument.
569  // FIXME: Implement this check! Needs a recursive walk over the types.
570
571  // Check the well-formedness of the default template argument.
572  TemplateArgument Converted;
573  if (CheckTemplateArgument(TemplateParm, TemplateParm->getType(), Default,
574                            Converted)) {
575    TemplateParm->setInvalidDecl();
576    return;
577  }
578
579  TemplateParm->setDefaultArgument(DefaultE.takeAs<Expr>());
580}
581
582
583/// ActOnTemplateTemplateParameter - Called when a C++ template template
584/// parameter (e.g. T in template <template <typename> class T> class array)
585/// has been parsed. S is the current scope.
586Sema::DeclPtrTy Sema::ActOnTemplateTemplateParameter(Scope* S,
587                                                     SourceLocation TmpLoc,
588                                                     TemplateParamsTy *Params,
589                                                     IdentifierInfo *Name,
590                                                     SourceLocation NameLoc,
591                                                     unsigned Depth,
592                                                     unsigned Position) {
593  assert(S->isTemplateParamScope() &&
594         "Template template parameter not in template parameter scope!");
595
596  // Construct the parameter object.
597  TemplateTemplateParmDecl *Param =
598    TemplateTemplateParmDecl::Create(Context, CurContext, TmpLoc, Depth,
599                                     Position, Name,
600                                     (TemplateParameterList*)Params);
601
602  // Make sure the parameter is valid.
603  // FIXME: Decl object is not currently invalidated anywhere so this doesn't
604  // do anything yet. However, if the template parameter list or (eventual)
605  // default value is ever invalidated, that will propagate here.
606  bool Invalid = false;
607  if (Invalid) {
608    Param->setInvalidDecl();
609  }
610
611  // If the tt-param has a name, then link the identifier into the scope
612  // and lookup mechanisms.
613  if (Name) {
614    S->AddDecl(DeclPtrTy::make(Param));
615    IdResolver.AddDecl(Param);
616  }
617
618  return DeclPtrTy::make(Param);
619}
620
621/// \brief Adds a default argument to the given template template
622/// parameter.
623void Sema::ActOnTemplateTemplateParameterDefault(DeclPtrTy TemplateParamD,
624                                                 SourceLocation EqualLoc,
625                                        const ParsedTemplateArgument &Default) {
626  TemplateTemplateParmDecl *TemplateParm
627    = cast<TemplateTemplateParmDecl>(TemplateParamD.getAs<Decl>());
628
629  // C++ [temp.param]p14:
630  //   A template-parameter shall not be used in its own default argument.
631  // FIXME: Implement this check! Needs a recursive walk over the types.
632
633  // Check only that we have a template template argument. We don't want to
634  // try to check well-formedness now, because our template template parameter
635  // might have dependent types in its template parameters, which we wouldn't
636  // be able to match now.
637  //
638  // If none of the template template parameter's template arguments mention
639  // other template parameters, we could actually perform more checking here.
640  // However, it isn't worth doing.
641  TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default);
642  if (DefaultArg.getArgument().getAsTemplate().isNull()) {
643    Diag(DefaultArg.getLocation(), diag::err_template_arg_not_class_template)
644      << DefaultArg.getSourceRange();
645    return;
646  }
647
648  TemplateParm->setDefaultArgument(DefaultArg);
649}
650
651/// ActOnTemplateParameterList - Builds a TemplateParameterList that
652/// contains the template parameters in Params/NumParams.
653Sema::TemplateParamsTy *
654Sema::ActOnTemplateParameterList(unsigned Depth,
655                                 SourceLocation ExportLoc,
656                                 SourceLocation TemplateLoc,
657                                 SourceLocation LAngleLoc,
658                                 DeclPtrTy *Params, unsigned NumParams,
659                                 SourceLocation RAngleLoc) {
660  if (ExportLoc.isValid())
661    Diag(ExportLoc, diag::warn_template_export_unsupported);
662
663  return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
664                                       (NamedDecl**)Params, NumParams,
665                                       RAngleLoc);
666}
667
668Sema::DeclResult
669Sema::CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
670                         SourceLocation KWLoc, const CXXScopeSpec &SS,
671                         IdentifierInfo *Name, SourceLocation NameLoc,
672                         AttributeList *Attr,
673                         TemplateParameterList *TemplateParams,
674                         AccessSpecifier AS) {
675  assert(TemplateParams && TemplateParams->size() > 0 &&
676         "No template parameters");
677  assert(TUK != TUK_Reference && "Can only declare or define class templates");
678  bool Invalid = false;
679
680  // Check that we can declare a template here.
681  if (CheckTemplateDeclScope(S, TemplateParams))
682    return true;
683
684  TagDecl::TagKind Kind = TagDecl::getTagKindForTypeSpec(TagSpec);
685  assert(Kind != TagDecl::TK_enum && "can't build template of enumerated type");
686
687  // There is no such thing as an unnamed class template.
688  if (!Name) {
689    Diag(KWLoc, diag::err_template_unnamed_class);
690    return true;
691  }
692
693  // Find any previous declaration with this name.
694  DeclContext *SemanticContext;
695  LookupResult Previous(*this, Name, NameLoc, LookupOrdinaryName,
696                        ForRedeclaration);
697  if (SS.isNotEmpty() && !SS.isInvalid()) {
698    if (RequireCompleteDeclContext(SS))
699      return true;
700
701    SemanticContext = computeDeclContext(SS, true);
702    if (!SemanticContext) {
703      // FIXME: Produce a reasonable diagnostic here
704      return true;
705    }
706
707    LookupQualifiedName(Previous, SemanticContext);
708  } else {
709    SemanticContext = CurContext;
710    LookupName(Previous, S);
711  }
712
713  assert(!Previous.isAmbiguous() && "Ambiguity in class template redecl?");
714  NamedDecl *PrevDecl = 0;
715  if (Previous.begin() != Previous.end())
716    PrevDecl = *Previous.begin();
717
718  // If there is a previous declaration with the same name, check
719  // whether this is a valid redeclaration.
720  ClassTemplateDecl *PrevClassTemplate
721    = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
722
723  // We may have found the injected-class-name of a class template,
724  // class template partial specialization, or class template specialization.
725  // In these cases, grab the template that is being defined or specialized.
726  if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) &&
727      cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
728    PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
729    PrevClassTemplate
730      = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
731    if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
732      PrevClassTemplate
733        = cast<ClassTemplateSpecializationDecl>(PrevDecl)
734            ->getSpecializedTemplate();
735    }
736  }
737
738  if (TUK == TUK_Friend) {
739    // C++ [namespace.memdef]p3:
740    //   [...] When looking for a prior declaration of a class or a function
741    //   declared as a friend, and when the name of the friend class or
742    //   function is neither a qualified name nor a template-id, scopes outside
743    //   the innermost enclosing namespace scope are not considered.
744    DeclContext *OutermostContext = CurContext;
745    while (!OutermostContext->isFileContext())
746      OutermostContext = OutermostContext->getLookupParent();
747
748    if (PrevDecl &&
749        (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
750         OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
751      SemanticContext = PrevDecl->getDeclContext();
752    } else {
753      // Declarations in outer scopes don't matter. However, the outermost
754      // context we computed is the semantic context for our new
755      // declaration.
756      PrevDecl = PrevClassTemplate = 0;
757      SemanticContext = OutermostContext;
758    }
759
760    if (CurContext->isDependentContext()) {
761      // If this is a dependent context, we don't want to link the friend
762      // class template to the template in scope, because that would perform
763      // checking of the template parameter lists that can't be performed
764      // until the outer context is instantiated.
765      PrevDecl = PrevClassTemplate = 0;
766    }
767  } else if (PrevDecl && !isDeclInScope(PrevDecl, SemanticContext, S))
768    PrevDecl = PrevClassTemplate = 0;
769
770  if (PrevClassTemplate) {
771    // Ensure that the template parameter lists are compatible.
772    if (!TemplateParameterListsAreEqual(TemplateParams,
773                                   PrevClassTemplate->getTemplateParameters(),
774                                        /*Complain=*/true,
775                                        TPL_TemplateMatch))
776      return true;
777
778    // C++ [temp.class]p4:
779    //   In a redeclaration, partial specialization, explicit
780    //   specialization or explicit instantiation of a class template,
781    //   the class-key shall agree in kind with the original class
782    //   template declaration (7.1.5.3).
783    RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
784    if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind, KWLoc, *Name)) {
785      Diag(KWLoc, diag::err_use_with_wrong_tag)
786        << Name
787        << CodeModificationHint::CreateReplacement(KWLoc,
788                            PrevRecordDecl->getKindName());
789      Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
790      Kind = PrevRecordDecl->getTagKind();
791    }
792
793    // Check for redefinition of this class template.
794    if (TUK == TUK_Definition) {
795      if (TagDecl *Def = PrevRecordDecl->getDefinition(Context)) {
796        Diag(NameLoc, diag::err_redefinition) << Name;
797        Diag(Def->getLocation(), diag::note_previous_definition);
798        // FIXME: Would it make sense to try to "forget" the previous
799        // definition, as part of error recovery?
800        return true;
801      }
802    }
803  } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
804    // Maybe we will complain about the shadowed template parameter.
805    DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
806    // Just pretend that we didn't see the previous declaration.
807    PrevDecl = 0;
808  } else if (PrevDecl) {
809    // C++ [temp]p5:
810    //   A class template shall not have the same name as any other
811    //   template, class, function, object, enumeration, enumerator,
812    //   namespace, or type in the same scope (3.3), except as specified
813    //   in (14.5.4).
814    Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
815    Diag(PrevDecl->getLocation(), diag::note_previous_definition);
816    return true;
817  }
818
819  // Check the template parameter list of this declaration, possibly
820  // merging in the template parameter list from the previous class
821  // template declaration.
822  if (CheckTemplateParameterList(TemplateParams,
823            PrevClassTemplate? PrevClassTemplate->getTemplateParameters() : 0,
824                                 TPC_ClassTemplate))
825    Invalid = true;
826
827  // FIXME: If we had a scope specifier, we better have a previous template
828  // declaration!
829
830  CXXRecordDecl *NewClass =
831    CXXRecordDecl::Create(Context, Kind, SemanticContext, NameLoc, Name, KWLoc,
832                          PrevClassTemplate?
833                            PrevClassTemplate->getTemplatedDecl() : 0,
834                          /*DelayTypeCreation=*/true);
835
836  ClassTemplateDecl *NewTemplate
837    = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
838                                DeclarationName(Name), TemplateParams,
839                                NewClass, PrevClassTemplate);
840  NewClass->setDescribedClassTemplate(NewTemplate);
841
842  // Build the type for the class template declaration now.
843  QualType T =
844    Context.getTypeDeclType(NewClass,
845                            PrevClassTemplate?
846                              PrevClassTemplate->getTemplatedDecl() : 0);
847  assert(T->isDependentType() && "Class template type is not dependent?");
848  (void)T;
849
850  // If we are providing an explicit specialization of a member that is a
851  // class template, make a note of that.
852  if (PrevClassTemplate &&
853      PrevClassTemplate->getInstantiatedFromMemberTemplate())
854    PrevClassTemplate->setMemberSpecialization();
855
856  // Set the access specifier.
857  if (!Invalid && TUK != TUK_Friend)
858    SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
859
860  // Set the lexical context of these templates
861  NewClass->setLexicalDeclContext(CurContext);
862  NewTemplate->setLexicalDeclContext(CurContext);
863
864  if (TUK == TUK_Definition)
865    NewClass->startDefinition();
866
867  if (Attr)
868    ProcessDeclAttributeList(S, NewClass, Attr);
869
870  if (TUK != TUK_Friend)
871    PushOnScopeChains(NewTemplate, S);
872  else {
873    if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
874      NewTemplate->setAccess(PrevClassTemplate->getAccess());
875      NewClass->setAccess(PrevClassTemplate->getAccess());
876    }
877
878    NewTemplate->setObjectOfFriendDecl(/* PreviouslyDeclared = */
879                                       PrevClassTemplate != NULL);
880
881    // Friend templates are visible in fairly strange ways.
882    if (!CurContext->isDependentContext()) {
883      DeclContext *DC = SemanticContext->getLookupContext();
884      DC->makeDeclVisibleInContext(NewTemplate, /* Recoverable = */ false);
885      if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
886        PushOnScopeChains(NewTemplate, EnclosingScope,
887                          /* AddToContext = */ false);
888    }
889
890    FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
891                                            NewClass->getLocation(),
892                                            NewTemplate,
893                                    /*FIXME:*/NewClass->getLocation());
894    Friend->setAccess(AS_public);
895    CurContext->addDecl(Friend);
896  }
897
898  if (Invalid) {
899    NewTemplate->setInvalidDecl();
900    NewClass->setInvalidDecl();
901  }
902  return DeclPtrTy::make(NewTemplate);
903}
904
905/// \brief Diagnose the presence of a default template argument on a
906/// template parameter, which is ill-formed in certain contexts.
907///
908/// \returns true if the default template argument should be dropped.
909static bool DiagnoseDefaultTemplateArgument(Sema &S,
910                                            Sema::TemplateParamListContext TPC,
911                                            SourceLocation ParamLoc,
912                                            SourceRange DefArgRange) {
913  switch (TPC) {
914  case Sema::TPC_ClassTemplate:
915    return false;
916
917  case Sema::TPC_FunctionTemplate:
918    // C++ [temp.param]p9:
919    //   A default template-argument shall not be specified in a
920    //   function template declaration or a function template
921    //   definition [...]
922    // (This sentence is not in C++0x, per DR226).
923    if (!S.getLangOptions().CPlusPlus0x)
924      S.Diag(ParamLoc,
925             diag::err_template_parameter_default_in_function_template)
926        << DefArgRange;
927    return false;
928
929  case Sema::TPC_ClassTemplateMember:
930    // C++0x [temp.param]p9:
931    //   A default template-argument shall not be specified in the
932    //   template-parameter-lists of the definition of a member of a
933    //   class template that appears outside of the member's class.
934    S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
935      << DefArgRange;
936    return true;
937
938  case Sema::TPC_FriendFunctionTemplate:
939    // C++ [temp.param]p9:
940    //   A default template-argument shall not be specified in a
941    //   friend template declaration.
942    S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
943      << DefArgRange;
944    return true;
945
946    // FIXME: C++0x [temp.param]p9 allows default template-arguments
947    // for friend function templates if there is only a single
948    // declaration (and it is a definition). Strange!
949  }
950
951  return false;
952}
953
954/// \brief Checks the validity of a template parameter list, possibly
955/// considering the template parameter list from a previous
956/// declaration.
957///
958/// If an "old" template parameter list is provided, it must be
959/// equivalent (per TemplateParameterListsAreEqual) to the "new"
960/// template parameter list.
961///
962/// \param NewParams Template parameter list for a new template
963/// declaration. This template parameter list will be updated with any
964/// default arguments that are carried through from the previous
965/// template parameter list.
966///
967/// \param OldParams If provided, template parameter list from a
968/// previous declaration of the same template. Default template
969/// arguments will be merged from the old template parameter list to
970/// the new template parameter list.
971///
972/// \param TPC Describes the context in which we are checking the given
973/// template parameter list.
974///
975/// \returns true if an error occurred, false otherwise.
976bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
977                                      TemplateParameterList *OldParams,
978                                      TemplateParamListContext TPC) {
979  bool Invalid = false;
980
981  // C++ [temp.param]p10:
982  //   The set of default template-arguments available for use with a
983  //   template declaration or definition is obtained by merging the
984  //   default arguments from the definition (if in scope) and all
985  //   declarations in scope in the same way default function
986  //   arguments are (8.3.6).
987  bool SawDefaultArgument = false;
988  SourceLocation PreviousDefaultArgLoc;
989
990  bool SawParameterPack = false;
991  SourceLocation ParameterPackLoc;
992
993  // Dummy initialization to avoid warnings.
994  TemplateParameterList::iterator OldParam = NewParams->end();
995  if (OldParams)
996    OldParam = OldParams->begin();
997
998  for (TemplateParameterList::iterator NewParam = NewParams->begin(),
999                                    NewParamEnd = NewParams->end();
1000       NewParam != NewParamEnd; ++NewParam) {
1001    // Variables used to diagnose redundant default arguments
1002    bool RedundantDefaultArg = false;
1003    SourceLocation OldDefaultLoc;
1004    SourceLocation NewDefaultLoc;
1005
1006    // Variables used to diagnose missing default arguments
1007    bool MissingDefaultArg = false;
1008
1009    // C++0x [temp.param]p11:
1010    // If a template parameter of a class template is a template parameter pack,
1011    // it must be the last template parameter.
1012    if (SawParameterPack) {
1013      Diag(ParameterPackLoc,
1014           diag::err_template_param_pack_must_be_last_template_parameter);
1015      Invalid = true;
1016    }
1017
1018    if (TemplateTypeParmDecl *NewTypeParm
1019          = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
1020      // Check the presence of a default argument here.
1021      if (NewTypeParm->hasDefaultArgument() &&
1022          DiagnoseDefaultTemplateArgument(*this, TPC,
1023                                          NewTypeParm->getLocation(),
1024               NewTypeParm->getDefaultArgumentInfo()->getTypeLoc()
1025                                                       .getFullSourceRange()))
1026        NewTypeParm->removeDefaultArgument();
1027
1028      // Merge default arguments for template type parameters.
1029      TemplateTypeParmDecl *OldTypeParm
1030          = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : 0;
1031
1032      if (NewTypeParm->isParameterPack()) {
1033        assert(!NewTypeParm->hasDefaultArgument() &&
1034               "Parameter packs can't have a default argument!");
1035        SawParameterPack = true;
1036        ParameterPackLoc = NewTypeParm->getLocation();
1037      } else if (OldTypeParm && OldTypeParm->hasDefaultArgument() &&
1038                 NewTypeParm->hasDefaultArgument()) {
1039        OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
1040        NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
1041        SawDefaultArgument = true;
1042        RedundantDefaultArg = true;
1043        PreviousDefaultArgLoc = NewDefaultLoc;
1044      } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
1045        // Merge the default argument from the old declaration to the
1046        // new declaration.
1047        SawDefaultArgument = true;
1048        NewTypeParm->setDefaultArgument(OldTypeParm->getDefaultArgumentInfo(),
1049                                        true);
1050        PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
1051      } else if (NewTypeParm->hasDefaultArgument()) {
1052        SawDefaultArgument = true;
1053        PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
1054      } else if (SawDefaultArgument)
1055        MissingDefaultArg = true;
1056    } else if (NonTypeTemplateParmDecl *NewNonTypeParm
1057               = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
1058      // Check the presence of a default argument here.
1059      if (NewNonTypeParm->hasDefaultArgument() &&
1060          DiagnoseDefaultTemplateArgument(*this, TPC,
1061                                          NewNonTypeParm->getLocation(),
1062                    NewNonTypeParm->getDefaultArgument()->getSourceRange())) {
1063        NewNonTypeParm->getDefaultArgument()->Destroy(Context);
1064        NewNonTypeParm->setDefaultArgument(0);
1065      }
1066
1067      // Merge default arguments for non-type template parameters
1068      NonTypeTemplateParmDecl *OldNonTypeParm
1069        = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : 0;
1070      if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument() &&
1071          NewNonTypeParm->hasDefaultArgument()) {
1072        OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
1073        NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
1074        SawDefaultArgument = true;
1075        RedundantDefaultArg = true;
1076        PreviousDefaultArgLoc = NewDefaultLoc;
1077      } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
1078        // Merge the default argument from the old declaration to the
1079        // new declaration.
1080        SawDefaultArgument = true;
1081        // FIXME: We need to create a new kind of "default argument"
1082        // expression that points to a previous template template
1083        // parameter.
1084        NewNonTypeParm->setDefaultArgument(
1085                                        OldNonTypeParm->getDefaultArgument());
1086        PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
1087      } else if (NewNonTypeParm->hasDefaultArgument()) {
1088        SawDefaultArgument = true;
1089        PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
1090      } else if (SawDefaultArgument)
1091        MissingDefaultArg = true;
1092    } else {
1093      // Check the presence of a default argument here.
1094      TemplateTemplateParmDecl *NewTemplateParm
1095        = cast<TemplateTemplateParmDecl>(*NewParam);
1096      if (NewTemplateParm->hasDefaultArgument() &&
1097          DiagnoseDefaultTemplateArgument(*this, TPC,
1098                                          NewTemplateParm->getLocation(),
1099                     NewTemplateParm->getDefaultArgument().getSourceRange()))
1100        NewTemplateParm->setDefaultArgument(TemplateArgumentLoc());
1101
1102      // Merge default arguments for template template parameters
1103      TemplateTemplateParmDecl *OldTemplateParm
1104        = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : 0;
1105      if (OldTemplateParm && OldTemplateParm->hasDefaultArgument() &&
1106          NewTemplateParm->hasDefaultArgument()) {
1107        OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
1108        NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
1109        SawDefaultArgument = true;
1110        RedundantDefaultArg = true;
1111        PreviousDefaultArgLoc = NewDefaultLoc;
1112      } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
1113        // Merge the default argument from the old declaration to the
1114        // new declaration.
1115        SawDefaultArgument = true;
1116        // FIXME: We need to create a new kind of "default argument" expression
1117        // that points to a previous template template parameter.
1118        NewTemplateParm->setDefaultArgument(
1119                                        OldTemplateParm->getDefaultArgument());
1120        PreviousDefaultArgLoc
1121          = OldTemplateParm->getDefaultArgument().getLocation();
1122      } else if (NewTemplateParm->hasDefaultArgument()) {
1123        SawDefaultArgument = true;
1124        PreviousDefaultArgLoc
1125          = NewTemplateParm->getDefaultArgument().getLocation();
1126      } else if (SawDefaultArgument)
1127        MissingDefaultArg = true;
1128    }
1129
1130    if (RedundantDefaultArg) {
1131      // C++ [temp.param]p12:
1132      //   A template-parameter shall not be given default arguments
1133      //   by two different declarations in the same scope.
1134      Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
1135      Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
1136      Invalid = true;
1137    } else if (MissingDefaultArg) {
1138      // C++ [temp.param]p11:
1139      //   If a template-parameter has a default template-argument,
1140      //   all subsequent template-parameters shall have a default
1141      //   template-argument supplied.
1142      Diag((*NewParam)->getLocation(),
1143           diag::err_template_param_default_arg_missing);
1144      Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
1145      Invalid = true;
1146    }
1147
1148    // If we have an old template parameter list that we're merging
1149    // in, move on to the next parameter.
1150    if (OldParams)
1151      ++OldParam;
1152  }
1153
1154  return Invalid;
1155}
1156
1157/// \brief Match the given template parameter lists to the given scope
1158/// specifier, returning the template parameter list that applies to the
1159/// name.
1160///
1161/// \param DeclStartLoc the start of the declaration that has a scope
1162/// specifier or a template parameter list.
1163///
1164/// \param SS the scope specifier that will be matched to the given template
1165/// parameter lists. This scope specifier precedes a qualified name that is
1166/// being declared.
1167///
1168/// \param ParamLists the template parameter lists, from the outermost to the
1169/// innermost template parameter lists.
1170///
1171/// \param NumParamLists the number of template parameter lists in ParamLists.
1172///
1173/// \param IsExplicitSpecialization will be set true if the entity being
1174/// declared is an explicit specialization, false otherwise.
1175///
1176/// \returns the template parameter list, if any, that corresponds to the
1177/// name that is preceded by the scope specifier @p SS. This template
1178/// parameter list may be have template parameters (if we're declaring a
1179/// template) or may have no template parameters (if we're declaring a
1180/// template specialization), or may be NULL (if we were's declaring isn't
1181/// itself a template).
1182TemplateParameterList *
1183Sema::MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc,
1184                                              const CXXScopeSpec &SS,
1185                                          TemplateParameterList **ParamLists,
1186                                              unsigned NumParamLists,
1187                                              bool &IsExplicitSpecialization) {
1188  IsExplicitSpecialization = false;
1189
1190  // Find the template-ids that occur within the nested-name-specifier. These
1191  // template-ids will match up with the template parameter lists.
1192  llvm::SmallVector<const TemplateSpecializationType *, 4>
1193    TemplateIdsInSpecifier;
1194  llvm::SmallVector<ClassTemplateSpecializationDecl *, 4>
1195    ExplicitSpecializationsInSpecifier;
1196  for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
1197       NNS; NNS = NNS->getPrefix()) {
1198    const Type *T = NNS->getAsType();
1199    if (!T) break;
1200
1201    // C++0x [temp.expl.spec]p17:
1202    //   A member or a member template may be nested within many
1203    //   enclosing class templates. In an explicit specialization for
1204    //   such a member, the member declaration shall be preceded by a
1205    //   template<> for each enclosing class template that is
1206    //   explicitly specialized.
1207    // We interpret this as forbidding typedefs of template
1208    // specializations in the scope specifiers of out-of-line decls.
1209    if (const TypedefType *TT = dyn_cast<TypedefType>(T)) {
1210      const Type *UnderlyingT = TT->LookThroughTypedefs().getTypePtr();
1211      if (isa<TemplateSpecializationType>(UnderlyingT))
1212        // FIXME: better source location information.
1213        Diag(DeclStartLoc, diag::err_typedef_in_def_scope) << QualType(T,0);
1214      T = UnderlyingT;
1215    }
1216
1217    if (const TemplateSpecializationType *SpecType
1218          = dyn_cast<TemplateSpecializationType>(T)) {
1219      TemplateDecl *Template = SpecType->getTemplateName().getAsTemplateDecl();
1220      if (!Template)
1221        continue; // FIXME: should this be an error? probably...
1222
1223      if (const RecordType *Record = SpecType->getAs<RecordType>()) {
1224        ClassTemplateSpecializationDecl *SpecDecl
1225          = cast<ClassTemplateSpecializationDecl>(Record->getDecl());
1226        // If the nested name specifier refers to an explicit specialization,
1227        // we don't need a template<> header.
1228        if (SpecDecl->getSpecializationKind() == TSK_ExplicitSpecialization) {
1229          ExplicitSpecializationsInSpecifier.push_back(SpecDecl);
1230          continue;
1231        }
1232      }
1233
1234      TemplateIdsInSpecifier.push_back(SpecType);
1235    }
1236  }
1237
1238  // Reverse the list of template-ids in the scope specifier, so that we can
1239  // more easily match up the template-ids and the template parameter lists.
1240  std::reverse(TemplateIdsInSpecifier.begin(), TemplateIdsInSpecifier.end());
1241
1242  SourceLocation FirstTemplateLoc = DeclStartLoc;
1243  if (NumParamLists)
1244    FirstTemplateLoc = ParamLists[0]->getTemplateLoc();
1245
1246  // Match the template-ids found in the specifier to the template parameter
1247  // lists.
1248  unsigned Idx = 0;
1249  for (unsigned NumTemplateIds = TemplateIdsInSpecifier.size();
1250       Idx != NumTemplateIds; ++Idx) {
1251    QualType TemplateId = QualType(TemplateIdsInSpecifier[Idx], 0);
1252    bool DependentTemplateId = TemplateId->isDependentType();
1253    if (Idx >= NumParamLists) {
1254      // We have a template-id without a corresponding template parameter
1255      // list.
1256      if (DependentTemplateId) {
1257        // FIXME: the location information here isn't great.
1258        Diag(SS.getRange().getBegin(),
1259             diag::err_template_spec_needs_template_parameters)
1260          << TemplateId
1261          << SS.getRange();
1262      } else {
1263        Diag(SS.getRange().getBegin(), diag::err_template_spec_needs_header)
1264          << SS.getRange()
1265          << CodeModificationHint::CreateInsertion(FirstTemplateLoc,
1266                                                   "template<> ");
1267        IsExplicitSpecialization = true;
1268      }
1269      return 0;
1270    }
1271
1272    // Check the template parameter list against its corresponding template-id.
1273    if (DependentTemplateId) {
1274      TemplateDecl *Template
1275        = TemplateIdsInSpecifier[Idx]->getTemplateName().getAsTemplateDecl();
1276
1277      if (ClassTemplateDecl *ClassTemplate
1278            = dyn_cast<ClassTemplateDecl>(Template)) {
1279        TemplateParameterList *ExpectedTemplateParams = 0;
1280        // Is this template-id naming the primary template?
1281        if (Context.hasSameType(TemplateId,
1282                             ClassTemplate->getInjectedClassNameType(Context)))
1283          ExpectedTemplateParams = ClassTemplate->getTemplateParameters();
1284        // ... or a partial specialization?
1285        else if (ClassTemplatePartialSpecializationDecl *PartialSpec
1286                   = ClassTemplate->findPartialSpecialization(TemplateId))
1287          ExpectedTemplateParams = PartialSpec->getTemplateParameters();
1288
1289        if (ExpectedTemplateParams)
1290          TemplateParameterListsAreEqual(ParamLists[Idx],
1291                                         ExpectedTemplateParams,
1292                                         true, TPL_TemplateMatch);
1293      }
1294
1295      CheckTemplateParameterList(ParamLists[Idx], 0, TPC_ClassTemplateMember);
1296    } else if (ParamLists[Idx]->size() > 0)
1297      Diag(ParamLists[Idx]->getTemplateLoc(),
1298           diag::err_template_param_list_matches_nontemplate)
1299        << TemplateId
1300        << ParamLists[Idx]->getSourceRange();
1301    else
1302      IsExplicitSpecialization = true;
1303  }
1304
1305  // If there were at least as many template-ids as there were template
1306  // parameter lists, then there are no template parameter lists remaining for
1307  // the declaration itself.
1308  if (Idx >= NumParamLists)
1309    return 0;
1310
1311  // If there were too many template parameter lists, complain about that now.
1312  if (Idx != NumParamLists - 1) {
1313    while (Idx < NumParamLists - 1) {
1314      bool isExplicitSpecHeader = ParamLists[Idx]->size() == 0;
1315      Diag(ParamLists[Idx]->getTemplateLoc(),
1316           isExplicitSpecHeader? diag::warn_template_spec_extra_headers
1317                               : diag::err_template_spec_extra_headers)
1318        << SourceRange(ParamLists[Idx]->getTemplateLoc(),
1319                       ParamLists[Idx]->getRAngleLoc());
1320
1321      if (isExplicitSpecHeader && !ExplicitSpecializationsInSpecifier.empty()) {
1322        Diag(ExplicitSpecializationsInSpecifier.back()->getLocation(),
1323             diag::note_explicit_template_spec_does_not_need_header)
1324          << ExplicitSpecializationsInSpecifier.back();
1325        ExplicitSpecializationsInSpecifier.pop_back();
1326      }
1327
1328      ++Idx;
1329    }
1330  }
1331
1332  // Return the last template parameter list, which corresponds to the
1333  // entity being declared.
1334  return ParamLists[NumParamLists - 1];
1335}
1336
1337QualType Sema::CheckTemplateIdType(TemplateName Name,
1338                                   SourceLocation TemplateLoc,
1339                              const TemplateArgumentListInfo &TemplateArgs) {
1340  TemplateDecl *Template = Name.getAsTemplateDecl();
1341  if (!Template) {
1342    // The template name does not resolve to a template, so we just
1343    // build a dependent template-id type.
1344    return Context.getTemplateSpecializationType(Name, TemplateArgs);
1345  }
1346
1347  // Check that the template argument list is well-formed for this
1348  // template.
1349  TemplateArgumentListBuilder Converted(Template->getTemplateParameters(),
1350                                        TemplateArgs.size());
1351  if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
1352                                false, Converted))
1353    return QualType();
1354
1355  assert((Converted.structuredSize() ==
1356            Template->getTemplateParameters()->size()) &&
1357         "Converted template argument list is too short!");
1358
1359  QualType CanonType;
1360
1361  if (Name.isDependent() ||
1362      TemplateSpecializationType::anyDependentTemplateArguments(
1363                                                      TemplateArgs)) {
1364    // This class template specialization is a dependent
1365    // type. Therefore, its canonical type is another class template
1366    // specialization type that contains all of the converted
1367    // arguments in canonical form. This ensures that, e.g., A<T> and
1368    // A<T, T> have identical types when A is declared as:
1369    //
1370    //   template<typename T, typename U = T> struct A;
1371    TemplateName CanonName = Context.getCanonicalTemplateName(Name);
1372    CanonType = Context.getTemplateSpecializationType(CanonName,
1373                                                   Converted.getFlatArguments(),
1374                                                   Converted.flatSize());
1375
1376    // FIXME: CanonType is not actually the canonical type, and unfortunately
1377    // it is a TemplateSpecializationType that we will never use again.
1378    // In the future, we need to teach getTemplateSpecializationType to only
1379    // build the canonical type and return that to us.
1380    CanonType = Context.getCanonicalType(CanonType);
1381  } else if (ClassTemplateDecl *ClassTemplate
1382               = dyn_cast<ClassTemplateDecl>(Template)) {
1383    // Find the class template specialization declaration that
1384    // corresponds to these arguments.
1385    llvm::FoldingSetNodeID ID;
1386    ClassTemplateSpecializationDecl::Profile(ID,
1387                                             Converted.getFlatArguments(),
1388                                             Converted.flatSize(),
1389                                             Context);
1390    void *InsertPos = 0;
1391    ClassTemplateSpecializationDecl *Decl
1392      = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
1393    if (!Decl) {
1394      // This is the first time we have referenced this class template
1395      // specialization. Create the canonical declaration and add it to
1396      // the set of specializations.
1397      Decl = ClassTemplateSpecializationDecl::Create(Context,
1398                                    ClassTemplate->getDeclContext(),
1399                                    ClassTemplate->getLocation(),
1400                                    ClassTemplate,
1401                                    Converted, 0);
1402      ClassTemplate->getSpecializations().InsertNode(Decl, InsertPos);
1403      Decl->setLexicalDeclContext(CurContext);
1404    }
1405
1406    CanonType = Context.getTypeDeclType(Decl);
1407  }
1408
1409  // Build the fully-sugared type for this class template
1410  // specialization, which refers back to the class template
1411  // specialization we created or found.
1412  return Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType);
1413}
1414
1415Action::TypeResult
1416Sema::ActOnTemplateIdType(TemplateTy TemplateD, SourceLocation TemplateLoc,
1417                          SourceLocation LAngleLoc,
1418                          ASTTemplateArgsPtr TemplateArgsIn,
1419                          SourceLocation RAngleLoc) {
1420  TemplateName Template = TemplateD.getAsVal<TemplateName>();
1421
1422  // Translate the parser's template argument list in our AST format.
1423  TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
1424  translateTemplateArguments(TemplateArgsIn, TemplateArgs);
1425
1426  QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
1427  TemplateArgsIn.release();
1428
1429  if (Result.isNull())
1430    return true;
1431
1432  TypeSourceInfo *DI = Context.CreateTypeSourceInfo(Result);
1433  TemplateSpecializationTypeLoc TL
1434    = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
1435  TL.setTemplateNameLoc(TemplateLoc);
1436  TL.setLAngleLoc(LAngleLoc);
1437  TL.setRAngleLoc(RAngleLoc);
1438  for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
1439    TL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
1440
1441  return CreateLocInfoType(Result, DI).getAsOpaquePtr();
1442}
1443
1444Sema::TypeResult Sema::ActOnTagTemplateIdType(TypeResult TypeResult,
1445                                              TagUseKind TUK,
1446                                              DeclSpec::TST TagSpec,
1447                                              SourceLocation TagLoc) {
1448  if (TypeResult.isInvalid())
1449    return Sema::TypeResult();
1450
1451  // FIXME: preserve source info, ideally without copying the DI.
1452  TypeSourceInfo *DI;
1453  QualType Type = GetTypeFromParser(TypeResult.get(), &DI);
1454
1455  // Verify the tag specifier.
1456  TagDecl::TagKind TagKind = TagDecl::getTagKindForTypeSpec(TagSpec);
1457
1458  if (const RecordType *RT = Type->getAs<RecordType>()) {
1459    RecordDecl *D = RT->getDecl();
1460
1461    IdentifierInfo *Id = D->getIdentifier();
1462    assert(Id && "templated class must have an identifier");
1463
1464    if (!isAcceptableTagRedeclaration(D, TagKind, TagLoc, *Id)) {
1465      Diag(TagLoc, diag::err_use_with_wrong_tag)
1466        << Type
1467        << CodeModificationHint::CreateReplacement(SourceRange(TagLoc),
1468                                                   D->getKindName());
1469      Diag(D->getLocation(), diag::note_previous_use);
1470    }
1471  }
1472
1473  QualType ElabType = Context.getElaboratedType(Type, TagKind);
1474
1475  return ElabType.getAsOpaquePtr();
1476}
1477
1478Sema::OwningExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,
1479                                                 LookupResult &R,
1480                                                 bool RequiresADL,
1481                                 const TemplateArgumentListInfo &TemplateArgs) {
1482  // FIXME: Can we do any checking at this point? I guess we could check the
1483  // template arguments that we have against the template name, if the template
1484  // name refers to a single template. That's not a terribly common case,
1485  // though.
1486
1487  // These should be filtered out by our callers.
1488  assert(!R.empty() && "empty lookup results when building templateid");
1489  assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
1490
1491  NestedNameSpecifier *Qualifier = 0;
1492  SourceRange QualifierRange;
1493  if (SS.isSet()) {
1494    Qualifier = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
1495    QualifierRange = SS.getRange();
1496  }
1497
1498  bool Dependent
1499    = UnresolvedLookupExpr::ComputeDependence(R.begin(), R.end(),
1500                                              &TemplateArgs);
1501  UnresolvedLookupExpr *ULE
1502    = UnresolvedLookupExpr::Create(Context, Dependent,
1503                                   Qualifier, QualifierRange,
1504                                   R.getLookupName(), R.getNameLoc(),
1505                                   RequiresADL, TemplateArgs);
1506  for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1507    ULE->addDecl(*I);
1508
1509  return Owned(ULE);
1510}
1511
1512// We actually only call this from template instantiation.
1513Sema::OwningExprResult
1514Sema::BuildQualifiedTemplateIdExpr(const CXXScopeSpec &SS,
1515                                   DeclarationName Name,
1516                                   SourceLocation NameLoc,
1517                             const TemplateArgumentListInfo &TemplateArgs) {
1518  DeclContext *DC;
1519  if (!(DC = computeDeclContext(SS, false)) ||
1520      DC->isDependentContext() ||
1521      RequireCompleteDeclContext(SS))
1522    return BuildDependentDeclRefExpr(SS, Name, NameLoc, &TemplateArgs);
1523
1524  LookupResult R(*this, Name, NameLoc, LookupOrdinaryName);
1525  LookupTemplateName(R, (Scope*) 0, SS, QualType(), /*Entering*/ false);
1526
1527  if (R.isAmbiguous())
1528    return ExprError();
1529
1530  if (R.empty()) {
1531    Diag(NameLoc, diag::err_template_kw_refers_to_non_template)
1532      << Name << SS.getRange();
1533    return ExprError();
1534  }
1535
1536  if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>()) {
1537    Diag(NameLoc, diag::err_template_kw_refers_to_class_template)
1538      << (NestedNameSpecifier*) SS.getScopeRep() << Name << SS.getRange();
1539    Diag(Temp->getLocation(), diag::note_referenced_class_template);
1540    return ExprError();
1541  }
1542
1543  return BuildTemplateIdExpr(SS, R, /* ADL */ false, TemplateArgs);
1544}
1545
1546/// \brief Form a dependent template name.
1547///
1548/// This action forms a dependent template name given the template
1549/// name and its (presumably dependent) scope specifier. For
1550/// example, given "MetaFun::template apply", the scope specifier \p
1551/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
1552/// of the "template" keyword, and "apply" is the \p Name.
1553Sema::TemplateTy
1554Sema::ActOnDependentTemplateName(SourceLocation TemplateKWLoc,
1555                                 const CXXScopeSpec &SS,
1556                                 UnqualifiedId &Name,
1557                                 TypeTy *ObjectType,
1558                                 bool EnteringContext) {
1559  if ((ObjectType &&
1560       computeDeclContext(QualType::getFromOpaquePtr(ObjectType))) ||
1561      (SS.isSet() && computeDeclContext(SS, EnteringContext))) {
1562    // C++0x [temp.names]p5:
1563    //   If a name prefixed by the keyword template is not the name of
1564    //   a template, the program is ill-formed. [Note: the keyword
1565    //   template may not be applied to non-template members of class
1566    //   templates. -end note ] [ Note: as is the case with the
1567    //   typename prefix, the template prefix is allowed in cases
1568    //   where it is not strictly necessary; i.e., when the
1569    //   nested-name-specifier or the expression on the left of the ->
1570    //   or . is not dependent on a template-parameter, or the use
1571    //   does not appear in the scope of a template. -end note]
1572    //
1573    // Note: C++03 was more strict here, because it banned the use of
1574    // the "template" keyword prior to a template-name that was not a
1575    // dependent name. C++ DR468 relaxed this requirement (the
1576    // "template" keyword is now permitted). We follow the C++0x
1577    // rules, even in C++03 mode, retroactively applying the DR.
1578    TemplateTy Template;
1579    TemplateNameKind TNK = isTemplateName(0, SS, Name, ObjectType,
1580                                          EnteringContext, Template);
1581    if (TNK == TNK_Non_template) {
1582      Diag(Name.getSourceRange().getBegin(),
1583           diag::err_template_kw_refers_to_non_template)
1584        << GetNameFromUnqualifiedId(Name)
1585        << Name.getSourceRange();
1586      return TemplateTy();
1587    }
1588
1589    return Template;
1590  }
1591
1592  NestedNameSpecifier *Qualifier
1593    = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
1594
1595  switch (Name.getKind()) {
1596  case UnqualifiedId::IK_Identifier:
1597    return TemplateTy::make(Context.getDependentTemplateName(Qualifier,
1598                                                             Name.Identifier));
1599
1600  case UnqualifiedId::IK_OperatorFunctionId:
1601    return TemplateTy::make(Context.getDependentTemplateName(Qualifier,
1602                                             Name.OperatorFunctionId.Operator));
1603
1604  case UnqualifiedId::IK_LiteralOperatorId:
1605    assert(false && "We don't support these; Parse shouldn't have allowed propagation");
1606
1607  default:
1608    break;
1609  }
1610
1611  Diag(Name.getSourceRange().getBegin(),
1612       diag::err_template_kw_refers_to_non_template)
1613    << GetNameFromUnqualifiedId(Name)
1614    << Name.getSourceRange();
1615  return TemplateTy();
1616}
1617
1618bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
1619                                     const TemplateArgumentLoc &AL,
1620                                     TemplateArgumentListBuilder &Converted) {
1621  const TemplateArgument &Arg = AL.getArgument();
1622
1623  // Check template type parameter.
1624  if (Arg.getKind() != TemplateArgument::Type) {
1625    // C++ [temp.arg.type]p1:
1626    //   A template-argument for a template-parameter which is a
1627    //   type shall be a type-id.
1628
1629    // We have a template type parameter but the template argument
1630    // is not a type.
1631    SourceRange SR = AL.getSourceRange();
1632    Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
1633    Diag(Param->getLocation(), diag::note_template_param_here);
1634
1635    return true;
1636  }
1637
1638  if (CheckTemplateArgument(Param, AL.getTypeSourceInfo()))
1639    return true;
1640
1641  // Add the converted template type argument.
1642  Converted.Append(
1643                 TemplateArgument(Context.getCanonicalType(Arg.getAsType())));
1644  return false;
1645}
1646
1647/// \brief Substitute template arguments into the default template argument for
1648/// the given template type parameter.
1649///
1650/// \param SemaRef the semantic analysis object for which we are performing
1651/// the substitution.
1652///
1653/// \param Template the template that we are synthesizing template arguments
1654/// for.
1655///
1656/// \param TemplateLoc the location of the template name that started the
1657/// template-id we are checking.
1658///
1659/// \param RAngleLoc the location of the right angle bracket ('>') that
1660/// terminates the template-id.
1661///
1662/// \param Param the template template parameter whose default we are
1663/// substituting into.
1664///
1665/// \param Converted the list of template arguments provided for template
1666/// parameters that precede \p Param in the template parameter list.
1667///
1668/// \returns the substituted template argument, or NULL if an error occurred.
1669static TypeSourceInfo *
1670SubstDefaultTemplateArgument(Sema &SemaRef,
1671                             TemplateDecl *Template,
1672                             SourceLocation TemplateLoc,
1673                             SourceLocation RAngleLoc,
1674                             TemplateTypeParmDecl *Param,
1675                             TemplateArgumentListBuilder &Converted) {
1676  TypeSourceInfo *ArgType = Param->getDefaultArgumentInfo();
1677
1678  // If the argument type is dependent, instantiate it now based
1679  // on the previously-computed template arguments.
1680  if (ArgType->getType()->isDependentType()) {
1681    TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1682                                      /*TakeArgs=*/false);
1683
1684    MultiLevelTemplateArgumentList AllTemplateArgs
1685      = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1686
1687    Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1688                                     Template, Converted.getFlatArguments(),
1689                                     Converted.flatSize(),
1690                                     SourceRange(TemplateLoc, RAngleLoc));
1691
1692    ArgType = SemaRef.SubstType(ArgType, AllTemplateArgs,
1693                                Param->getDefaultArgumentLoc(),
1694                                Param->getDeclName());
1695  }
1696
1697  return ArgType;
1698}
1699
1700/// \brief Substitute template arguments into the default template argument for
1701/// the given non-type template parameter.
1702///
1703/// \param SemaRef the semantic analysis object for which we are performing
1704/// the substitution.
1705///
1706/// \param Template the template that we are synthesizing template arguments
1707/// for.
1708///
1709/// \param TemplateLoc the location of the template name that started the
1710/// template-id we are checking.
1711///
1712/// \param RAngleLoc the location of the right angle bracket ('>') that
1713/// terminates the template-id.
1714///
1715/// \param Param the non-type template parameter whose default we are
1716/// substituting into.
1717///
1718/// \param Converted the list of template arguments provided for template
1719/// parameters that precede \p Param in the template parameter list.
1720///
1721/// \returns the substituted template argument, or NULL if an error occurred.
1722static Sema::OwningExprResult
1723SubstDefaultTemplateArgument(Sema &SemaRef,
1724                             TemplateDecl *Template,
1725                             SourceLocation TemplateLoc,
1726                             SourceLocation RAngleLoc,
1727                             NonTypeTemplateParmDecl *Param,
1728                             TemplateArgumentListBuilder &Converted) {
1729  TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1730                                    /*TakeArgs=*/false);
1731
1732  MultiLevelTemplateArgumentList AllTemplateArgs
1733    = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1734
1735  Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1736                                   Template, Converted.getFlatArguments(),
1737                                   Converted.flatSize(),
1738                                   SourceRange(TemplateLoc, RAngleLoc));
1739
1740  return SemaRef.SubstExpr(Param->getDefaultArgument(), AllTemplateArgs);
1741}
1742
1743/// \brief Substitute template arguments into the default template argument for
1744/// the given template template parameter.
1745///
1746/// \param SemaRef the semantic analysis object for which we are performing
1747/// the substitution.
1748///
1749/// \param Template the template that we are synthesizing template arguments
1750/// for.
1751///
1752/// \param TemplateLoc the location of the template name that started the
1753/// template-id we are checking.
1754///
1755/// \param RAngleLoc the location of the right angle bracket ('>') that
1756/// terminates the template-id.
1757///
1758/// \param Param the template template parameter whose default we are
1759/// substituting into.
1760///
1761/// \param Converted the list of template arguments provided for template
1762/// parameters that precede \p Param in the template parameter list.
1763///
1764/// \returns the substituted template argument, or NULL if an error occurred.
1765static TemplateName
1766SubstDefaultTemplateArgument(Sema &SemaRef,
1767                             TemplateDecl *Template,
1768                             SourceLocation TemplateLoc,
1769                             SourceLocation RAngleLoc,
1770                             TemplateTemplateParmDecl *Param,
1771                             TemplateArgumentListBuilder &Converted) {
1772  TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1773                                    /*TakeArgs=*/false);
1774
1775  MultiLevelTemplateArgumentList AllTemplateArgs
1776    = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1777
1778  Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1779                                   Template, Converted.getFlatArguments(),
1780                                   Converted.flatSize(),
1781                                   SourceRange(TemplateLoc, RAngleLoc));
1782
1783  return SemaRef.SubstTemplateName(
1784                      Param->getDefaultArgument().getArgument().getAsTemplate(),
1785                              Param->getDefaultArgument().getTemplateNameLoc(),
1786                                   AllTemplateArgs);
1787}
1788
1789/// \brief If the given template parameter has a default template
1790/// argument, substitute into that default template argument and
1791/// return the corresponding template argument.
1792TemplateArgumentLoc
1793Sema::SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
1794                                              SourceLocation TemplateLoc,
1795                                              SourceLocation RAngleLoc,
1796                                              Decl *Param,
1797                                     TemplateArgumentListBuilder &Converted) {
1798  if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
1799    if (!TypeParm->hasDefaultArgument())
1800      return TemplateArgumentLoc();
1801
1802    TypeSourceInfo *DI = SubstDefaultTemplateArgument(*this, Template,
1803                                                      TemplateLoc,
1804                                                      RAngleLoc,
1805                                                      TypeParm,
1806                                                      Converted);
1807    if (DI)
1808      return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
1809
1810    return TemplateArgumentLoc();
1811  }
1812
1813  if (NonTypeTemplateParmDecl *NonTypeParm
1814        = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
1815    if (!NonTypeParm->hasDefaultArgument())
1816      return TemplateArgumentLoc();
1817
1818    OwningExprResult Arg = SubstDefaultTemplateArgument(*this, Template,
1819                                                        TemplateLoc,
1820                                                        RAngleLoc,
1821                                                        NonTypeParm,
1822                                                        Converted);
1823    if (Arg.isInvalid())
1824      return TemplateArgumentLoc();
1825
1826    Expr *ArgE = Arg.takeAs<Expr>();
1827    return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE);
1828  }
1829
1830  TemplateTemplateParmDecl *TempTempParm
1831    = cast<TemplateTemplateParmDecl>(Param);
1832  if (!TempTempParm->hasDefaultArgument())
1833    return TemplateArgumentLoc();
1834
1835  TemplateName TName = SubstDefaultTemplateArgument(*this, Template,
1836                                                    TemplateLoc,
1837                                                    RAngleLoc,
1838                                                    TempTempParm,
1839                                                    Converted);
1840  if (TName.isNull())
1841    return TemplateArgumentLoc();
1842
1843  return TemplateArgumentLoc(TemplateArgument(TName),
1844                TempTempParm->getDefaultArgument().getTemplateQualifierRange(),
1845                TempTempParm->getDefaultArgument().getTemplateNameLoc());
1846}
1847
1848/// \brief Check that the given template argument corresponds to the given
1849/// template parameter.
1850bool Sema::CheckTemplateArgument(NamedDecl *Param,
1851                                 const TemplateArgumentLoc &Arg,
1852                                 TemplateDecl *Template,
1853                                 SourceLocation TemplateLoc,
1854                                 SourceLocation RAngleLoc,
1855                                 TemplateArgumentListBuilder &Converted) {
1856  // Check template type parameters.
1857  if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
1858    return CheckTemplateTypeArgument(TTP, Arg, Converted);
1859
1860  // Check non-type template parameters.
1861  if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
1862    // Do substitution on the type of the non-type template parameter
1863    // with the template arguments we've seen thus far.
1864    QualType NTTPType = NTTP->getType();
1865    if (NTTPType->isDependentType()) {
1866      // Do substitution on the type of the non-type template parameter.
1867      InstantiatingTemplate Inst(*this, TemplateLoc, Template,
1868                                 NTTP, Converted.getFlatArguments(),
1869                                 Converted.flatSize(),
1870                                 SourceRange(TemplateLoc, RAngleLoc));
1871
1872      TemplateArgumentList TemplateArgs(Context, Converted,
1873                                        /*TakeArgs=*/false);
1874      NTTPType = SubstType(NTTPType,
1875                           MultiLevelTemplateArgumentList(TemplateArgs),
1876                           NTTP->getLocation(),
1877                           NTTP->getDeclName());
1878      // If that worked, check the non-type template parameter type
1879      // for validity.
1880      if (!NTTPType.isNull())
1881        NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
1882                                                     NTTP->getLocation());
1883      if (NTTPType.isNull())
1884        return true;
1885    }
1886
1887    switch (Arg.getArgument().getKind()) {
1888    case TemplateArgument::Null:
1889      assert(false && "Should never see a NULL template argument here");
1890      return true;
1891
1892    case TemplateArgument::Expression: {
1893      Expr *E = Arg.getArgument().getAsExpr();
1894      TemplateArgument Result;
1895      if (CheckTemplateArgument(NTTP, NTTPType, E, Result))
1896        return true;
1897
1898      Converted.Append(Result);
1899      break;
1900    }
1901
1902    case TemplateArgument::Declaration:
1903    case TemplateArgument::Integral:
1904      // We've already checked this template argument, so just copy
1905      // it to the list of converted arguments.
1906      Converted.Append(Arg.getArgument());
1907      break;
1908
1909    case TemplateArgument::Template:
1910      // We were given a template template argument. It may not be ill-formed;
1911      // see below.
1912      if (DependentTemplateName *DTN
1913            = Arg.getArgument().getAsTemplate().getAsDependentTemplateName()) {
1914        // We have a template argument such as \c T::template X, which we
1915        // parsed as a template template argument. However, since we now
1916        // know that we need a non-type template argument, convert this
1917        // template name into an expression.
1918        Expr *E = DependentScopeDeclRefExpr::Create(Context,
1919                                                    DTN->getQualifier(),
1920                                               Arg.getTemplateQualifierRange(),
1921                                                    DTN->getIdentifier(),
1922                                                    Arg.getTemplateNameLoc());
1923
1924        TemplateArgument Result;
1925        if (CheckTemplateArgument(NTTP, NTTPType, E, Result))
1926          return true;
1927
1928        Converted.Append(Result);
1929        break;
1930      }
1931
1932      // We have a template argument that actually does refer to a class
1933      // template, template alias, or template template parameter, and
1934      // therefore cannot be a non-type template argument.
1935      Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
1936        << Arg.getSourceRange();
1937
1938      Diag(Param->getLocation(), diag::note_template_param_here);
1939      return true;
1940
1941    case TemplateArgument::Type: {
1942      // We have a non-type template parameter but the template
1943      // argument is a type.
1944
1945      // C++ [temp.arg]p2:
1946      //   In a template-argument, an ambiguity between a type-id and
1947      //   an expression is resolved to a type-id, regardless of the
1948      //   form of the corresponding template-parameter.
1949      //
1950      // We warn specifically about this case, since it can be rather
1951      // confusing for users.
1952      QualType T = Arg.getArgument().getAsType();
1953      SourceRange SR = Arg.getSourceRange();
1954      if (T->isFunctionType())
1955        Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
1956      else
1957        Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
1958      Diag(Param->getLocation(), diag::note_template_param_here);
1959      return true;
1960    }
1961
1962    case TemplateArgument::Pack:
1963      llvm_unreachable("Caller must expand template argument packs");
1964      break;
1965    }
1966
1967    return false;
1968  }
1969
1970
1971  // Check template template parameters.
1972  TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
1973
1974  // Substitute into the template parameter list of the template
1975  // template parameter, since previously-supplied template arguments
1976  // may appear within the template template parameter.
1977  {
1978    // Set up a template instantiation context.
1979    LocalInstantiationScope Scope(*this);
1980    InstantiatingTemplate Inst(*this, TemplateLoc, Template,
1981                               TempParm, Converted.getFlatArguments(),
1982                               Converted.flatSize(),
1983                               SourceRange(TemplateLoc, RAngleLoc));
1984
1985    TemplateArgumentList TemplateArgs(Context, Converted,
1986                                      /*TakeArgs=*/false);
1987    TempParm = cast_or_null<TemplateTemplateParmDecl>(
1988                      SubstDecl(TempParm, CurContext,
1989                                MultiLevelTemplateArgumentList(TemplateArgs)));
1990    if (!TempParm)
1991      return true;
1992
1993    // FIXME: TempParam is leaked.
1994  }
1995
1996  switch (Arg.getArgument().getKind()) {
1997  case TemplateArgument::Null:
1998    assert(false && "Should never see a NULL template argument here");
1999    return true;
2000
2001  case TemplateArgument::Template:
2002    if (CheckTemplateArgument(TempParm, Arg))
2003      return true;
2004
2005    Converted.Append(Arg.getArgument());
2006    break;
2007
2008  case TemplateArgument::Expression:
2009  case TemplateArgument::Type:
2010    // We have a template template parameter but the template
2011    // argument does not refer to a template.
2012    Diag(Arg.getLocation(), diag::err_template_arg_must_be_template);
2013    return true;
2014
2015  case TemplateArgument::Declaration:
2016    llvm_unreachable(
2017                       "Declaration argument with template template parameter");
2018    break;
2019  case TemplateArgument::Integral:
2020    llvm_unreachable(
2021                          "Integral argument with template template parameter");
2022    break;
2023
2024  case TemplateArgument::Pack:
2025    llvm_unreachable("Caller must expand template argument packs");
2026    break;
2027  }
2028
2029  return false;
2030}
2031
2032/// \brief Check that the given template argument list is well-formed
2033/// for specializing the given template.
2034bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
2035                                     SourceLocation TemplateLoc,
2036                                const TemplateArgumentListInfo &TemplateArgs,
2037                                     bool PartialTemplateArgs,
2038                                     TemplateArgumentListBuilder &Converted) {
2039  TemplateParameterList *Params = Template->getTemplateParameters();
2040  unsigned NumParams = Params->size();
2041  unsigned NumArgs = TemplateArgs.size();
2042  bool Invalid = false;
2043
2044  SourceLocation RAngleLoc = TemplateArgs.getRAngleLoc();
2045
2046  bool HasParameterPack =
2047    NumParams > 0 && Params->getParam(NumParams - 1)->isTemplateParameterPack();
2048
2049  if ((NumArgs > NumParams && !HasParameterPack) ||
2050      (NumArgs < Params->getMinRequiredArguments() &&
2051       !PartialTemplateArgs)) {
2052    // FIXME: point at either the first arg beyond what we can handle,
2053    // or the '>', depending on whether we have too many or too few
2054    // arguments.
2055    SourceRange Range;
2056    if (NumArgs > NumParams)
2057      Range = SourceRange(TemplateArgs[NumParams].getLocation(), RAngleLoc);
2058    Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
2059      << (NumArgs > NumParams)
2060      << (isa<ClassTemplateDecl>(Template)? 0 :
2061          isa<FunctionTemplateDecl>(Template)? 1 :
2062          isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
2063      << Template << Range;
2064    Diag(Template->getLocation(), diag::note_template_decl_here)
2065      << Params->getSourceRange();
2066    Invalid = true;
2067  }
2068
2069  // C++ [temp.arg]p1:
2070  //   [...] The type and form of each template-argument specified in
2071  //   a template-id shall match the type and form specified for the
2072  //   corresponding parameter declared by the template in its
2073  //   template-parameter-list.
2074  unsigned ArgIdx = 0;
2075  for (TemplateParameterList::iterator Param = Params->begin(),
2076                                       ParamEnd = Params->end();
2077       Param != ParamEnd; ++Param, ++ArgIdx) {
2078    if (ArgIdx > NumArgs && PartialTemplateArgs)
2079      break;
2080
2081    // If we have a template parameter pack, check every remaining template
2082    // argument against that template parameter pack.
2083    if ((*Param)->isTemplateParameterPack()) {
2084      Converted.BeginPack();
2085      for (; ArgIdx < NumArgs; ++ArgIdx) {
2086        if (CheckTemplateArgument(*Param, TemplateArgs[ArgIdx], Template,
2087                                  TemplateLoc, RAngleLoc, Converted)) {
2088          Invalid = true;
2089          break;
2090        }
2091      }
2092      Converted.EndPack();
2093      continue;
2094    }
2095
2096    if (ArgIdx < NumArgs) {
2097      // Check the template argument we were given.
2098      if (CheckTemplateArgument(*Param, TemplateArgs[ArgIdx], Template,
2099                                TemplateLoc, RAngleLoc, Converted))
2100        return true;
2101
2102      continue;
2103    }
2104
2105    // We have a default template argument that we will use.
2106    TemplateArgumentLoc Arg;
2107
2108    // Retrieve the default template argument from the template
2109    // parameter. For each kind of template parameter, we substitute the
2110    // template arguments provided thus far and any "outer" template arguments
2111    // (when the template parameter was part of a nested template) into
2112    // the default argument.
2113    if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
2114      if (!TTP->hasDefaultArgument()) {
2115        assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2116        break;
2117      }
2118
2119      TypeSourceInfo *ArgType = SubstDefaultTemplateArgument(*this,
2120                                                             Template,
2121                                                             TemplateLoc,
2122                                                             RAngleLoc,
2123                                                             TTP,
2124                                                             Converted);
2125      if (!ArgType)
2126        return true;
2127
2128      Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()),
2129                                ArgType);
2130    } else if (NonTypeTemplateParmDecl *NTTP
2131                 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
2132      if (!NTTP->hasDefaultArgument()) {
2133        assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2134        break;
2135      }
2136
2137      Sema::OwningExprResult E = SubstDefaultTemplateArgument(*this, Template,
2138                                                              TemplateLoc,
2139                                                              RAngleLoc,
2140                                                              NTTP,
2141                                                              Converted);
2142      if (E.isInvalid())
2143        return true;
2144
2145      Expr *Ex = E.takeAs<Expr>();
2146      Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
2147    } else {
2148      TemplateTemplateParmDecl *TempParm
2149        = cast<TemplateTemplateParmDecl>(*Param);
2150
2151      if (!TempParm->hasDefaultArgument()) {
2152        assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2153        break;
2154      }
2155
2156      TemplateName Name = SubstDefaultTemplateArgument(*this, Template,
2157                                                       TemplateLoc,
2158                                                       RAngleLoc,
2159                                                       TempParm,
2160                                                       Converted);
2161      if (Name.isNull())
2162        return true;
2163
2164      Arg = TemplateArgumentLoc(TemplateArgument(Name),
2165                  TempParm->getDefaultArgument().getTemplateQualifierRange(),
2166                  TempParm->getDefaultArgument().getTemplateNameLoc());
2167    }
2168
2169    // Introduce an instantiation record that describes where we are using
2170    // the default template argument.
2171    InstantiatingTemplate Instantiating(*this, RAngleLoc, Template, *Param,
2172                                        Converted.getFlatArguments(),
2173                                        Converted.flatSize(),
2174                                        SourceRange(TemplateLoc, RAngleLoc));
2175
2176    // Check the default template argument.
2177    if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc,
2178                              RAngleLoc, Converted))
2179      return true;
2180  }
2181
2182  return Invalid;
2183}
2184
2185/// \brief Check a template argument against its corresponding
2186/// template type parameter.
2187///
2188/// This routine implements the semantics of C++ [temp.arg.type]. It
2189/// returns true if an error occurred, and false otherwise.
2190bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
2191                                 TypeSourceInfo *ArgInfo) {
2192  assert(ArgInfo && "invalid TypeSourceInfo");
2193  QualType Arg = ArgInfo->getType();
2194
2195  // C++ [temp.arg.type]p2:
2196  //   A local type, a type with no linkage, an unnamed type or a type
2197  //   compounded from any of these types shall not be used as a
2198  //   template-argument for a template type-parameter.
2199  //
2200  // FIXME: Perform the recursive and no-linkage type checks.
2201  const TagType *Tag = 0;
2202  if (const EnumType *EnumT = Arg->getAs<EnumType>())
2203    Tag = EnumT;
2204  else if (const RecordType *RecordT = Arg->getAs<RecordType>())
2205    Tag = RecordT;
2206  if (Tag && Tag->getDecl()->getDeclContext()->isFunctionOrMethod()) {
2207    SourceRange SR = ArgInfo->getTypeLoc().getFullSourceRange();
2208    return Diag(SR.getBegin(), diag::err_template_arg_local_type)
2209      << QualType(Tag, 0) << SR;
2210  } else if (Tag && !Tag->getDecl()->getDeclName() &&
2211           !Tag->getDecl()->getTypedefForAnonDecl()) {
2212    SourceRange SR = ArgInfo->getTypeLoc().getFullSourceRange();
2213    Diag(SR.getBegin(), diag::err_template_arg_unnamed_type) << SR;
2214    Diag(Tag->getDecl()->getLocation(), diag::note_template_unnamed_type_here);
2215    return true;
2216  } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
2217    SourceRange SR = ArgInfo->getTypeLoc().getFullSourceRange();
2218    return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
2219  }
2220
2221  return false;
2222}
2223
2224/// \brief Checks whether the given template argument is the address
2225/// of an object or function according to C++ [temp.arg.nontype]p1.
2226bool Sema::CheckTemplateArgumentAddressOfObjectOrFunction(Expr *Arg,
2227                                                          NamedDecl *&Entity) {
2228  bool Invalid = false;
2229
2230  // See through any implicit casts we added to fix the type.
2231  while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
2232    Arg = Cast->getSubExpr();
2233
2234  // C++0x allows nullptr, and there's no further checking to be done for that.
2235  if (Arg->getType()->isNullPtrType())
2236    return false;
2237
2238  // C++ [temp.arg.nontype]p1:
2239  //
2240  //   A template-argument for a non-type, non-template
2241  //   template-parameter shall be one of: [...]
2242  //
2243  //     -- the address of an object or function with external
2244  //        linkage, including function templates and function
2245  //        template-ids but excluding non-static class members,
2246  //        expressed as & id-expression where the & is optional if
2247  //        the name refers to a function or array, or if the
2248  //        corresponding template-parameter is a reference; or
2249  DeclRefExpr *DRE = 0;
2250
2251  // Ignore (and complain about) any excess parentheses.
2252  while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
2253    if (!Invalid) {
2254      Diag(Arg->getSourceRange().getBegin(),
2255           diag::err_template_arg_extra_parens)
2256        << Arg->getSourceRange();
2257      Invalid = true;
2258    }
2259
2260    Arg = Parens->getSubExpr();
2261  }
2262
2263  if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
2264    if (UnOp->getOpcode() == UnaryOperator::AddrOf)
2265      DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
2266  } else
2267    DRE = dyn_cast<DeclRefExpr>(Arg);
2268
2269  if (!DRE || !isa<ValueDecl>(DRE->getDecl()))
2270    return Diag(Arg->getSourceRange().getBegin(),
2271                diag::err_template_arg_not_object_or_func_form)
2272      << Arg->getSourceRange();
2273
2274  // Cannot refer to non-static data members
2275  if (FieldDecl *Field = dyn_cast<FieldDecl>(DRE->getDecl()))
2276    return Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_field)
2277      << Field << Arg->getSourceRange();
2278
2279  // Cannot refer to non-static member functions
2280  if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(DRE->getDecl()))
2281    if (!Method->isStatic())
2282      return Diag(Arg->getSourceRange().getBegin(),
2283                  diag::err_template_arg_method)
2284        << Method << Arg->getSourceRange();
2285
2286  // Functions must have external linkage.
2287  if (FunctionDecl *Func = dyn_cast<FunctionDecl>(DRE->getDecl())) {
2288    if (Func->getLinkage() != NamedDecl::ExternalLinkage) {
2289      Diag(Arg->getSourceRange().getBegin(),
2290           diag::err_template_arg_function_not_extern)
2291        << Func << Arg->getSourceRange();
2292      Diag(Func->getLocation(), diag::note_template_arg_internal_object)
2293        << true;
2294      return true;
2295    }
2296
2297    // Okay: we've named a function with external linkage.
2298    Entity = Func;
2299    return Invalid;
2300  }
2301
2302  if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
2303    if (Var->getLinkage() != NamedDecl::ExternalLinkage) {
2304      Diag(Arg->getSourceRange().getBegin(),
2305           diag::err_template_arg_object_not_extern)
2306        << Var << Arg->getSourceRange();
2307      Diag(Var->getLocation(), diag::note_template_arg_internal_object)
2308        << true;
2309      return true;
2310    }
2311
2312    // Okay: we've named an object with external linkage
2313    Entity = Var;
2314    return Invalid;
2315  }
2316
2317  // We found something else, but we don't know specifically what it is.
2318  Diag(Arg->getSourceRange().getBegin(),
2319       diag::err_template_arg_not_object_or_func)
2320      << Arg->getSourceRange();
2321  Diag(DRE->getDecl()->getLocation(),
2322       diag::note_template_arg_refers_here);
2323  return true;
2324}
2325
2326/// \brief Checks whether the given template argument is a pointer to
2327/// member constant according to C++ [temp.arg.nontype]p1.
2328bool Sema::CheckTemplateArgumentPointerToMember(Expr *Arg,
2329                                                TemplateArgument &Converted) {
2330  bool Invalid = false;
2331
2332  // See through any implicit casts we added to fix the type.
2333  while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
2334    Arg = Cast->getSubExpr();
2335
2336  // C++0x allows nullptr, and there's no further checking to be done for that.
2337  if (Arg->getType()->isNullPtrType())
2338    return false;
2339
2340  // C++ [temp.arg.nontype]p1:
2341  //
2342  //   A template-argument for a non-type, non-template
2343  //   template-parameter shall be one of: [...]
2344  //
2345  //     -- a pointer to member expressed as described in 5.3.1.
2346  DeclRefExpr *DRE = 0;
2347
2348  // Ignore (and complain about) any excess parentheses.
2349  while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
2350    if (!Invalid) {
2351      Diag(Arg->getSourceRange().getBegin(),
2352           diag::err_template_arg_extra_parens)
2353        << Arg->getSourceRange();
2354      Invalid = true;
2355    }
2356
2357    Arg = Parens->getSubExpr();
2358  }
2359
2360  // A pointer-to-member constant written &Class::member.
2361  if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
2362    if (UnOp->getOpcode() == UnaryOperator::AddrOf) {
2363      DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
2364      if (DRE && !DRE->getQualifier())
2365        DRE = 0;
2366    }
2367  }
2368  // A constant of pointer-to-member type.
2369  else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
2370    if (ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl())) {
2371      if (VD->getType()->isMemberPointerType()) {
2372        if (isa<NonTypeTemplateParmDecl>(VD) ||
2373            (isa<VarDecl>(VD) &&
2374             Context.getCanonicalType(VD->getType()).isConstQualified())) {
2375          if (Arg->isTypeDependent() || Arg->isValueDependent())
2376            Converted = TemplateArgument(Arg->Retain());
2377          else
2378            Converted = TemplateArgument(VD->getCanonicalDecl());
2379          return Invalid;
2380        }
2381      }
2382    }
2383
2384    DRE = 0;
2385  }
2386
2387  if (!DRE)
2388    return Diag(Arg->getSourceRange().getBegin(),
2389                diag::err_template_arg_not_pointer_to_member_form)
2390      << Arg->getSourceRange();
2391
2392  if (isa<FieldDecl>(DRE->getDecl()) || isa<CXXMethodDecl>(DRE->getDecl())) {
2393    assert((isa<FieldDecl>(DRE->getDecl()) ||
2394            !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
2395           "Only non-static member pointers can make it here");
2396
2397    // Okay: this is the address of a non-static member, and therefore
2398    // a member pointer constant.
2399    if (Arg->isTypeDependent() || Arg->isValueDependent())
2400      Converted = TemplateArgument(Arg->Retain());
2401    else
2402      Converted = TemplateArgument(DRE->getDecl()->getCanonicalDecl());
2403    return Invalid;
2404  }
2405
2406  // We found something else, but we don't know specifically what it is.
2407  Diag(Arg->getSourceRange().getBegin(),
2408       diag::err_template_arg_not_pointer_to_member_form)
2409      << Arg->getSourceRange();
2410  Diag(DRE->getDecl()->getLocation(),
2411       diag::note_template_arg_refers_here);
2412  return true;
2413}
2414
2415/// \brief Check a template argument against its corresponding
2416/// non-type template parameter.
2417///
2418/// This routine implements the semantics of C++ [temp.arg.nontype].
2419/// It returns true if an error occurred, and false otherwise. \p
2420/// InstantiatedParamType is the type of the non-type template
2421/// parameter after it has been instantiated.
2422///
2423/// If no error was detected, Converted receives the converted template argument.
2424bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
2425                                 QualType InstantiatedParamType, Expr *&Arg,
2426                                 TemplateArgument &Converted) {
2427  SourceLocation StartLoc = Arg->getSourceRange().getBegin();
2428
2429  // If either the parameter has a dependent type or the argument is
2430  // type-dependent, there's nothing we can check now.
2431  // FIXME: Add template argument to Converted!
2432  if (InstantiatedParamType->isDependentType() || Arg->isTypeDependent()) {
2433    // FIXME: Produce a cloned, canonical expression?
2434    Converted = TemplateArgument(Arg);
2435    return false;
2436  }
2437
2438  // C++ [temp.arg.nontype]p5:
2439  //   The following conversions are performed on each expression used
2440  //   as a non-type template-argument. If a non-type
2441  //   template-argument cannot be converted to the type of the
2442  //   corresponding template-parameter then the program is
2443  //   ill-formed.
2444  //
2445  //     -- for a non-type template-parameter of integral or
2446  //        enumeration type, integral promotions (4.5) and integral
2447  //        conversions (4.7) are applied.
2448  QualType ParamType = InstantiatedParamType;
2449  QualType ArgType = Arg->getType();
2450  if (ParamType->isIntegralType() || ParamType->isEnumeralType()) {
2451    // C++ [temp.arg.nontype]p1:
2452    //   A template-argument for a non-type, non-template
2453    //   template-parameter shall be one of:
2454    //
2455    //     -- an integral constant-expression of integral or enumeration
2456    //        type; or
2457    //     -- the name of a non-type template-parameter; or
2458    SourceLocation NonConstantLoc;
2459    llvm::APSInt Value;
2460    if (!ArgType->isIntegralType() && !ArgType->isEnumeralType()) {
2461      Diag(Arg->getSourceRange().getBegin(),
2462           diag::err_template_arg_not_integral_or_enumeral)
2463        << ArgType << Arg->getSourceRange();
2464      Diag(Param->getLocation(), diag::note_template_param_here);
2465      return true;
2466    } else if (!Arg->isValueDependent() &&
2467               !Arg->isIntegerConstantExpr(Value, Context, &NonConstantLoc)) {
2468      Diag(NonConstantLoc, diag::err_template_arg_not_ice)
2469        << ArgType << Arg->getSourceRange();
2470      return true;
2471    }
2472
2473    // FIXME: We need some way to more easily get the unqualified form
2474    // of the types without going all the way to the
2475    // canonical type.
2476    if (Context.getCanonicalType(ParamType).getCVRQualifiers())
2477      ParamType = Context.getCanonicalType(ParamType).getUnqualifiedType();
2478    if (Context.getCanonicalType(ArgType).getCVRQualifiers())
2479      ArgType = Context.getCanonicalType(ArgType).getUnqualifiedType();
2480
2481    // Try to convert the argument to the parameter's type.
2482    if (Context.hasSameType(ParamType, ArgType)) {
2483      // Okay: no conversion necessary
2484    } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
2485               !ParamType->isEnumeralType()) {
2486      // This is an integral promotion or conversion.
2487      ImpCastExprToType(Arg, ParamType, CastExpr::CK_IntegralCast);
2488    } else {
2489      // We can't perform this conversion.
2490      Diag(Arg->getSourceRange().getBegin(),
2491           diag::err_template_arg_not_convertible)
2492        << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
2493      Diag(Param->getLocation(), diag::note_template_param_here);
2494      return true;
2495    }
2496
2497    QualType IntegerType = Context.getCanonicalType(ParamType);
2498    if (const EnumType *Enum = IntegerType->getAs<EnumType>())
2499      IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
2500
2501    if (!Arg->isValueDependent()) {
2502      // Check that an unsigned parameter does not receive a negative
2503      // value.
2504      if (IntegerType->isUnsignedIntegerType()
2505          && (Value.isSigned() && Value.isNegative())) {
2506        Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_negative)
2507          << Value.toString(10) << Param->getType()
2508          << Arg->getSourceRange();
2509        Diag(Param->getLocation(), diag::note_template_param_here);
2510        return true;
2511      }
2512
2513      // Check that we don't overflow the template parameter type.
2514      unsigned AllowedBits = Context.getTypeSize(IntegerType);
2515      unsigned RequiredBits;
2516      if (IntegerType->isUnsignedIntegerType())
2517        RequiredBits = Value.getActiveBits();
2518      else if (Value.isUnsigned())
2519        RequiredBits = Value.getActiveBits() + 1;
2520      else
2521        RequiredBits = Value.getMinSignedBits();
2522      if (RequiredBits > AllowedBits) {
2523        Diag(Arg->getSourceRange().getBegin(),
2524             diag::err_template_arg_too_large)
2525          << Value.toString(10) << Param->getType()
2526          << Arg->getSourceRange();
2527        Diag(Param->getLocation(), diag::note_template_param_here);
2528        return true;
2529      }
2530
2531      if (Value.getBitWidth() != AllowedBits)
2532        Value.extOrTrunc(AllowedBits);
2533      Value.setIsSigned(IntegerType->isSignedIntegerType());
2534    }
2535
2536    // Add the value of this argument to the list of converted
2537    // arguments. We use the bitwidth and signedness of the template
2538    // parameter.
2539    if (Arg->isValueDependent()) {
2540      // The argument is value-dependent. Create a new
2541      // TemplateArgument with the converted expression.
2542      Converted = TemplateArgument(Arg);
2543      return false;
2544    }
2545
2546    Converted = TemplateArgument(Value,
2547                                 ParamType->isEnumeralType() ? ParamType
2548                                                             : IntegerType);
2549    return false;
2550  }
2551
2552  // Handle pointer-to-function, reference-to-function, and
2553  // pointer-to-member-function all in (roughly) the same way.
2554  if (// -- For a non-type template-parameter of type pointer to
2555      //    function, only the function-to-pointer conversion (4.3) is
2556      //    applied. If the template-argument represents a set of
2557      //    overloaded functions (or a pointer to such), the matching
2558      //    function is selected from the set (13.4).
2559      // In C++0x, any std::nullptr_t value can be converted.
2560      (ParamType->isPointerType() &&
2561       ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
2562      // -- For a non-type template-parameter of type reference to
2563      //    function, no conversions apply. If the template-argument
2564      //    represents a set of overloaded functions, the matching
2565      //    function is selected from the set (13.4).
2566      (ParamType->isReferenceType() &&
2567       ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
2568      // -- For a non-type template-parameter of type pointer to
2569      //    member function, no conversions apply. If the
2570      //    template-argument represents a set of overloaded member
2571      //    functions, the matching member function is selected from
2572      //    the set (13.4).
2573      // Again, C++0x allows a std::nullptr_t value.
2574      (ParamType->isMemberPointerType() &&
2575       ParamType->getAs<MemberPointerType>()->getPointeeType()
2576         ->isFunctionType())) {
2577    if (Context.hasSameUnqualifiedType(ArgType,
2578                                       ParamType.getNonReferenceType())) {
2579      // We don't have to do anything: the types already match.
2580    } else if (ArgType->isNullPtrType() && (ParamType->isPointerType() ||
2581                 ParamType->isMemberPointerType())) {
2582      ArgType = ParamType;
2583      if (ParamType->isMemberPointerType())
2584        ImpCastExprToType(Arg, ParamType, CastExpr::CK_NullToMemberPointer);
2585      else
2586        ImpCastExprToType(Arg, ParamType, CastExpr::CK_BitCast);
2587    } else if (ArgType->isFunctionType() && ParamType->isPointerType()) {
2588      ArgType = Context.getPointerType(ArgType);
2589      ImpCastExprToType(Arg, ArgType, CastExpr::CK_FunctionToPointerDecay);
2590    } else if (FunctionDecl *Fn
2591                 = ResolveAddressOfOverloadedFunction(Arg, ParamType, true)) {
2592      if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
2593        return true;
2594
2595      Arg = FixOverloadedFunctionReference(Arg, Fn);
2596      ArgType = Arg->getType();
2597      if (ArgType->isFunctionType() && ParamType->isPointerType()) {
2598        ArgType = Context.getPointerType(Arg->getType());
2599        ImpCastExprToType(Arg, ArgType, CastExpr::CK_FunctionToPointerDecay);
2600      }
2601    }
2602
2603    if (!Context.hasSameUnqualifiedType(ArgType,
2604                                        ParamType.getNonReferenceType())) {
2605      // We can't perform this conversion.
2606      Diag(Arg->getSourceRange().getBegin(),
2607           diag::err_template_arg_not_convertible)
2608        << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
2609      Diag(Param->getLocation(), diag::note_template_param_here);
2610      return true;
2611    }
2612
2613    if (ParamType->isMemberPointerType())
2614      return CheckTemplateArgumentPointerToMember(Arg, Converted);
2615
2616    NamedDecl *Entity = 0;
2617    if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
2618      return true;
2619
2620    if (Entity)
2621      Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
2622    Converted = TemplateArgument(Entity);
2623    return false;
2624  }
2625
2626  if (ParamType->isPointerType()) {
2627    //   -- for a non-type template-parameter of type pointer to
2628    //      object, qualification conversions (4.4) and the
2629    //      array-to-pointer conversion (4.2) are applied.
2630    // C++0x also allows a value of std::nullptr_t.
2631    assert(ParamType->getAs<PointerType>()->getPointeeType()->isObjectType() &&
2632           "Only object pointers allowed here");
2633
2634    if (ArgType->isNullPtrType()) {
2635      ArgType = ParamType;
2636      ImpCastExprToType(Arg, ParamType, CastExpr::CK_BitCast);
2637    } else if (ArgType->isArrayType()) {
2638      ArgType = Context.getArrayDecayedType(ArgType);
2639      ImpCastExprToType(Arg, ArgType, CastExpr::CK_ArrayToPointerDecay);
2640    }
2641
2642    if (IsQualificationConversion(ArgType, ParamType)) {
2643      ArgType = ParamType;
2644      ImpCastExprToType(Arg, ParamType, CastExpr::CK_NoOp);
2645    }
2646
2647    if (!Context.hasSameUnqualifiedType(ArgType, ParamType)) {
2648      // We can't perform this conversion.
2649      Diag(Arg->getSourceRange().getBegin(),
2650           diag::err_template_arg_not_convertible)
2651        << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
2652      Diag(Param->getLocation(), diag::note_template_param_here);
2653      return true;
2654    }
2655
2656    NamedDecl *Entity = 0;
2657    if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
2658      return true;
2659
2660    if (Entity)
2661      Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
2662    Converted = TemplateArgument(Entity);
2663    return false;
2664  }
2665
2666  if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
2667    //   -- For a non-type template-parameter of type reference to
2668    //      object, no conversions apply. The type referred to by the
2669    //      reference may be more cv-qualified than the (otherwise
2670    //      identical) type of the template-argument. The
2671    //      template-parameter is bound directly to the
2672    //      template-argument, which must be an lvalue.
2673    assert(ParamRefType->getPointeeType()->isObjectType() &&
2674           "Only object references allowed here");
2675
2676    if (!Context.hasSameUnqualifiedType(ParamRefType->getPointeeType(), ArgType)) {
2677      Diag(Arg->getSourceRange().getBegin(),
2678           diag::err_template_arg_no_ref_bind)
2679        << InstantiatedParamType << Arg->getType()
2680        << Arg->getSourceRange();
2681      Diag(Param->getLocation(), diag::note_template_param_here);
2682      return true;
2683    }
2684
2685    unsigned ParamQuals
2686      = Context.getCanonicalType(ParamType).getCVRQualifiers();
2687    unsigned ArgQuals = Context.getCanonicalType(ArgType).getCVRQualifiers();
2688
2689    if ((ParamQuals | ArgQuals) != ParamQuals) {
2690      Diag(Arg->getSourceRange().getBegin(),
2691           diag::err_template_arg_ref_bind_ignores_quals)
2692        << InstantiatedParamType << Arg->getType()
2693        << Arg->getSourceRange();
2694      Diag(Param->getLocation(), diag::note_template_param_here);
2695      return true;
2696    }
2697
2698    NamedDecl *Entity = 0;
2699    if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
2700      return true;
2701
2702    Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
2703    Converted = TemplateArgument(Entity);
2704    return false;
2705  }
2706
2707  //     -- For a non-type template-parameter of type pointer to data
2708  //        member, qualification conversions (4.4) are applied.
2709  // C++0x allows std::nullptr_t values.
2710  assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
2711
2712  if (Context.hasSameUnqualifiedType(ParamType, ArgType)) {
2713    // Types match exactly: nothing more to do here.
2714  } else if (ArgType->isNullPtrType()) {
2715    ImpCastExprToType(Arg, ParamType, CastExpr::CK_NullToMemberPointer);
2716  } else if (IsQualificationConversion(ArgType, ParamType)) {
2717    ImpCastExprToType(Arg, ParamType, CastExpr::CK_NoOp);
2718  } else {
2719    // We can't perform this conversion.
2720    Diag(Arg->getSourceRange().getBegin(),
2721         diag::err_template_arg_not_convertible)
2722      << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
2723    Diag(Param->getLocation(), diag::note_template_param_here);
2724    return true;
2725  }
2726
2727  return CheckTemplateArgumentPointerToMember(Arg, Converted);
2728}
2729
2730/// \brief Check a template argument against its corresponding
2731/// template template parameter.
2732///
2733/// This routine implements the semantics of C++ [temp.arg.template].
2734/// It returns true if an error occurred, and false otherwise.
2735bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
2736                                 const TemplateArgumentLoc &Arg) {
2737  TemplateName Name = Arg.getArgument().getAsTemplate();
2738  TemplateDecl *Template = Name.getAsTemplateDecl();
2739  if (!Template) {
2740    // Any dependent template name is fine.
2741    assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
2742    return false;
2743  }
2744
2745  // C++ [temp.arg.template]p1:
2746  //   A template-argument for a template template-parameter shall be
2747  //   the name of a class template, expressed as id-expression. Only
2748  //   primary class templates are considered when matching the
2749  //   template template argument with the corresponding parameter;
2750  //   partial specializations are not considered even if their
2751  //   parameter lists match that of the template template parameter.
2752  //
2753  // Note that we also allow template template parameters here, which
2754  // will happen when we are dealing with, e.g., class template
2755  // partial specializations.
2756  if (!isa<ClassTemplateDecl>(Template) &&
2757      !isa<TemplateTemplateParmDecl>(Template)) {
2758    assert(isa<FunctionTemplateDecl>(Template) &&
2759           "Only function templates are possible here");
2760    Diag(Arg.getLocation(), diag::err_template_arg_not_class_template);
2761    Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
2762      << Template;
2763  }
2764
2765  return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
2766                                         Param->getTemplateParameters(),
2767                                         true,
2768                                         TPL_TemplateTemplateArgumentMatch,
2769                                         Arg.getLocation());
2770}
2771
2772/// \brief Determine whether the given template parameter lists are
2773/// equivalent.
2774///
2775/// \param New  The new template parameter list, typically written in the
2776/// source code as part of a new template declaration.
2777///
2778/// \param Old  The old template parameter list, typically found via
2779/// name lookup of the template declared with this template parameter
2780/// list.
2781///
2782/// \param Complain  If true, this routine will produce a diagnostic if
2783/// the template parameter lists are not equivalent.
2784///
2785/// \param Kind describes how we are to match the template parameter lists.
2786///
2787/// \param TemplateArgLoc If this source location is valid, then we
2788/// are actually checking the template parameter list of a template
2789/// argument (New) against the template parameter list of its
2790/// corresponding template template parameter (Old). We produce
2791/// slightly different diagnostics in this scenario.
2792///
2793/// \returns True if the template parameter lists are equal, false
2794/// otherwise.
2795bool
2796Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
2797                                     TemplateParameterList *Old,
2798                                     bool Complain,
2799                                     TemplateParameterListEqualKind Kind,
2800                                     SourceLocation TemplateArgLoc) {
2801  if (Old->size() != New->size()) {
2802    if (Complain) {
2803      unsigned NextDiag = diag::err_template_param_list_different_arity;
2804      if (TemplateArgLoc.isValid()) {
2805        Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
2806        NextDiag = diag::note_template_param_list_different_arity;
2807      }
2808      Diag(New->getTemplateLoc(), NextDiag)
2809          << (New->size() > Old->size())
2810          << (Kind != TPL_TemplateMatch)
2811          << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
2812      Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
2813        << (Kind != TPL_TemplateMatch)
2814        << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
2815    }
2816
2817    return false;
2818  }
2819
2820  for (TemplateParameterList::iterator OldParm = Old->begin(),
2821         OldParmEnd = Old->end(), NewParm = New->begin();
2822       OldParm != OldParmEnd; ++OldParm, ++NewParm) {
2823    if ((*OldParm)->getKind() != (*NewParm)->getKind()) {
2824      if (Complain) {
2825        unsigned NextDiag = diag::err_template_param_different_kind;
2826        if (TemplateArgLoc.isValid()) {
2827          Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
2828          NextDiag = diag::note_template_param_different_kind;
2829        }
2830        Diag((*NewParm)->getLocation(), NextDiag)
2831          << (Kind != TPL_TemplateMatch);
2832        Diag((*OldParm)->getLocation(), diag::note_template_prev_declaration)
2833          << (Kind != TPL_TemplateMatch);
2834      }
2835      return false;
2836    }
2837
2838    if (isa<TemplateTypeParmDecl>(*OldParm)) {
2839      // Okay; all template type parameters are equivalent (since we
2840      // know we're at the same index).
2841    } else if (NonTypeTemplateParmDecl *OldNTTP
2842                 = dyn_cast<NonTypeTemplateParmDecl>(*OldParm)) {
2843      // The types of non-type template parameters must agree.
2844      NonTypeTemplateParmDecl *NewNTTP
2845        = cast<NonTypeTemplateParmDecl>(*NewParm);
2846
2847      // If we are matching a template template argument to a template
2848      // template parameter and one of the non-type template parameter types
2849      // is dependent, then we must wait until template instantiation time
2850      // to actually compare the arguments.
2851      if (Kind == TPL_TemplateTemplateArgumentMatch &&
2852          (OldNTTP->getType()->isDependentType() ||
2853           NewNTTP->getType()->isDependentType()))
2854        continue;
2855
2856      if (Context.getCanonicalType(OldNTTP->getType()) !=
2857            Context.getCanonicalType(NewNTTP->getType())) {
2858        if (Complain) {
2859          unsigned NextDiag = diag::err_template_nontype_parm_different_type;
2860          if (TemplateArgLoc.isValid()) {
2861            Diag(TemplateArgLoc,
2862                 diag::err_template_arg_template_params_mismatch);
2863            NextDiag = diag::note_template_nontype_parm_different_type;
2864          }
2865          Diag(NewNTTP->getLocation(), NextDiag)
2866            << NewNTTP->getType()
2867            << (Kind != TPL_TemplateMatch);
2868          Diag(OldNTTP->getLocation(),
2869               diag::note_template_nontype_parm_prev_declaration)
2870            << OldNTTP->getType();
2871        }
2872        return false;
2873      }
2874    } else {
2875      // The template parameter lists of template template
2876      // parameters must agree.
2877      assert(isa<TemplateTemplateParmDecl>(*OldParm) &&
2878             "Only template template parameters handled here");
2879      TemplateTemplateParmDecl *OldTTP
2880        = cast<TemplateTemplateParmDecl>(*OldParm);
2881      TemplateTemplateParmDecl *NewTTP
2882        = cast<TemplateTemplateParmDecl>(*NewParm);
2883      if (!TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
2884                                          OldTTP->getTemplateParameters(),
2885                                          Complain,
2886              (Kind == TPL_TemplateMatch? TPL_TemplateTemplateParmMatch : Kind),
2887                                          TemplateArgLoc))
2888        return false;
2889    }
2890  }
2891
2892  return true;
2893}
2894
2895/// \brief Check whether a template can be declared within this scope.
2896///
2897/// If the template declaration is valid in this scope, returns
2898/// false. Otherwise, issues a diagnostic and returns true.
2899bool
2900Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
2901  // Find the nearest enclosing declaration scope.
2902  while ((S->getFlags() & Scope::DeclScope) == 0 ||
2903         (S->getFlags() & Scope::TemplateParamScope) != 0)
2904    S = S->getParent();
2905
2906  // C++ [temp]p2:
2907  //   A template-declaration can appear only as a namespace scope or
2908  //   class scope declaration.
2909  DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
2910  if (Ctx && isa<LinkageSpecDecl>(Ctx) &&
2911      cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx)
2912    return Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
2913             << TemplateParams->getSourceRange();
2914
2915  while (Ctx && isa<LinkageSpecDecl>(Ctx))
2916    Ctx = Ctx->getParent();
2917
2918  if (Ctx && (Ctx->isFileContext() || Ctx->isRecord()))
2919    return false;
2920
2921  return Diag(TemplateParams->getTemplateLoc(),
2922              diag::err_template_outside_namespace_or_class_scope)
2923    << TemplateParams->getSourceRange();
2924}
2925
2926/// \brief Determine what kind of template specialization the given declaration
2927/// is.
2928static TemplateSpecializationKind getTemplateSpecializationKind(NamedDecl *D) {
2929  if (!D)
2930    return TSK_Undeclared;
2931
2932  if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
2933    return Record->getTemplateSpecializationKind();
2934  if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
2935    return Function->getTemplateSpecializationKind();
2936  if (VarDecl *Var = dyn_cast<VarDecl>(D))
2937    return Var->getTemplateSpecializationKind();
2938
2939  return TSK_Undeclared;
2940}
2941
2942/// \brief Check whether a specialization is well-formed in the current
2943/// context.
2944///
2945/// This routine determines whether a template specialization can be declared
2946/// in the current context (C++ [temp.expl.spec]p2).
2947///
2948/// \param S the semantic analysis object for which this check is being
2949/// performed.
2950///
2951/// \param Specialized the entity being specialized or instantiated, which
2952/// may be a kind of template (class template, function template, etc.) or
2953/// a member of a class template (member function, static data member,
2954/// member class).
2955///
2956/// \param PrevDecl the previous declaration of this entity, if any.
2957///
2958/// \param Loc the location of the explicit specialization or instantiation of
2959/// this entity.
2960///
2961/// \param IsPartialSpecialization whether this is a partial specialization of
2962/// a class template.
2963///
2964/// \returns true if there was an error that we cannot recover from, false
2965/// otherwise.
2966static bool CheckTemplateSpecializationScope(Sema &S,
2967                                             NamedDecl *Specialized,
2968                                             NamedDecl *PrevDecl,
2969                                             SourceLocation Loc,
2970                                             bool IsPartialSpecialization) {
2971  // Keep these "kind" numbers in sync with the %select statements in the
2972  // various diagnostics emitted by this routine.
2973  int EntityKind = 0;
2974  bool isTemplateSpecialization = false;
2975  if (isa<ClassTemplateDecl>(Specialized)) {
2976    EntityKind = IsPartialSpecialization? 1 : 0;
2977    isTemplateSpecialization = true;
2978  } else if (isa<FunctionTemplateDecl>(Specialized)) {
2979    EntityKind = 2;
2980    isTemplateSpecialization = true;
2981  } else if (isa<CXXMethodDecl>(Specialized))
2982    EntityKind = 3;
2983  else if (isa<VarDecl>(Specialized))
2984    EntityKind = 4;
2985  else if (isa<RecordDecl>(Specialized))
2986    EntityKind = 5;
2987  else {
2988    S.Diag(Loc, diag::err_template_spec_unknown_kind);
2989    S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
2990    return true;
2991  }
2992
2993  // C++ [temp.expl.spec]p2:
2994  //   An explicit specialization shall be declared in the namespace
2995  //   of which the template is a member, or, for member templates, in
2996  //   the namespace of which the enclosing class or enclosing class
2997  //   template is a member. An explicit specialization of a member
2998  //   function, member class or static data member of a class
2999  //   template shall be declared in the namespace of which the class
3000  //   template is a member. Such a declaration may also be a
3001  //   definition. If the declaration is not a definition, the
3002  //   specialization may be defined later in the name- space in which
3003  //   the explicit specialization was declared, or in a namespace
3004  //   that encloses the one in which the explicit specialization was
3005  //   declared.
3006  if (S.CurContext->getLookupContext()->isFunctionOrMethod()) {
3007    S.Diag(Loc, diag::err_template_spec_decl_function_scope)
3008      << Specialized;
3009    return true;
3010  }
3011
3012  if (S.CurContext->isRecord() && !IsPartialSpecialization) {
3013    S.Diag(Loc, diag::err_template_spec_decl_class_scope)
3014      << Specialized;
3015    return true;
3016  }
3017
3018  // C++ [temp.class.spec]p6:
3019  //   A class template partial specialization may be declared or redeclared
3020  //   in any namespace scope in which its definition may be defined (14.5.1
3021  //   and 14.5.2).
3022  bool ComplainedAboutScope = false;
3023  DeclContext *SpecializedContext
3024    = Specialized->getDeclContext()->getEnclosingNamespaceContext();
3025  DeclContext *DC = S.CurContext->getEnclosingNamespaceContext();
3026  if ((!PrevDecl ||
3027       getTemplateSpecializationKind(PrevDecl) == TSK_Undeclared ||
3028       getTemplateSpecializationKind(PrevDecl) == TSK_ImplicitInstantiation)){
3029    // There is no prior declaration of this entity, so this
3030    // specialization must be in the same context as the template
3031    // itself.
3032    if (!DC->Equals(SpecializedContext)) {
3033      if (isa<TranslationUnitDecl>(SpecializedContext))
3034        S.Diag(Loc, diag::err_template_spec_decl_out_of_scope_global)
3035        << EntityKind << Specialized;
3036      else if (isa<NamespaceDecl>(SpecializedContext))
3037        S.Diag(Loc, diag::err_template_spec_decl_out_of_scope)
3038        << EntityKind << Specialized
3039        << cast<NamedDecl>(SpecializedContext);
3040
3041      S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
3042      ComplainedAboutScope = true;
3043    }
3044  }
3045
3046  // Make sure that this redeclaration (or definition) occurs in an enclosing
3047  // namespace.
3048  // Note that HandleDeclarator() performs this check for explicit
3049  // specializations of function templates, static data members, and member
3050  // functions, so we skip the check here for those kinds of entities.
3051  // FIXME: HandleDeclarator's diagnostics aren't quite as good, though.
3052  // Should we refactor that check, so that it occurs later?
3053  if (!ComplainedAboutScope && !DC->Encloses(SpecializedContext) &&
3054      !(isa<FunctionTemplateDecl>(Specialized) || isa<VarDecl>(Specialized) ||
3055        isa<FunctionDecl>(Specialized))) {
3056    if (isa<TranslationUnitDecl>(SpecializedContext))
3057      S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
3058        << EntityKind << Specialized;
3059    else if (isa<NamespaceDecl>(SpecializedContext))
3060      S.Diag(Loc, diag::err_template_spec_redecl_out_of_scope)
3061        << EntityKind << Specialized
3062        << cast<NamedDecl>(SpecializedContext);
3063
3064    S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
3065  }
3066
3067  // FIXME: check for specialization-after-instantiation errors and such.
3068
3069  return false;
3070}
3071
3072/// \brief Check the non-type template arguments of a class template
3073/// partial specialization according to C++ [temp.class.spec]p9.
3074///
3075/// \param TemplateParams the template parameters of the primary class
3076/// template.
3077///
3078/// \param TemplateArg the template arguments of the class template
3079/// partial specialization.
3080///
3081/// \param MirrorsPrimaryTemplate will be set true if the class
3082/// template partial specialization arguments are identical to the
3083/// implicit template arguments of the primary template. This is not
3084/// necessarily an error (C++0x), and it is left to the caller to diagnose
3085/// this condition when it is an error.
3086///
3087/// \returns true if there was an error, false otherwise.
3088bool Sema::CheckClassTemplatePartialSpecializationArgs(
3089                                        TemplateParameterList *TemplateParams,
3090                             const TemplateArgumentListBuilder &TemplateArgs,
3091                                        bool &MirrorsPrimaryTemplate) {
3092  // FIXME: the interface to this function will have to change to
3093  // accommodate variadic templates.
3094  MirrorsPrimaryTemplate = true;
3095
3096  const TemplateArgument *ArgList = TemplateArgs.getFlatArguments();
3097
3098  for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
3099    // Determine whether the template argument list of the partial
3100    // specialization is identical to the implicit argument list of
3101    // the primary template. The caller may need to diagnostic this as
3102    // an error per C++ [temp.class.spec]p9b3.
3103    if (MirrorsPrimaryTemplate) {
3104      if (TemplateTypeParmDecl *TTP
3105            = dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(I))) {
3106        if (Context.getCanonicalType(Context.getTypeDeclType(TTP)) !=
3107              Context.getCanonicalType(ArgList[I].getAsType()))
3108          MirrorsPrimaryTemplate = false;
3109      } else if (TemplateTemplateParmDecl *TTP
3110                   = dyn_cast<TemplateTemplateParmDecl>(
3111                                                 TemplateParams->getParam(I))) {
3112        TemplateName Name = ArgList[I].getAsTemplate();
3113        TemplateTemplateParmDecl *ArgDecl
3114          = dyn_cast_or_null<TemplateTemplateParmDecl>(Name.getAsTemplateDecl());
3115        if (!ArgDecl ||
3116            ArgDecl->getIndex() != TTP->getIndex() ||
3117            ArgDecl->getDepth() != TTP->getDepth())
3118          MirrorsPrimaryTemplate = false;
3119      }
3120    }
3121
3122    NonTypeTemplateParmDecl *Param
3123      = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
3124    if (!Param) {
3125      continue;
3126    }
3127
3128    Expr *ArgExpr = ArgList[I].getAsExpr();
3129    if (!ArgExpr) {
3130      MirrorsPrimaryTemplate = false;
3131      continue;
3132    }
3133
3134    // C++ [temp.class.spec]p8:
3135    //   A non-type argument is non-specialized if it is the name of a
3136    //   non-type parameter. All other non-type arguments are
3137    //   specialized.
3138    //
3139    // Below, we check the two conditions that only apply to
3140    // specialized non-type arguments, so skip any non-specialized
3141    // arguments.
3142    if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
3143      if (NonTypeTemplateParmDecl *NTTP
3144            = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl())) {
3145        if (MirrorsPrimaryTemplate &&
3146            (Param->getIndex() != NTTP->getIndex() ||
3147             Param->getDepth() != NTTP->getDepth()))
3148          MirrorsPrimaryTemplate = false;
3149
3150        continue;
3151      }
3152
3153    // C++ [temp.class.spec]p9:
3154    //   Within the argument list of a class template partial
3155    //   specialization, the following restrictions apply:
3156    //     -- A partially specialized non-type argument expression
3157    //        shall not involve a template parameter of the partial
3158    //        specialization except when the argument expression is a
3159    //        simple identifier.
3160    if (ArgExpr->isTypeDependent() || ArgExpr->isValueDependent()) {
3161      Diag(ArgExpr->getLocStart(),
3162           diag::err_dependent_non_type_arg_in_partial_spec)
3163        << ArgExpr->getSourceRange();
3164      return true;
3165    }
3166
3167    //     -- The type of a template parameter corresponding to a
3168    //        specialized non-type argument shall not be dependent on a
3169    //        parameter of the specialization.
3170    if (Param->getType()->isDependentType()) {
3171      Diag(ArgExpr->getLocStart(),
3172           diag::err_dependent_typed_non_type_arg_in_partial_spec)
3173        << Param->getType()
3174        << ArgExpr->getSourceRange();
3175      Diag(Param->getLocation(), diag::note_template_param_here);
3176      return true;
3177    }
3178
3179    MirrorsPrimaryTemplate = false;
3180  }
3181
3182  return false;
3183}
3184
3185Sema::DeclResult
3186Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec,
3187                                       TagUseKind TUK,
3188                                       SourceLocation KWLoc,
3189                                       const CXXScopeSpec &SS,
3190                                       TemplateTy TemplateD,
3191                                       SourceLocation TemplateNameLoc,
3192                                       SourceLocation LAngleLoc,
3193                                       ASTTemplateArgsPtr TemplateArgsIn,
3194                                       SourceLocation RAngleLoc,
3195                                       AttributeList *Attr,
3196                               MultiTemplateParamsArg TemplateParameterLists) {
3197  assert(TUK != TUK_Reference && "References are not specializations");
3198
3199  // Find the class template we're specializing
3200  TemplateName Name = TemplateD.getAsVal<TemplateName>();
3201  ClassTemplateDecl *ClassTemplate
3202    = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
3203
3204  if (!ClassTemplate) {
3205    Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
3206      << (Name.getAsTemplateDecl() &&
3207          isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
3208    return true;
3209  }
3210
3211  bool isExplicitSpecialization = false;
3212  bool isPartialSpecialization = false;
3213
3214  // Check the validity of the template headers that introduce this
3215  // template.
3216  // FIXME: We probably shouldn't complain about these headers for
3217  // friend declarations.
3218  TemplateParameterList *TemplateParams
3219    = MatchTemplateParametersToScopeSpecifier(TemplateNameLoc, SS,
3220                        (TemplateParameterList**)TemplateParameterLists.get(),
3221                                              TemplateParameterLists.size(),
3222                                              isExplicitSpecialization);
3223  if (TemplateParams && TemplateParams->size() > 0) {
3224    isPartialSpecialization = true;
3225
3226    // C++ [temp.class.spec]p10:
3227    //   The template parameter list of a specialization shall not
3228    //   contain default template argument values.
3229    for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
3230      Decl *Param = TemplateParams->getParam(I);
3231      if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
3232        if (TTP->hasDefaultArgument()) {
3233          Diag(TTP->getDefaultArgumentLoc(),
3234               diag::err_default_arg_in_partial_spec);
3235          TTP->removeDefaultArgument();
3236        }
3237      } else if (NonTypeTemplateParmDecl *NTTP
3238                   = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
3239        if (Expr *DefArg = NTTP->getDefaultArgument()) {
3240          Diag(NTTP->getDefaultArgumentLoc(),
3241               diag::err_default_arg_in_partial_spec)
3242            << DefArg->getSourceRange();
3243          NTTP->setDefaultArgument(0);
3244          DefArg->Destroy(Context);
3245        }
3246      } else {
3247        TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
3248        if (TTP->hasDefaultArgument()) {
3249          Diag(TTP->getDefaultArgument().getLocation(),
3250               diag::err_default_arg_in_partial_spec)
3251            << TTP->getDefaultArgument().getSourceRange();
3252          TTP->setDefaultArgument(TemplateArgumentLoc());
3253        }
3254      }
3255    }
3256  } else if (TemplateParams) {
3257    if (TUK == TUK_Friend)
3258      Diag(KWLoc, diag::err_template_spec_friend)
3259        << CodeModificationHint::CreateRemoval(
3260                                SourceRange(TemplateParams->getTemplateLoc(),
3261                                            TemplateParams->getRAngleLoc()))
3262        << SourceRange(LAngleLoc, RAngleLoc);
3263    else
3264      isExplicitSpecialization = true;
3265  } else if (TUK != TUK_Friend) {
3266    Diag(KWLoc, diag::err_template_spec_needs_header)
3267      << CodeModificationHint::CreateInsertion(KWLoc, "template<> ");
3268    isExplicitSpecialization = true;
3269  }
3270
3271  // Check that the specialization uses the same tag kind as the
3272  // original template.
3273  TagDecl::TagKind Kind;
3274  switch (TagSpec) {
3275  default: assert(0 && "Unknown tag type!");
3276  case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
3277  case DeclSpec::TST_union:  Kind = TagDecl::TK_union; break;
3278  case DeclSpec::TST_class:  Kind = TagDecl::TK_class; break;
3279  }
3280  if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
3281                                    Kind, KWLoc,
3282                                    *ClassTemplate->getIdentifier())) {
3283    Diag(KWLoc, diag::err_use_with_wrong_tag)
3284      << ClassTemplate
3285      << CodeModificationHint::CreateReplacement(KWLoc,
3286                            ClassTemplate->getTemplatedDecl()->getKindName());
3287    Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
3288         diag::note_previous_use);
3289    Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
3290  }
3291
3292  // Translate the parser's template argument list in our AST format.
3293  TemplateArgumentListInfo TemplateArgs;
3294  TemplateArgs.setLAngleLoc(LAngleLoc);
3295  TemplateArgs.setRAngleLoc(RAngleLoc);
3296  translateTemplateArguments(TemplateArgsIn, TemplateArgs);
3297
3298  // Check that the template argument list is well-formed for this
3299  // template.
3300  TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
3301                                        TemplateArgs.size());
3302  if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
3303                                TemplateArgs, false, Converted))
3304    return true;
3305
3306  assert((Converted.structuredSize() ==
3307            ClassTemplate->getTemplateParameters()->size()) &&
3308         "Converted template argument list is too short!");
3309
3310  // Find the class template (partial) specialization declaration that
3311  // corresponds to these arguments.
3312  llvm::FoldingSetNodeID ID;
3313  if (isPartialSpecialization) {
3314    bool MirrorsPrimaryTemplate;
3315    if (CheckClassTemplatePartialSpecializationArgs(
3316                                         ClassTemplate->getTemplateParameters(),
3317                                         Converted, MirrorsPrimaryTemplate))
3318      return true;
3319
3320    if (MirrorsPrimaryTemplate) {
3321      // C++ [temp.class.spec]p9b3:
3322      //
3323      //   -- The argument list of the specialization shall not be identical
3324      //      to the implicit argument list of the primary template.
3325      Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
3326        << (TUK == TUK_Definition)
3327        << CodeModificationHint::CreateRemoval(SourceRange(LAngleLoc,
3328                                                           RAngleLoc));
3329      return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
3330                                ClassTemplate->getIdentifier(),
3331                                TemplateNameLoc,
3332                                Attr,
3333                                TemplateParams,
3334                                AS_none);
3335    }
3336
3337    // FIXME: Diagnose friend partial specializations
3338
3339    // FIXME: Template parameter list matters, too
3340    ClassTemplatePartialSpecializationDecl::Profile(ID,
3341                                                   Converted.getFlatArguments(),
3342                                                   Converted.flatSize(),
3343                                                    Context);
3344  } else
3345    ClassTemplateSpecializationDecl::Profile(ID,
3346                                             Converted.getFlatArguments(),
3347                                             Converted.flatSize(),
3348                                             Context);
3349  void *InsertPos = 0;
3350  ClassTemplateSpecializationDecl *PrevDecl = 0;
3351
3352  if (isPartialSpecialization)
3353    PrevDecl
3354      = ClassTemplate->getPartialSpecializations().FindNodeOrInsertPos(ID,
3355                                                                    InsertPos);
3356  else
3357    PrevDecl
3358      = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
3359
3360  ClassTemplateSpecializationDecl *Specialization = 0;
3361
3362  // Check whether we can declare a class template specialization in
3363  // the current scope.
3364  if (TUK != TUK_Friend &&
3365      CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
3366                                       TemplateNameLoc,
3367                                       isPartialSpecialization))
3368    return true;
3369
3370  // The canonical type
3371  QualType CanonType;
3372  if (PrevDecl &&
3373      (PrevDecl->getSpecializationKind() == TSK_Undeclared ||
3374       TUK == TUK_Friend)) {
3375    // Since the only prior class template specialization with these
3376    // arguments was referenced but not declared, or we're only
3377    // referencing this specialization as a friend, reuse that
3378    // declaration node as our own, updating its source location to
3379    // reflect our new declaration.
3380    Specialization = PrevDecl;
3381    Specialization->setLocation(TemplateNameLoc);
3382    PrevDecl = 0;
3383    CanonType = Context.getTypeDeclType(Specialization);
3384  } else if (isPartialSpecialization) {
3385    // Build the canonical type that describes the converted template
3386    // arguments of the class template partial specialization.
3387    CanonType = Context.getTemplateSpecializationType(
3388                                                  TemplateName(ClassTemplate),
3389                                                  Converted.getFlatArguments(),
3390                                                  Converted.flatSize());
3391
3392    // Create a new class template partial specialization declaration node.
3393    ClassTemplatePartialSpecializationDecl *PrevPartial
3394      = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
3395    ClassTemplatePartialSpecializationDecl *Partial
3396      = ClassTemplatePartialSpecializationDecl::Create(Context,
3397                                             ClassTemplate->getDeclContext(),
3398                                                       TemplateNameLoc,
3399                                                       TemplateParams,
3400                                                       ClassTemplate,
3401                                                       Converted,
3402                                                       TemplateArgs,
3403                                                       PrevPartial);
3404
3405    if (PrevPartial) {
3406      ClassTemplate->getPartialSpecializations().RemoveNode(PrevPartial);
3407      ClassTemplate->getPartialSpecializations().GetOrInsertNode(Partial);
3408    } else {
3409      ClassTemplate->getPartialSpecializations().InsertNode(Partial, InsertPos);
3410    }
3411    Specialization = Partial;
3412
3413    // If we are providing an explicit specialization of a member class
3414    // template specialization, make a note of that.
3415    if (PrevPartial && PrevPartial->getInstantiatedFromMember())
3416      PrevPartial->setMemberSpecialization();
3417
3418    // Check that all of the template parameters of the class template
3419    // partial specialization are deducible from the template
3420    // arguments. If not, this class template partial specialization
3421    // will never be used.
3422    llvm::SmallVector<bool, 8> DeducibleParams;
3423    DeducibleParams.resize(TemplateParams->size());
3424    MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
3425                               TemplateParams->getDepth(),
3426                               DeducibleParams);
3427    unsigned NumNonDeducible = 0;
3428    for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I)
3429      if (!DeducibleParams[I])
3430        ++NumNonDeducible;
3431
3432    if (NumNonDeducible) {
3433      Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
3434        << (NumNonDeducible > 1)
3435        << SourceRange(TemplateNameLoc, RAngleLoc);
3436      for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
3437        if (!DeducibleParams[I]) {
3438          NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
3439          if (Param->getDeclName())
3440            Diag(Param->getLocation(),
3441                 diag::note_partial_spec_unused_parameter)
3442              << Param->getDeclName();
3443          else
3444            Diag(Param->getLocation(),
3445                 diag::note_partial_spec_unused_parameter)
3446              << std::string("<anonymous>");
3447        }
3448      }
3449    }
3450  } else {
3451    // Create a new class template specialization declaration node for
3452    // this explicit specialization or friend declaration.
3453    Specialization
3454      = ClassTemplateSpecializationDecl::Create(Context,
3455                                             ClassTemplate->getDeclContext(),
3456                                                TemplateNameLoc,
3457                                                ClassTemplate,
3458                                                Converted,
3459                                                PrevDecl);
3460
3461    if (PrevDecl) {
3462      ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
3463      ClassTemplate->getSpecializations().GetOrInsertNode(Specialization);
3464    } else {
3465      ClassTemplate->getSpecializations().InsertNode(Specialization,
3466                                                     InsertPos);
3467    }
3468
3469    CanonType = Context.getTypeDeclType(Specialization);
3470  }
3471
3472  // C++ [temp.expl.spec]p6:
3473  //   If a template, a member template or the member of a class template is
3474  //   explicitly specialized then that specialization shall be declared
3475  //   before the first use of that specialization that would cause an implicit
3476  //   instantiation to take place, in every translation unit in which such a
3477  //   use occurs; no diagnostic is required.
3478  if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
3479    SourceRange Range(TemplateNameLoc, RAngleLoc);
3480    Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
3481      << Context.getTypeDeclType(Specialization) << Range;
3482
3483    Diag(PrevDecl->getPointOfInstantiation(),
3484         diag::note_instantiation_required_here)
3485      << (PrevDecl->getTemplateSpecializationKind()
3486                                                != TSK_ImplicitInstantiation);
3487    return true;
3488  }
3489
3490  // If this is not a friend, note that this is an explicit specialization.
3491  if (TUK != TUK_Friend)
3492    Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
3493
3494  // Check that this isn't a redefinition of this specialization.
3495  if (TUK == TUK_Definition) {
3496    if (RecordDecl *Def = Specialization->getDefinition(Context)) {
3497      SourceRange Range(TemplateNameLoc, RAngleLoc);
3498      Diag(TemplateNameLoc, diag::err_redefinition)
3499        << Context.getTypeDeclType(Specialization) << Range;
3500      Diag(Def->getLocation(), diag::note_previous_definition);
3501      Specialization->setInvalidDecl();
3502      return true;
3503    }
3504  }
3505
3506  // Build the fully-sugared type for this class template
3507  // specialization as the user wrote in the specialization
3508  // itself. This means that we'll pretty-print the type retrieved
3509  // from the specialization's declaration the way that the user
3510  // actually wrote the specialization, rather than formatting the
3511  // name based on the "canonical" representation used to store the
3512  // template arguments in the specialization.
3513  QualType WrittenTy
3514    = Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType);
3515  if (TUK != TUK_Friend)
3516    Specialization->setTypeAsWritten(WrittenTy);
3517  TemplateArgsIn.release();
3518
3519  // C++ [temp.expl.spec]p9:
3520  //   A template explicit specialization is in the scope of the
3521  //   namespace in which the template was defined.
3522  //
3523  // We actually implement this paragraph where we set the semantic
3524  // context (in the creation of the ClassTemplateSpecializationDecl),
3525  // but we also maintain the lexical context where the actual
3526  // definition occurs.
3527  Specialization->setLexicalDeclContext(CurContext);
3528
3529  // We may be starting the definition of this specialization.
3530  if (TUK == TUK_Definition)
3531    Specialization->startDefinition();
3532
3533  if (TUK == TUK_Friend) {
3534    FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
3535                                            TemplateNameLoc,
3536                                            WrittenTy.getTypePtr(),
3537                                            /*FIXME:*/KWLoc);
3538    Friend->setAccess(AS_public);
3539    CurContext->addDecl(Friend);
3540  } else {
3541    // Add the specialization into its lexical context, so that it can
3542    // be seen when iterating through the list of declarations in that
3543    // context. However, specializations are not found by name lookup.
3544    CurContext->addDecl(Specialization);
3545  }
3546  return DeclPtrTy::make(Specialization);
3547}
3548
3549Sema::DeclPtrTy
3550Sema::ActOnTemplateDeclarator(Scope *S,
3551                              MultiTemplateParamsArg TemplateParameterLists,
3552                              Declarator &D) {
3553  return HandleDeclarator(S, D, move(TemplateParameterLists), false);
3554}
3555
3556Sema::DeclPtrTy
3557Sema::ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope,
3558                               MultiTemplateParamsArg TemplateParameterLists,
3559                                      Declarator &D) {
3560  assert(getCurFunctionDecl() == 0 && "Function parsing confused");
3561  assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
3562         "Not a function declarator!");
3563  DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
3564
3565  if (FTI.hasPrototype) {
3566    // FIXME: Diagnose arguments without names in C.
3567  }
3568
3569  Scope *ParentScope = FnBodyScope->getParent();
3570
3571  DeclPtrTy DP = HandleDeclarator(ParentScope, D,
3572                                  move(TemplateParameterLists),
3573                                  /*IsFunctionDefinition=*/true);
3574  if (FunctionTemplateDecl *FunctionTemplate
3575        = dyn_cast_or_null<FunctionTemplateDecl>(DP.getAs<Decl>()))
3576    return ActOnStartOfFunctionDef(FnBodyScope,
3577                      DeclPtrTy::make(FunctionTemplate->getTemplatedDecl()));
3578  if (FunctionDecl *Function = dyn_cast_or_null<FunctionDecl>(DP.getAs<Decl>()))
3579    return ActOnStartOfFunctionDef(FnBodyScope, DeclPtrTy::make(Function));
3580  return DeclPtrTy();
3581}
3582
3583/// \brief Diagnose cases where we have an explicit template specialization
3584/// before/after an explicit template instantiation, producing diagnostics
3585/// for those cases where they are required and determining whether the
3586/// new specialization/instantiation will have any effect.
3587///
3588/// \param NewLoc the location of the new explicit specialization or
3589/// instantiation.
3590///
3591/// \param NewTSK the kind of the new explicit specialization or instantiation.
3592///
3593/// \param PrevDecl the previous declaration of the entity.
3594///
3595/// \param PrevTSK the kind of the old explicit specialization or instantiatin.
3596///
3597/// \param PrevPointOfInstantiation if valid, indicates where the previus
3598/// declaration was instantiated (either implicitly or explicitly).
3599///
3600/// \param SuppressNew will be set to true to indicate that the new
3601/// specialization or instantiation has no effect and should be ignored.
3602///
3603/// \returns true if there was an error that should prevent the introduction of
3604/// the new declaration into the AST, false otherwise.
3605bool
3606Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
3607                                             TemplateSpecializationKind NewTSK,
3608                                             NamedDecl *PrevDecl,
3609                                             TemplateSpecializationKind PrevTSK,
3610                                        SourceLocation PrevPointOfInstantiation,
3611                                             bool &SuppressNew) {
3612  SuppressNew = false;
3613
3614  switch (NewTSK) {
3615  case TSK_Undeclared:
3616  case TSK_ImplicitInstantiation:
3617    assert(false && "Don't check implicit instantiations here");
3618    return false;
3619
3620  case TSK_ExplicitSpecialization:
3621    switch (PrevTSK) {
3622    case TSK_Undeclared:
3623    case TSK_ExplicitSpecialization:
3624      // Okay, we're just specializing something that is either already
3625      // explicitly specialized or has merely been mentioned without any
3626      // instantiation.
3627      return false;
3628
3629    case TSK_ImplicitInstantiation:
3630      if (PrevPointOfInstantiation.isInvalid()) {
3631        // The declaration itself has not actually been instantiated, so it is
3632        // still okay to specialize it.
3633        return false;
3634      }
3635      // Fall through
3636
3637    case TSK_ExplicitInstantiationDeclaration:
3638    case TSK_ExplicitInstantiationDefinition:
3639      assert((PrevTSK == TSK_ImplicitInstantiation ||
3640              PrevPointOfInstantiation.isValid()) &&
3641             "Explicit instantiation without point of instantiation?");
3642
3643      // C++ [temp.expl.spec]p6:
3644      //   If a template, a member template or the member of a class template
3645      //   is explicitly specialized then that specialization shall be declared
3646      //   before the first use of that specialization that would cause an
3647      //   implicit instantiation to take place, in every translation unit in
3648      //   which such a use occurs; no diagnostic is required.
3649      Diag(NewLoc, diag::err_specialization_after_instantiation)
3650        << PrevDecl;
3651      Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
3652        << (PrevTSK != TSK_ImplicitInstantiation);
3653
3654      return true;
3655    }
3656    break;
3657
3658  case TSK_ExplicitInstantiationDeclaration:
3659    switch (PrevTSK) {
3660    case TSK_ExplicitInstantiationDeclaration:
3661      // This explicit instantiation declaration is redundant (that's okay).
3662      SuppressNew = true;
3663      return false;
3664
3665    case TSK_Undeclared:
3666    case TSK_ImplicitInstantiation:
3667      // We're explicitly instantiating something that may have already been
3668      // implicitly instantiated; that's fine.
3669      return false;
3670
3671    case TSK_ExplicitSpecialization:
3672      // C++0x [temp.explicit]p4:
3673      //   For a given set of template parameters, if an explicit instantiation
3674      //   of a template appears after a declaration of an explicit
3675      //   specialization for that template, the explicit instantiation has no
3676      //   effect.
3677      return false;
3678
3679    case TSK_ExplicitInstantiationDefinition:
3680      // C++0x [temp.explicit]p10:
3681      //   If an entity is the subject of both an explicit instantiation
3682      //   declaration and an explicit instantiation definition in the same
3683      //   translation unit, the definition shall follow the declaration.
3684      Diag(NewLoc,
3685           diag::err_explicit_instantiation_declaration_after_definition);
3686      Diag(PrevPointOfInstantiation,
3687           diag::note_explicit_instantiation_definition_here);
3688      assert(PrevPointOfInstantiation.isValid() &&
3689             "Explicit instantiation without point of instantiation?");
3690      SuppressNew = true;
3691      return false;
3692    }
3693    break;
3694
3695  case TSK_ExplicitInstantiationDefinition:
3696    switch (PrevTSK) {
3697    case TSK_Undeclared:
3698    case TSK_ImplicitInstantiation:
3699      // We're explicitly instantiating something that may have already been
3700      // implicitly instantiated; that's fine.
3701      return false;
3702
3703    case TSK_ExplicitSpecialization:
3704      // C++ DR 259, C++0x [temp.explicit]p4:
3705      //   For a given set of template parameters, if an explicit
3706      //   instantiation of a template appears after a declaration of
3707      //   an explicit specialization for that template, the explicit
3708      //   instantiation has no effect.
3709      //
3710      // In C++98/03 mode, we only give an extension warning here, because it
3711      // is not not harmful to try to explicitly instantiate something that
3712      // has been explicitly specialized.
3713      if (!getLangOptions().CPlusPlus0x) {
3714        Diag(NewLoc, diag::ext_explicit_instantiation_after_specialization)
3715          << PrevDecl;
3716        Diag(PrevDecl->getLocation(),
3717             diag::note_previous_template_specialization);
3718      }
3719      SuppressNew = true;
3720      return false;
3721
3722    case TSK_ExplicitInstantiationDeclaration:
3723      // We're explicity instantiating a definition for something for which we
3724      // were previously asked to suppress instantiations. That's fine.
3725      return false;
3726
3727    case TSK_ExplicitInstantiationDefinition:
3728      // C++0x [temp.spec]p5:
3729      //   For a given template and a given set of template-arguments,
3730      //     - an explicit instantiation definition shall appear at most once
3731      //       in a program,
3732      Diag(NewLoc, diag::err_explicit_instantiation_duplicate)
3733        << PrevDecl;
3734      Diag(PrevPointOfInstantiation,
3735           diag::note_previous_explicit_instantiation);
3736      SuppressNew = true;
3737      return false;
3738    }
3739    break;
3740  }
3741
3742  assert(false && "Missing specialization/instantiation case?");
3743
3744  return false;
3745}
3746
3747/// \brief Perform semantic analysis for the given function template
3748/// specialization.
3749///
3750/// This routine performs all of the semantic analysis required for an
3751/// explicit function template specialization. On successful completion,
3752/// the function declaration \p FD will become a function template
3753/// specialization.
3754///
3755/// \param FD the function declaration, which will be updated to become a
3756/// function template specialization.
3757///
3758/// \param HasExplicitTemplateArgs whether any template arguments were
3759/// explicitly provided.
3760///
3761/// \param LAngleLoc the location of the left angle bracket ('<'), if
3762/// template arguments were explicitly provided.
3763///
3764/// \param ExplicitTemplateArgs the explicitly-provided template arguments,
3765/// if any.
3766///
3767/// \param NumExplicitTemplateArgs the number of explicitly-provided template
3768/// arguments. This number may be zero even when HasExplicitTemplateArgs is
3769/// true as in, e.g., \c void sort<>(char*, char*);
3770///
3771/// \param RAngleLoc the location of the right angle bracket ('>'), if
3772/// template arguments were explicitly provided.
3773///
3774/// \param PrevDecl the set of declarations that
3775bool
3776Sema::CheckFunctionTemplateSpecialization(FunctionDecl *FD,
3777                        const TemplateArgumentListInfo *ExplicitTemplateArgs,
3778                                          LookupResult &Previous) {
3779  // The set of function template specializations that could match this
3780  // explicit function template specialization.
3781  typedef llvm::SmallVector<FunctionDecl *, 8> CandidateSet;
3782  CandidateSet Candidates;
3783
3784  DeclContext *FDLookupContext = FD->getDeclContext()->getLookupContext();
3785  for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
3786         I != E; ++I) {
3787    NamedDecl *Ovl = (*I)->getUnderlyingDecl();
3788    if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
3789      // Only consider templates found within the same semantic lookup scope as
3790      // FD.
3791      if (!FDLookupContext->Equals(Ovl->getDeclContext()->getLookupContext()))
3792        continue;
3793
3794      // C++ [temp.expl.spec]p11:
3795      //   A trailing template-argument can be left unspecified in the
3796      //   template-id naming an explicit function template specialization
3797      //   provided it can be deduced from the function argument type.
3798      // Perform template argument deduction to determine whether we may be
3799      // specializing this template.
3800      // FIXME: It is somewhat wasteful to build
3801      TemplateDeductionInfo Info(Context);
3802      FunctionDecl *Specialization = 0;
3803      if (TemplateDeductionResult TDK
3804            = DeduceTemplateArguments(FunTmpl, ExplicitTemplateArgs,
3805                                      FD->getType(),
3806                                      Specialization,
3807                                      Info)) {
3808        // FIXME: Template argument deduction failed; record why it failed, so
3809        // that we can provide nifty diagnostics.
3810        (void)TDK;
3811        continue;
3812      }
3813
3814      // Record this candidate.
3815      Candidates.push_back(Specialization);
3816    }
3817  }
3818
3819  // Find the most specialized function template.
3820  FunctionDecl *Specialization = getMostSpecialized(Candidates.data(),
3821                                                    Candidates.size(),
3822                                                    TPOC_Other,
3823                                                    FD->getLocation(),
3824                  PartialDiagnostic(diag::err_function_template_spec_no_match)
3825                    << FD->getDeclName(),
3826                  PartialDiagnostic(diag::err_function_template_spec_ambiguous)
3827                    << FD->getDeclName() << (ExplicitTemplateArgs != 0),
3828                  PartialDiagnostic(diag::note_function_template_spec_matched));
3829  if (!Specialization)
3830    return true;
3831
3832  // FIXME: Check if the prior specialization has a point of instantiation.
3833  // If so, we have run afoul of .
3834
3835  // Check the scope of this explicit specialization.
3836  if (CheckTemplateSpecializationScope(*this,
3837                                       Specialization->getPrimaryTemplate(),
3838                                       Specialization, FD->getLocation(),
3839                                       false))
3840    return true;
3841
3842  // C++ [temp.expl.spec]p6:
3843  //   If a template, a member template or the member of a class template is
3844  //   explicitly specialized then that specialization shall be declared
3845  //   before the first use of that specialization that would cause an implicit
3846  //   instantiation to take place, in every translation unit in which such a
3847  //   use occurs; no diagnostic is required.
3848  FunctionTemplateSpecializationInfo *SpecInfo
3849    = Specialization->getTemplateSpecializationInfo();
3850  assert(SpecInfo && "Function template specialization info missing?");
3851  if (SpecInfo->getPointOfInstantiation().isValid()) {
3852    Diag(FD->getLocation(), diag::err_specialization_after_instantiation)
3853      << FD;
3854    Diag(SpecInfo->getPointOfInstantiation(),
3855         diag::note_instantiation_required_here)
3856      << (Specialization->getTemplateSpecializationKind()
3857                                                != TSK_ImplicitInstantiation);
3858    return true;
3859  }
3860
3861  // Mark the prior declaration as an explicit specialization, so that later
3862  // clients know that this is an explicit specialization.
3863  SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
3864
3865  // Turn the given function declaration into a function template
3866  // specialization, with the template arguments from the previous
3867  // specialization.
3868  FD->setFunctionTemplateSpecialization(Context,
3869                                        Specialization->getPrimaryTemplate(),
3870                         new (Context) TemplateArgumentList(
3871                             *Specialization->getTemplateSpecializationArgs()),
3872                                        /*InsertPos=*/0,
3873                                        TSK_ExplicitSpecialization);
3874
3875  // The "previous declaration" for this function template specialization is
3876  // the prior function template specialization.
3877  Previous.clear();
3878  Previous.addDecl(Specialization);
3879  return false;
3880}
3881
3882/// \brief Perform semantic analysis for the given non-template member
3883/// specialization.
3884///
3885/// This routine performs all of the semantic analysis required for an
3886/// explicit member function specialization. On successful completion,
3887/// the function declaration \p FD will become a member function
3888/// specialization.
3889///
3890/// \param Member the member declaration, which will be updated to become a
3891/// specialization.
3892///
3893/// \param Previous the set of declarations, one of which may be specialized
3894/// by this function specialization;  the set will be modified to contain the
3895/// redeclared member.
3896bool
3897Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
3898  assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
3899
3900  // Try to find the member we are instantiating.
3901  NamedDecl *Instantiation = 0;
3902  NamedDecl *InstantiatedFrom = 0;
3903  MemberSpecializationInfo *MSInfo = 0;
3904
3905  if (Previous.empty()) {
3906    // Nowhere to look anyway.
3907  } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
3908    for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
3909           I != E; ++I) {
3910      NamedDecl *D = (*I)->getUnderlyingDecl();
3911      if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
3912        if (Context.hasSameType(Function->getType(), Method->getType())) {
3913          Instantiation = Method;
3914          InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
3915          MSInfo = Method->getMemberSpecializationInfo();
3916          break;
3917        }
3918      }
3919    }
3920  } else if (isa<VarDecl>(Member)) {
3921    VarDecl *PrevVar;
3922    if (Previous.isSingleResult() &&
3923        (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
3924      if (PrevVar->isStaticDataMember()) {
3925        Instantiation = PrevVar;
3926        InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
3927        MSInfo = PrevVar->getMemberSpecializationInfo();
3928      }
3929  } else if (isa<RecordDecl>(Member)) {
3930    CXXRecordDecl *PrevRecord;
3931    if (Previous.isSingleResult() &&
3932        (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
3933      Instantiation = PrevRecord;
3934      InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
3935      MSInfo = PrevRecord->getMemberSpecializationInfo();
3936    }
3937  }
3938
3939  if (!Instantiation) {
3940    // There is no previous declaration that matches. Since member
3941    // specializations are always out-of-line, the caller will complain about
3942    // this mismatch later.
3943    return false;
3944  }
3945
3946  // Make sure that this is a specialization of a member.
3947  if (!InstantiatedFrom) {
3948    Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
3949      << Member;
3950    Diag(Instantiation->getLocation(), diag::note_specialized_decl);
3951    return true;
3952  }
3953
3954  // C++ [temp.expl.spec]p6:
3955  //   If a template, a member template or the member of a class template is
3956  //   explicitly specialized then that spe- cialization shall be declared
3957  //   before the first use of that specialization that would cause an implicit
3958  //   instantiation to take place, in every translation unit in which such a
3959  //   use occurs; no diagnostic is required.
3960  assert(MSInfo && "Member specialization info missing?");
3961  if (MSInfo->getPointOfInstantiation().isValid()) {
3962    Diag(Member->getLocation(), diag::err_specialization_after_instantiation)
3963      << Member;
3964    Diag(MSInfo->getPointOfInstantiation(),
3965         diag::note_instantiation_required_here)
3966      << (MSInfo->getTemplateSpecializationKind() != TSK_ImplicitInstantiation);
3967    return true;
3968  }
3969
3970  // Check the scope of this explicit specialization.
3971  if (CheckTemplateSpecializationScope(*this,
3972                                       InstantiatedFrom,
3973                                       Instantiation, Member->getLocation(),
3974                                       false))
3975    return true;
3976
3977  // Note that this is an explicit instantiation of a member.
3978  // the original declaration to note that it is an explicit specialization
3979  // (if it was previously an implicit instantiation). This latter step
3980  // makes bookkeeping easier.
3981  if (isa<FunctionDecl>(Member)) {
3982    FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
3983    if (InstantiationFunction->getTemplateSpecializationKind() ==
3984          TSK_ImplicitInstantiation) {
3985      InstantiationFunction->setTemplateSpecializationKind(
3986                                                  TSK_ExplicitSpecialization);
3987      InstantiationFunction->setLocation(Member->getLocation());
3988    }
3989
3990    cast<FunctionDecl>(Member)->setInstantiationOfMemberFunction(
3991                                        cast<CXXMethodDecl>(InstantiatedFrom),
3992                                                  TSK_ExplicitSpecialization);
3993  } else if (isa<VarDecl>(Member)) {
3994    VarDecl *InstantiationVar = cast<VarDecl>(Instantiation);
3995    if (InstantiationVar->getTemplateSpecializationKind() ==
3996          TSK_ImplicitInstantiation) {
3997      InstantiationVar->setTemplateSpecializationKind(
3998                                                  TSK_ExplicitSpecialization);
3999      InstantiationVar->setLocation(Member->getLocation());
4000    }
4001
4002    Context.setInstantiatedFromStaticDataMember(cast<VarDecl>(Member),
4003                                                cast<VarDecl>(InstantiatedFrom),
4004                                                TSK_ExplicitSpecialization);
4005  } else {
4006    assert(isa<CXXRecordDecl>(Member) && "Only member classes remain");
4007    CXXRecordDecl *InstantiationClass = cast<CXXRecordDecl>(Instantiation);
4008    if (InstantiationClass->getTemplateSpecializationKind() ==
4009          TSK_ImplicitInstantiation) {
4010      InstantiationClass->setTemplateSpecializationKind(
4011                                                   TSK_ExplicitSpecialization);
4012      InstantiationClass->setLocation(Member->getLocation());
4013    }
4014
4015    cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
4016                                        cast<CXXRecordDecl>(InstantiatedFrom),
4017                                                   TSK_ExplicitSpecialization);
4018  }
4019
4020  // Save the caller the trouble of having to figure out which declaration
4021  // this specialization matches.
4022  Previous.clear();
4023  Previous.addDecl(Instantiation);
4024  return false;
4025}
4026
4027/// \brief Check the scope of an explicit instantiation.
4028static void CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
4029                                            SourceLocation InstLoc,
4030                                            bool WasQualifiedName) {
4031  DeclContext *ExpectedContext
4032    = D->getDeclContext()->getEnclosingNamespaceContext()->getLookupContext();
4033  DeclContext *CurContext = S.CurContext->getLookupContext();
4034
4035  // C++0x [temp.explicit]p2:
4036  //   An explicit instantiation shall appear in an enclosing namespace of its
4037  //   template.
4038  //
4039  // This is DR275, which we do not retroactively apply to C++98/03.
4040  if (S.getLangOptions().CPlusPlus0x &&
4041      !CurContext->Encloses(ExpectedContext)) {
4042    if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ExpectedContext))
4043      S.Diag(InstLoc, diag::err_explicit_instantiation_out_of_scope)
4044        << D << NS;
4045    else
4046      S.Diag(InstLoc, diag::err_explicit_instantiation_must_be_global)
4047        << D;
4048    S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
4049    return;
4050  }
4051
4052  // C++0x [temp.explicit]p2:
4053  //   If the name declared in the explicit instantiation is an unqualified
4054  //   name, the explicit instantiation shall appear in the namespace where
4055  //   its template is declared or, if that namespace is inline (7.3.1), any
4056  //   namespace from its enclosing namespace set.
4057  if (WasQualifiedName)
4058    return;
4059
4060  if (CurContext->Equals(ExpectedContext))
4061    return;
4062
4063  S.Diag(InstLoc, diag::err_explicit_instantiation_unqualified_wrong_namespace)
4064    << D << ExpectedContext;
4065  S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
4066}
4067
4068/// \brief Determine whether the given scope specifier has a template-id in it.
4069static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
4070  if (!SS.isSet())
4071    return false;
4072
4073  // C++0x [temp.explicit]p2:
4074  //   If the explicit instantiation is for a member function, a member class
4075  //   or a static data member of a class template specialization, the name of
4076  //   the class template specialization in the qualified-id for the member
4077  //   name shall be a simple-template-id.
4078  //
4079  // C++98 has the same restriction, just worded differently.
4080  for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
4081       NNS; NNS = NNS->getPrefix())
4082    if (Type *T = NNS->getAsType())
4083      if (isa<TemplateSpecializationType>(T))
4084        return true;
4085
4086  return false;
4087}
4088
4089// Explicit instantiation of a class template specialization
4090// FIXME: Implement extern template semantics
4091Sema::DeclResult
4092Sema::ActOnExplicitInstantiation(Scope *S,
4093                                 SourceLocation ExternLoc,
4094                                 SourceLocation TemplateLoc,
4095                                 unsigned TagSpec,
4096                                 SourceLocation KWLoc,
4097                                 const CXXScopeSpec &SS,
4098                                 TemplateTy TemplateD,
4099                                 SourceLocation TemplateNameLoc,
4100                                 SourceLocation LAngleLoc,
4101                                 ASTTemplateArgsPtr TemplateArgsIn,
4102                                 SourceLocation RAngleLoc,
4103                                 AttributeList *Attr) {
4104  // Find the class template we're specializing
4105  TemplateName Name = TemplateD.getAsVal<TemplateName>();
4106  ClassTemplateDecl *ClassTemplate
4107    = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
4108
4109  // Check that the specialization uses the same tag kind as the
4110  // original template.
4111  TagDecl::TagKind Kind;
4112  switch (TagSpec) {
4113  default: assert(0 && "Unknown tag type!");
4114  case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
4115  case DeclSpec::TST_union:  Kind = TagDecl::TK_union; break;
4116  case DeclSpec::TST_class:  Kind = TagDecl::TK_class; break;
4117  }
4118  if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
4119                                    Kind, KWLoc,
4120                                    *ClassTemplate->getIdentifier())) {
4121    Diag(KWLoc, diag::err_use_with_wrong_tag)
4122      << ClassTemplate
4123      << CodeModificationHint::CreateReplacement(KWLoc,
4124                            ClassTemplate->getTemplatedDecl()->getKindName());
4125    Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
4126         diag::note_previous_use);
4127    Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
4128  }
4129
4130  // C++0x [temp.explicit]p2:
4131  //   There are two forms of explicit instantiation: an explicit instantiation
4132  //   definition and an explicit instantiation declaration. An explicit
4133  //   instantiation declaration begins with the extern keyword. [...]
4134  TemplateSpecializationKind TSK
4135    = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
4136                           : TSK_ExplicitInstantiationDeclaration;
4137
4138  // Translate the parser's template argument list in our AST format.
4139  TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
4140  translateTemplateArguments(TemplateArgsIn, TemplateArgs);
4141
4142  // Check that the template argument list is well-formed for this
4143  // template.
4144  TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
4145                                        TemplateArgs.size());
4146  if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
4147                                TemplateArgs, false, Converted))
4148    return true;
4149
4150  assert((Converted.structuredSize() ==
4151            ClassTemplate->getTemplateParameters()->size()) &&
4152         "Converted template argument list is too short!");
4153
4154  // Find the class template specialization declaration that
4155  // corresponds to these arguments.
4156  llvm::FoldingSetNodeID ID;
4157  ClassTemplateSpecializationDecl::Profile(ID,
4158                                           Converted.getFlatArguments(),
4159                                           Converted.flatSize(),
4160                                           Context);
4161  void *InsertPos = 0;
4162  ClassTemplateSpecializationDecl *PrevDecl
4163    = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
4164
4165  // C++0x [temp.explicit]p2:
4166  //   [...] An explicit instantiation shall appear in an enclosing
4167  //   namespace of its template. [...]
4168  //
4169  // This is C++ DR 275.
4170  CheckExplicitInstantiationScope(*this, ClassTemplate, TemplateNameLoc,
4171                                  SS.isSet());
4172
4173  ClassTemplateSpecializationDecl *Specialization = 0;
4174
4175  bool ReusedDecl = false;
4176  if (PrevDecl) {
4177    bool SuppressNew = false;
4178    if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
4179                                               PrevDecl,
4180                                              PrevDecl->getSpecializationKind(),
4181                                            PrevDecl->getPointOfInstantiation(),
4182                                               SuppressNew))
4183      return DeclPtrTy::make(PrevDecl);
4184
4185    if (SuppressNew)
4186      return DeclPtrTy::make(PrevDecl);
4187
4188    if (PrevDecl->getSpecializationKind() == TSK_ImplicitInstantiation ||
4189        PrevDecl->getSpecializationKind() == TSK_Undeclared) {
4190      // Since the only prior class template specialization with these
4191      // arguments was referenced but not declared, reuse that
4192      // declaration node as our own, updating its source location to
4193      // reflect our new declaration.
4194      Specialization = PrevDecl;
4195      Specialization->setLocation(TemplateNameLoc);
4196      PrevDecl = 0;
4197      ReusedDecl = true;
4198    }
4199  }
4200
4201  if (!Specialization) {
4202    // Create a new class template specialization declaration node for
4203    // this explicit specialization.
4204    Specialization
4205      = ClassTemplateSpecializationDecl::Create(Context,
4206                                             ClassTemplate->getDeclContext(),
4207                                                TemplateNameLoc,
4208                                                ClassTemplate,
4209                                                Converted, PrevDecl);
4210
4211    if (PrevDecl) {
4212      // Remove the previous declaration from the folding set, since we want
4213      // to introduce a new declaration.
4214      ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
4215      ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
4216    }
4217
4218    // Insert the new specialization.
4219    ClassTemplate->getSpecializations().InsertNode(Specialization, InsertPos);
4220  }
4221
4222  // Build the fully-sugared type for this explicit instantiation as
4223  // the user wrote in the explicit instantiation itself. This means
4224  // that we'll pretty-print the type retrieved from the
4225  // specialization's declaration the way that the user actually wrote
4226  // the explicit instantiation, rather than formatting the name based
4227  // on the "canonical" representation used to store the template
4228  // arguments in the specialization.
4229  QualType WrittenTy
4230    = Context.getTemplateSpecializationType(Name, TemplateArgs,
4231                                  Context.getTypeDeclType(Specialization));
4232  Specialization->setTypeAsWritten(WrittenTy);
4233  TemplateArgsIn.release();
4234
4235  if (!ReusedDecl) {
4236    // Add the explicit instantiation into its lexical context. However,
4237    // since explicit instantiations are never found by name lookup, we
4238    // just put it into the declaration context directly.
4239    Specialization->setLexicalDeclContext(CurContext);
4240    CurContext->addDecl(Specialization);
4241  }
4242
4243  // C++ [temp.explicit]p3:
4244  //   A definition of a class template or class member template
4245  //   shall be in scope at the point of the explicit instantiation of
4246  //   the class template or class member template.
4247  //
4248  // This check comes when we actually try to perform the
4249  // instantiation.
4250  ClassTemplateSpecializationDecl *Def
4251    = cast_or_null<ClassTemplateSpecializationDecl>(
4252                                        Specialization->getDefinition(Context));
4253  if (!Def)
4254    InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK);
4255
4256  // Instantiate the members of this class template specialization.
4257  Def = cast_or_null<ClassTemplateSpecializationDecl>(
4258                                       Specialization->getDefinition(Context));
4259  if (Def)
4260    InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
4261
4262  return DeclPtrTy::make(Specialization);
4263}
4264
4265// Explicit instantiation of a member class of a class template.
4266Sema::DeclResult
4267Sema::ActOnExplicitInstantiation(Scope *S,
4268                                 SourceLocation ExternLoc,
4269                                 SourceLocation TemplateLoc,
4270                                 unsigned TagSpec,
4271                                 SourceLocation KWLoc,
4272                                 const CXXScopeSpec &SS,
4273                                 IdentifierInfo *Name,
4274                                 SourceLocation NameLoc,
4275                                 AttributeList *Attr) {
4276
4277  bool Owned = false;
4278  bool IsDependent = false;
4279  DeclPtrTy TagD = ActOnTag(S, TagSpec, Action::TUK_Reference,
4280                            KWLoc, SS, Name, NameLoc, Attr, AS_none,
4281                            MultiTemplateParamsArg(*this, 0, 0),
4282                            Owned, IsDependent);
4283  assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
4284
4285  if (!TagD)
4286    return true;
4287
4288  TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>());
4289  if (Tag->isEnum()) {
4290    Diag(TemplateLoc, diag::err_explicit_instantiation_enum)
4291      << Context.getTypeDeclType(Tag);
4292    return true;
4293  }
4294
4295  if (Tag->isInvalidDecl())
4296    return true;
4297
4298  CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
4299  CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
4300  if (!Pattern) {
4301    Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
4302      << Context.getTypeDeclType(Record);
4303    Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
4304    return true;
4305  }
4306
4307  // C++0x [temp.explicit]p2:
4308  //   If the explicit instantiation is for a class or member class, the
4309  //   elaborated-type-specifier in the declaration shall include a
4310  //   simple-template-id.
4311  //
4312  // C++98 has the same restriction, just worded differently.
4313  if (!ScopeSpecifierHasTemplateId(SS))
4314    Diag(TemplateLoc, diag::err_explicit_instantiation_without_qualified_id)
4315      << Record << SS.getRange();
4316
4317  // C++0x [temp.explicit]p2:
4318  //   There are two forms of explicit instantiation: an explicit instantiation
4319  //   definition and an explicit instantiation declaration. An explicit
4320  //   instantiation declaration begins with the extern keyword. [...]
4321  TemplateSpecializationKind TSK
4322    = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
4323                           : TSK_ExplicitInstantiationDeclaration;
4324
4325  // C++0x [temp.explicit]p2:
4326  //   [...] An explicit instantiation shall appear in an enclosing
4327  //   namespace of its template. [...]
4328  //
4329  // This is C++ DR 275.
4330  CheckExplicitInstantiationScope(*this, Record, NameLoc, true);
4331
4332  // Verify that it is okay to explicitly instantiate here.
4333  CXXRecordDecl *PrevDecl
4334    = cast_or_null<CXXRecordDecl>(Record->getPreviousDeclaration());
4335  if (!PrevDecl && Record->getDefinition(Context))
4336    PrevDecl = Record;
4337  if (PrevDecl) {
4338    MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
4339    bool SuppressNew = false;
4340    assert(MSInfo && "No member specialization information?");
4341    if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
4342                                               PrevDecl,
4343                                        MSInfo->getTemplateSpecializationKind(),
4344                                             MSInfo->getPointOfInstantiation(),
4345                                               SuppressNew))
4346      return true;
4347    if (SuppressNew)
4348      return TagD;
4349  }
4350
4351  CXXRecordDecl *RecordDef
4352    = cast_or_null<CXXRecordDecl>(Record->getDefinition(Context));
4353  if (!RecordDef) {
4354    // C++ [temp.explicit]p3:
4355    //   A definition of a member class of a class template shall be in scope
4356    //   at the point of an explicit instantiation of the member class.
4357    CXXRecordDecl *Def
4358      = cast_or_null<CXXRecordDecl>(Pattern->getDefinition(Context));
4359    if (!Def) {
4360      Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
4361        << 0 << Record->getDeclName() << Record->getDeclContext();
4362      Diag(Pattern->getLocation(), diag::note_forward_declaration)
4363        << Pattern;
4364      return true;
4365    } else {
4366      if (InstantiateClass(NameLoc, Record, Def,
4367                           getTemplateInstantiationArgs(Record),
4368                           TSK))
4369        return true;
4370
4371      RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition(Context));
4372      if (!RecordDef)
4373        return true;
4374    }
4375  }
4376
4377  // Instantiate all of the members of the class.
4378  InstantiateClassMembers(NameLoc, RecordDef,
4379                          getTemplateInstantiationArgs(Record), TSK);
4380
4381  // FIXME: We don't have any representation for explicit instantiations of
4382  // member classes. Such a representation is not needed for compilation, but it
4383  // should be available for clients that want to see all of the declarations in
4384  // the source code.
4385  return TagD;
4386}
4387
4388Sema::DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
4389                                                  SourceLocation ExternLoc,
4390                                                  SourceLocation TemplateLoc,
4391                                                  Declarator &D) {
4392  // Explicit instantiations always require a name.
4393  DeclarationName Name = GetNameForDeclarator(D);
4394  if (!Name) {
4395    if (!D.isInvalidType())
4396      Diag(D.getDeclSpec().getSourceRange().getBegin(),
4397           diag::err_explicit_instantiation_requires_name)
4398        << D.getDeclSpec().getSourceRange()
4399        << D.getSourceRange();
4400
4401    return true;
4402  }
4403
4404  // The scope passed in may not be a decl scope.  Zip up the scope tree until
4405  // we find one that is.
4406  while ((S->getFlags() & Scope::DeclScope) == 0 ||
4407         (S->getFlags() & Scope::TemplateParamScope) != 0)
4408    S = S->getParent();
4409
4410  // Determine the type of the declaration.
4411  QualType R = GetTypeForDeclarator(D, S, 0);
4412  if (R.isNull())
4413    return true;
4414
4415  if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
4416    // Cannot explicitly instantiate a typedef.
4417    Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
4418      << Name;
4419    return true;
4420  }
4421
4422  // C++0x [temp.explicit]p1:
4423  //   [...] An explicit instantiation of a function template shall not use the
4424  //   inline or constexpr specifiers.
4425  // Presumably, this also applies to member functions of class templates as
4426  // well.
4427  if (D.getDeclSpec().isInlineSpecified() && getLangOptions().CPlusPlus0x)
4428    Diag(D.getDeclSpec().getInlineSpecLoc(),
4429         diag::err_explicit_instantiation_inline)
4430      <<CodeModificationHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
4431
4432  // FIXME: check for constexpr specifier.
4433
4434  // C++0x [temp.explicit]p2:
4435  //   There are two forms of explicit instantiation: an explicit instantiation
4436  //   definition and an explicit instantiation declaration. An explicit
4437  //   instantiation declaration begins with the extern keyword. [...]
4438  TemplateSpecializationKind TSK
4439    = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
4440                           : TSK_ExplicitInstantiationDeclaration;
4441
4442  LookupResult Previous(*this, Name, D.getIdentifierLoc(), LookupOrdinaryName);
4443  LookupParsedName(Previous, S, &D.getCXXScopeSpec());
4444
4445  if (!R->isFunctionType()) {
4446    // C++ [temp.explicit]p1:
4447    //   A [...] static data member of a class template can be explicitly
4448    //   instantiated from the member definition associated with its class
4449    //   template.
4450    if (Previous.isAmbiguous())
4451      return true;
4452
4453    VarDecl *Prev = Previous.getAsSingle<VarDecl>();
4454    if (!Prev || !Prev->isStaticDataMember()) {
4455      // We expect to see a data data member here.
4456      Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
4457        << Name;
4458      for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
4459           P != PEnd; ++P)
4460        Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
4461      return true;
4462    }
4463
4464    if (!Prev->getInstantiatedFromStaticDataMember()) {
4465      // FIXME: Check for explicit specialization?
4466      Diag(D.getIdentifierLoc(),
4467           diag::err_explicit_instantiation_data_member_not_instantiated)
4468        << Prev;
4469      Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
4470      // FIXME: Can we provide a note showing where this was declared?
4471      return true;
4472    }
4473
4474    // C++0x [temp.explicit]p2:
4475    //   If the explicit instantiation is for a member function, a member class
4476    //   or a static data member of a class template specialization, the name of
4477    //   the class template specialization in the qualified-id for the member
4478    //   name shall be a simple-template-id.
4479    //
4480    // C++98 has the same restriction, just worded differently.
4481    if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
4482      Diag(D.getIdentifierLoc(),
4483           diag::err_explicit_instantiation_without_qualified_id)
4484        << Prev << D.getCXXScopeSpec().getRange();
4485
4486    // Check the scope of this explicit instantiation.
4487    CheckExplicitInstantiationScope(*this, Prev, D.getIdentifierLoc(), true);
4488
4489    // Verify that it is okay to explicitly instantiate here.
4490    MemberSpecializationInfo *MSInfo = Prev->getMemberSpecializationInfo();
4491    assert(MSInfo && "Missing static data member specialization info?");
4492    bool SuppressNew = false;
4493    if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
4494                                        MSInfo->getTemplateSpecializationKind(),
4495                                              MSInfo->getPointOfInstantiation(),
4496                                               SuppressNew))
4497      return true;
4498    if (SuppressNew)
4499      return DeclPtrTy();
4500
4501    // Instantiate static data member.
4502    Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
4503    if (TSK == TSK_ExplicitInstantiationDefinition)
4504      InstantiateStaticDataMemberDefinition(D.getIdentifierLoc(), Prev, false,
4505                                            /*DefinitionRequired=*/true);
4506
4507    // FIXME: Create an ExplicitInstantiation node?
4508    return DeclPtrTy();
4509  }
4510
4511  // If the declarator is a template-id, translate the parser's template
4512  // argument list into our AST format.
4513  bool HasExplicitTemplateArgs = false;
4514  TemplateArgumentListInfo TemplateArgs;
4515  if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
4516    TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
4517    TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
4518    TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
4519    ASTTemplateArgsPtr TemplateArgsPtr(*this,
4520                                       TemplateId->getTemplateArgs(),
4521                                       TemplateId->NumArgs);
4522    translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
4523    HasExplicitTemplateArgs = true;
4524    TemplateArgsPtr.release();
4525  }
4526
4527  // C++ [temp.explicit]p1:
4528  //   A [...] function [...] can be explicitly instantiated from its template.
4529  //   A member function [...] of a class template can be explicitly
4530  //  instantiated from the member definition associated with its class
4531  //  template.
4532  llvm::SmallVector<FunctionDecl *, 8> Matches;
4533  for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
4534       P != PEnd; ++P) {
4535    NamedDecl *Prev = *P;
4536    if (!HasExplicitTemplateArgs) {
4537      if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
4538        if (Context.hasSameUnqualifiedType(Method->getType(), R)) {
4539          Matches.clear();
4540          Matches.push_back(Method);
4541          break;
4542        }
4543      }
4544    }
4545
4546    FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
4547    if (!FunTmpl)
4548      continue;
4549
4550    TemplateDeductionInfo Info(Context);
4551    FunctionDecl *Specialization = 0;
4552    if (TemplateDeductionResult TDK
4553          = DeduceTemplateArguments(FunTmpl,
4554                               (HasExplicitTemplateArgs ? &TemplateArgs : 0),
4555                                    R, Specialization, Info)) {
4556      // FIXME: Keep track of almost-matches?
4557      (void)TDK;
4558      continue;
4559    }
4560
4561    Matches.push_back(Specialization);
4562  }
4563
4564  // Find the most specialized function template specialization.
4565  FunctionDecl *Specialization
4566    = getMostSpecialized(Matches.data(), Matches.size(), TPOC_Other,
4567                         D.getIdentifierLoc(),
4568          PartialDiagnostic(diag::err_explicit_instantiation_not_known) << Name,
4569          PartialDiagnostic(diag::err_explicit_instantiation_ambiguous) << Name,
4570                PartialDiagnostic(diag::note_explicit_instantiation_candidate));
4571
4572  if (!Specialization)
4573    return true;
4574
4575  if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
4576    Diag(D.getIdentifierLoc(),
4577         diag::err_explicit_instantiation_member_function_not_instantiated)
4578      << Specialization
4579      << (Specialization->getTemplateSpecializationKind() ==
4580          TSK_ExplicitSpecialization);
4581    Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
4582    return true;
4583  }
4584
4585  FunctionDecl *PrevDecl = Specialization->getPreviousDeclaration();
4586  if (!PrevDecl && Specialization->isThisDeclarationADefinition())
4587    PrevDecl = Specialization;
4588
4589  if (PrevDecl) {
4590    bool SuppressNew = false;
4591    if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
4592                                               PrevDecl,
4593                                     PrevDecl->getTemplateSpecializationKind(),
4594                                          PrevDecl->getPointOfInstantiation(),
4595                                               SuppressNew))
4596      return true;
4597
4598    // FIXME: We may still want to build some representation of this
4599    // explicit specialization.
4600    if (SuppressNew)
4601      return DeclPtrTy();
4602  }
4603
4604  Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
4605
4606  if (TSK == TSK_ExplicitInstantiationDefinition)
4607    InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization,
4608                                  false, /*DefinitionRequired=*/true);
4609
4610  // C++0x [temp.explicit]p2:
4611  //   If the explicit instantiation is for a member function, a member class
4612  //   or a static data member of a class template specialization, the name of
4613  //   the class template specialization in the qualified-id for the member
4614  //   name shall be a simple-template-id.
4615  //
4616  // C++98 has the same restriction, just worded differently.
4617  FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
4618  if (D.getName().getKind() != UnqualifiedId::IK_TemplateId && !FunTmpl &&
4619      D.getCXXScopeSpec().isSet() &&
4620      !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
4621    Diag(D.getIdentifierLoc(),
4622         diag::err_explicit_instantiation_without_qualified_id)
4623    << Specialization << D.getCXXScopeSpec().getRange();
4624
4625  CheckExplicitInstantiationScope(*this,
4626                   FunTmpl? (NamedDecl *)FunTmpl
4627                          : Specialization->getInstantiatedFromMemberFunction(),
4628                                  D.getIdentifierLoc(),
4629                                  D.getCXXScopeSpec().isSet());
4630
4631  // FIXME: Create some kind of ExplicitInstantiationDecl here.
4632  return DeclPtrTy();
4633}
4634
4635Sema::TypeResult
4636Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
4637                        const CXXScopeSpec &SS, IdentifierInfo *Name,
4638                        SourceLocation TagLoc, SourceLocation NameLoc) {
4639  // This has to hold, because SS is expected to be defined.
4640  assert(Name && "Expected a name in a dependent tag");
4641
4642  NestedNameSpecifier *NNS
4643    = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
4644  if (!NNS)
4645    return true;
4646
4647  QualType T = CheckTypenameType(NNS, *Name, SourceRange(TagLoc, NameLoc));
4648  if (T.isNull())
4649    return true;
4650
4651  TagDecl::TagKind TagKind = TagDecl::getTagKindForTypeSpec(TagSpec);
4652  QualType ElabType = Context.getElaboratedType(T, TagKind);
4653
4654  return ElabType.getAsOpaquePtr();
4655}
4656
4657Sema::TypeResult
4658Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
4659                        const IdentifierInfo &II, SourceLocation IdLoc) {
4660  NestedNameSpecifier *NNS
4661    = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
4662  if (!NNS)
4663    return true;
4664
4665  QualType T = CheckTypenameType(NNS, II, SourceRange(TypenameLoc, IdLoc));
4666  if (T.isNull())
4667    return true;
4668  return T.getAsOpaquePtr();
4669}
4670
4671Sema::TypeResult
4672Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
4673                        SourceLocation TemplateLoc, TypeTy *Ty) {
4674  QualType T = GetTypeFromParser(Ty);
4675  NestedNameSpecifier *NNS
4676    = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
4677  const TemplateSpecializationType *TemplateId
4678    = T->getAs<TemplateSpecializationType>();
4679  assert(TemplateId && "Expected a template specialization type");
4680
4681  if (computeDeclContext(SS, false)) {
4682    // If we can compute a declaration context, then the "typename"
4683    // keyword was superfluous. Just build a QualifiedNameType to keep
4684    // track of the nested-name-specifier.
4685
4686    // FIXME: Note that the QualifiedNameType had the "typename" keyword!
4687    return Context.getQualifiedNameType(NNS, T).getAsOpaquePtr();
4688  }
4689
4690  return Context.getTypenameType(NNS, TemplateId).getAsOpaquePtr();
4691}
4692
4693/// \brief Build the type that describes a C++ typename specifier,
4694/// e.g., "typename T::type".
4695QualType
4696Sema::CheckTypenameType(NestedNameSpecifier *NNS, const IdentifierInfo &II,
4697                        SourceRange Range) {
4698  CXXRecordDecl *CurrentInstantiation = 0;
4699  if (NNS->isDependent()) {
4700    CurrentInstantiation = getCurrentInstantiationOf(NNS);
4701
4702    // If the nested-name-specifier does not refer to the current
4703    // instantiation, then build a typename type.
4704    if (!CurrentInstantiation)
4705      return Context.getTypenameType(NNS, &II);
4706
4707    // The nested-name-specifier refers to the current instantiation, so the
4708    // "typename" keyword itself is superfluous. In C++03, the program is
4709    // actually ill-formed. However, DR 382 (in C++0x CD1) allows such
4710    // extraneous "typename" keywords, and we retroactively apply this DR to
4711    // C++03 code.
4712  }
4713
4714  DeclContext *Ctx = 0;
4715
4716  if (CurrentInstantiation)
4717    Ctx = CurrentInstantiation;
4718  else {
4719    CXXScopeSpec SS;
4720    SS.setScopeRep(NNS);
4721    SS.setRange(Range);
4722    if (RequireCompleteDeclContext(SS))
4723      return QualType();
4724
4725    Ctx = computeDeclContext(SS);
4726  }
4727  assert(Ctx && "No declaration context?");
4728
4729  DeclarationName Name(&II);
4730  LookupResult Result(*this, Name, Range.getEnd(), LookupOrdinaryName);
4731  LookupQualifiedName(Result, Ctx);
4732  unsigned DiagID = 0;
4733  Decl *Referenced = 0;
4734  switch (Result.getResultKind()) {
4735  case LookupResult::NotFound:
4736    DiagID = diag::err_typename_nested_not_found;
4737    break;
4738
4739  case LookupResult::Found:
4740    if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
4741      // We found a type. Build a QualifiedNameType, since the
4742      // typename-specifier was just sugar. FIXME: Tell
4743      // QualifiedNameType that it has a "typename" prefix.
4744      return Context.getQualifiedNameType(NNS, Context.getTypeDeclType(Type));
4745    }
4746
4747    DiagID = diag::err_typename_nested_not_type;
4748    Referenced = Result.getFoundDecl();
4749    break;
4750
4751  case LookupResult::FoundUnresolvedValue:
4752    llvm_unreachable("unresolved using decl in non-dependent context");
4753    return QualType();
4754
4755  case LookupResult::FoundOverloaded:
4756    DiagID = diag::err_typename_nested_not_type;
4757    Referenced = *Result.begin();
4758    break;
4759
4760  case LookupResult::Ambiguous:
4761    return QualType();
4762  }
4763
4764  // If we get here, it's because name lookup did not find a
4765  // type. Emit an appropriate diagnostic and return an error.
4766  Diag(Range.getEnd(), DiagID) << Range << Name << Ctx;
4767  if (Referenced)
4768    Diag(Referenced->getLocation(), diag::note_typename_refers_here)
4769      << Name;
4770  return QualType();
4771}
4772
4773namespace {
4774  // See Sema::RebuildTypeInCurrentInstantiation
4775  class CurrentInstantiationRebuilder
4776    : public TreeTransform<CurrentInstantiationRebuilder> {
4777    SourceLocation Loc;
4778    DeclarationName Entity;
4779
4780  public:
4781    CurrentInstantiationRebuilder(Sema &SemaRef,
4782                                  SourceLocation Loc,
4783                                  DeclarationName Entity)
4784    : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
4785      Loc(Loc), Entity(Entity) { }
4786
4787    /// \brief Determine whether the given type \p T has already been
4788    /// transformed.
4789    ///
4790    /// For the purposes of type reconstruction, a type has already been
4791    /// transformed if it is NULL or if it is not dependent.
4792    bool AlreadyTransformed(QualType T) {
4793      return T.isNull() || !T->isDependentType();
4794    }
4795
4796    /// \brief Returns the location of the entity whose type is being
4797    /// rebuilt.
4798    SourceLocation getBaseLocation() { return Loc; }
4799
4800    /// \brief Returns the name of the entity whose type is being rebuilt.
4801    DeclarationName getBaseEntity() { return Entity; }
4802
4803    /// \brief Sets the "base" location and entity when that
4804    /// information is known based on another transformation.
4805    void setBase(SourceLocation Loc, DeclarationName Entity) {
4806      this->Loc = Loc;
4807      this->Entity = Entity;
4808    }
4809
4810    /// \brief Transforms an expression by returning the expression itself
4811    /// (an identity function).
4812    ///
4813    /// FIXME: This is completely unsafe; we will need to actually clone the
4814    /// expressions.
4815    Sema::OwningExprResult TransformExpr(Expr *E) {
4816      return getSema().Owned(E);
4817    }
4818
4819    /// \brief Transforms a typename type by determining whether the type now
4820    /// refers to a member of the current instantiation, and then
4821    /// type-checking and building a QualifiedNameType (when possible).
4822    QualType TransformTypenameType(TypeLocBuilder &TLB, TypenameTypeLoc TL);
4823  };
4824}
4825
4826QualType
4827CurrentInstantiationRebuilder::TransformTypenameType(TypeLocBuilder &TLB,
4828                                                     TypenameTypeLoc TL) {
4829  TypenameType *T = TL.getTypePtr();
4830
4831  NestedNameSpecifier *NNS
4832    = TransformNestedNameSpecifier(T->getQualifier(),
4833                              /*FIXME:*/SourceRange(getBaseLocation()));
4834  if (!NNS)
4835    return QualType();
4836
4837  // If the nested-name-specifier did not change, and we cannot compute the
4838  // context corresponding to the nested-name-specifier, then this
4839  // typename type will not change; exit early.
4840  CXXScopeSpec SS;
4841  SS.setRange(SourceRange(getBaseLocation()));
4842  SS.setScopeRep(NNS);
4843
4844  QualType Result;
4845  if (NNS == T->getQualifier() && getSema().computeDeclContext(SS) == 0)
4846    Result = QualType(T, 0);
4847
4848  // Rebuild the typename type, which will probably turn into a
4849  // QualifiedNameType.
4850  else if (const TemplateSpecializationType *TemplateId = T->getTemplateId()) {
4851    QualType NewTemplateId
4852      = TransformType(QualType(TemplateId, 0));
4853    if (NewTemplateId.isNull())
4854      return QualType();
4855
4856    if (NNS == T->getQualifier() &&
4857        NewTemplateId == QualType(TemplateId, 0))
4858      Result = QualType(T, 0);
4859    else
4860      Result = getDerived().RebuildTypenameType(NNS, NewTemplateId);
4861  } else
4862    Result = getDerived().RebuildTypenameType(NNS, T->getIdentifier(),
4863                                              SourceRange(TL.getNameLoc()));
4864
4865  TypenameTypeLoc NewTL = TLB.push<TypenameTypeLoc>(Result);
4866  NewTL.setNameLoc(TL.getNameLoc());
4867  return Result;
4868}
4869
4870/// \brief Rebuilds a type within the context of the current instantiation.
4871///
4872/// The type \p T is part of the type of an out-of-line member definition of
4873/// a class template (or class template partial specialization) that was parsed
4874/// and constructed before we entered the scope of the class template (or
4875/// partial specialization thereof). This routine will rebuild that type now
4876/// that we have entered the declarator's scope, which may produce different
4877/// canonical types, e.g.,
4878///
4879/// \code
4880/// template<typename T>
4881/// struct X {
4882///   typedef T* pointer;
4883///   pointer data();
4884/// };
4885///
4886/// template<typename T>
4887/// typename X<T>::pointer X<T>::data() { ... }
4888/// \endcode
4889///
4890/// Here, the type "typename X<T>::pointer" will be created as a TypenameType,
4891/// since we do not know that we can look into X<T> when we parsed the type.
4892/// This function will rebuild the type, performing the lookup of "pointer"
4893/// in X<T> and returning a QualifiedNameType whose canonical type is the same
4894/// as the canonical type of T*, allowing the return types of the out-of-line
4895/// definition and the declaration to match.
4896QualType Sema::RebuildTypeInCurrentInstantiation(QualType T, SourceLocation Loc,
4897                                                 DeclarationName Name) {
4898  if (T.isNull() || !T->isDependentType())
4899    return T;
4900
4901  CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
4902  return Rebuilder.TransformType(T);
4903}
4904
4905/// \brief Produces a formatted string that describes the binding of
4906/// template parameters to template arguments.
4907std::string
4908Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
4909                                      const TemplateArgumentList &Args) {
4910  // FIXME: For variadic templates, we'll need to get the structured list.
4911  return getTemplateArgumentBindingsText(Params, Args.getFlatArgumentList(),
4912                                         Args.flat_size());
4913}
4914
4915std::string
4916Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
4917                                      const TemplateArgument *Args,
4918                                      unsigned NumArgs) {
4919  std::string Result;
4920
4921  if (!Params || Params->size() == 0 || NumArgs == 0)
4922    return Result;
4923
4924  for (unsigned I = 0, N = Params->size(); I != N; ++I) {
4925    if (I >= NumArgs)
4926      break;
4927
4928    if (I == 0)
4929      Result += "[with ";
4930    else
4931      Result += ", ";
4932
4933    if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
4934      Result += Id->getName();
4935    } else {
4936      Result += '$';
4937      Result += llvm::utostr(I);
4938    }
4939
4940    Result += " = ";
4941
4942    switch (Args[I].getKind()) {
4943      case TemplateArgument::Null:
4944        Result += "<no value>";
4945        break;
4946
4947      case TemplateArgument::Type: {
4948        std::string TypeStr;
4949        Args[I].getAsType().getAsStringInternal(TypeStr,
4950                                                Context.PrintingPolicy);
4951        Result += TypeStr;
4952        break;
4953      }
4954
4955      case TemplateArgument::Declaration: {
4956        bool Unnamed = true;
4957        if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(Args[I].getAsDecl())) {
4958          if (ND->getDeclName()) {
4959            Unnamed = false;
4960            Result += ND->getNameAsString();
4961          }
4962        }
4963
4964        if (Unnamed) {
4965          Result += "<anonymous>";
4966        }
4967        break;
4968      }
4969
4970      case TemplateArgument::Template: {
4971        std::string Str;
4972        llvm::raw_string_ostream OS(Str);
4973        Args[I].getAsTemplate().print(OS, Context.PrintingPolicy);
4974        Result += OS.str();
4975        break;
4976      }
4977
4978      case TemplateArgument::Integral: {
4979        Result += Args[I].getAsIntegral()->toString(10);
4980        break;
4981      }
4982
4983      case TemplateArgument::Expression: {
4984        assert(false && "No expressions in deduced template arguments!");
4985        Result += "<expression>";
4986        break;
4987      }
4988
4989      case TemplateArgument::Pack:
4990        // FIXME: Format template argument packs
4991        Result += "<template argument pack>";
4992        break;
4993    }
4994  }
4995
4996  Result += ']';
4997  return Result;
4998}
4999