SemaTemplate.cpp revision bea479409a94af5abf202739e5688fdb452f9aa9
1//===------- SemaTemplate.cpp - Semantic Analysis for C++ Templates -------===/
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//===----------------------------------------------------------------------===/
8//
9//  This file implements semantic analysis for C++ templates.
10//===----------------------------------------------------------------------===/
11
12#include "Sema.h"
13#include "TreeTransform.h"
14#include "clang/AST/ASTContext.h"
15#include "clang/AST/Expr.h"
16#include "clang/AST/ExprCXX.h"
17#include "clang/AST/DeclTemplate.h"
18#include "clang/Parse/DeclSpec.h"
19#include "clang/Basic/LangOptions.h"
20#include "clang/Basic/PartialDiagnostic.h"
21#include "llvm/Support/Compiler.h"
22#include "llvm/ADT/StringExtras.h"
23using namespace clang;
24
25/// \brief Determine whether the declaration found is acceptable as the name
26/// of a template and, if so, return that template declaration. Otherwise,
27/// returns NULL.
28static NamedDecl *isAcceptableTemplateName(ASTContext &Context, NamedDecl *D) {
29  if (!D)
30    return 0;
31
32  if (isa<TemplateDecl>(D))
33    return D;
34
35  if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
36    // C++ [temp.local]p1:
37    //   Like normal (non-template) classes, class templates have an
38    //   injected-class-name (Clause 9). The injected-class-name
39    //   can be used with or without a template-argument-list. When
40    //   it is used without a template-argument-list, it is
41    //   equivalent to the injected-class-name followed by the
42    //   template-parameters of the class template enclosed in
43    //   <>. When it is used with a template-argument-list, it
44    //   refers to the specified class template specialization,
45    //   which could be the current specialization or another
46    //   specialization.
47    if (Record->isInjectedClassName()) {
48      Record = cast<CXXRecordDecl>(Record->getCanonicalDecl());
49      if (Record->getDescribedClassTemplate())
50        return Record->getDescribedClassTemplate();
51
52      if (ClassTemplateSpecializationDecl *Spec
53            = dyn_cast<ClassTemplateSpecializationDecl>(Record))
54        return Spec->getSpecializedTemplate();
55    }
56
57    return 0;
58  }
59
60  OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(D);
61  if (!Ovl)
62    return 0;
63
64  for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(),
65                                              FEnd = Ovl->function_end();
66       F != FEnd; ++F) {
67    if (FunctionTemplateDecl *FuncTmpl = dyn_cast<FunctionTemplateDecl>(*F)) {
68      // We've found a function template. Determine whether there are
69      // any other function templates we need to bundle together in an
70      // OverloadedFunctionDecl
71      for (++F; F != FEnd; ++F) {
72        if (isa<FunctionTemplateDecl>(*F))
73          break;
74      }
75
76      if (F != FEnd) {
77        // Build an overloaded function decl containing only the
78        // function templates in Ovl.
79        OverloadedFunctionDecl *OvlTemplate
80          = OverloadedFunctionDecl::Create(Context,
81                                           Ovl->getDeclContext(),
82                                           Ovl->getDeclName());
83        OvlTemplate->addOverload(FuncTmpl);
84        OvlTemplate->addOverload(*F);
85        for (++F; F != FEnd; ++F) {
86          if (isa<FunctionTemplateDecl>(*F))
87            OvlTemplate->addOverload(*F);
88        }
89
90        return OvlTemplate;
91      }
92
93      return FuncTmpl;
94    }
95  }
96
97  return 0;
98}
99
100TemplateNameKind Sema::isTemplateName(Scope *S,
101                                      const IdentifierInfo &II,
102                                      SourceLocation IdLoc,
103                                      const CXXScopeSpec *SS,
104                                      TypeTy *ObjectTypePtr,
105                                      bool EnteringContext,
106                                      TemplateTy &TemplateResult) {
107  // Determine where to perform name lookup
108  DeclContext *LookupCtx = 0;
109  bool isDependent = false;
110  if (ObjectTypePtr) {
111    // This nested-name-specifier occurs in a member access expression, e.g.,
112    // x->B::f, and we are looking into the type of the object.
113    assert((!SS || !SS->isSet()) &&
114           "ObjectType and scope specifier cannot coexist");
115    QualType ObjectType = QualType::getFromOpaquePtr(ObjectTypePtr);
116    LookupCtx = computeDeclContext(ObjectType);
117    isDependent = ObjectType->isDependentType();
118  } else if (SS && SS->isSet()) {
119    // This nested-name-specifier occurs after another nested-name-specifier,
120    // so long into the context associated with the prior nested-name-specifier.
121
122    LookupCtx = computeDeclContext(*SS, EnteringContext);
123    isDependent = isDependentScopeSpecifier(*SS);
124  }
125
126  LookupResult Found;
127  bool ObjectTypeSearchedInScope = false;
128  if (LookupCtx) {
129    // Perform "qualified" name lookup into the declaration context we
130    // computed, which is either the type of the base of a member access
131    // expression or the declaration context associated with a prior
132    // nested-name-specifier.
133
134    // The declaration context must be complete.
135    if (!LookupCtx->isDependentContext() && RequireCompleteDeclContext(*SS))
136      return TNK_Non_template;
137
138    Found = LookupQualifiedName(LookupCtx, &II, LookupOrdinaryName);
139
140    if (ObjectTypePtr && Found.getKind() == LookupResult::NotFound) {
141      // C++ [basic.lookup.classref]p1:
142      //   In a class member access expression (5.2.5), if the . or -> token is
143      //   immediately followed by an identifier followed by a <, the
144      //   identifier must be looked up to determine whether the < is the
145      //   beginning of a template argument list (14.2) or a less-than operator.
146      //   The identifier is first looked up in the class of the object
147      //   expression. If the identifier is not found, it is then looked up in
148      //   the context of the entire postfix-expression and shall name a class
149      //   or function template.
150      //
151      // FIXME: When we're instantiating a template, do we actually have to
152      // look in the scope of the template? Seems fishy...
153      Found = LookupName(S, &II, LookupOrdinaryName);
154      ObjectTypeSearchedInScope = true;
155    }
156  } else if (isDependent) {
157    // We cannot look into a dependent object type or
158    return TNK_Non_template;
159  } else {
160    // Perform unqualified name lookup in the current scope.
161    Found = LookupName(S, &II, LookupOrdinaryName);
162  }
163
164  // FIXME: Cope with ambiguous name-lookup results.
165  assert(!Found.isAmbiguous() &&
166         "Cannot handle template name-lookup ambiguities");
167
168  NamedDecl *Template = isAcceptableTemplateName(Context, Found);
169  if (!Template)
170    return TNK_Non_template;
171
172  if (ObjectTypePtr && !ObjectTypeSearchedInScope) {
173    // C++ [basic.lookup.classref]p1:
174    //   [...] If the lookup in the class of the object expression finds a
175    //   template, the name is also looked up in the context of the entire
176    //   postfix-expression and [...]
177    //
178    LookupResult FoundOuter = LookupName(S, &II, LookupOrdinaryName);
179    // FIXME: Handle ambiguities in this lookup better
180    NamedDecl *OuterTemplate = isAcceptableTemplateName(Context, FoundOuter);
181
182    if (!OuterTemplate) {
183      //   - if the name is not found, the name found in the class of the
184      //     object expression is used, otherwise
185    } else if (!isa<ClassTemplateDecl>(OuterTemplate)) {
186      //   - if the name is found in the context of the entire
187      //     postfix-expression and does not name a class template, the name
188      //     found in the class of the object expression is used, otherwise
189    } else {
190      //   - if the name found is a class template, it must refer to the same
191      //     entity as the one found in the class of the object expression,
192      //     otherwise the program is ill-formed.
193      if (OuterTemplate->getCanonicalDecl() != Template->getCanonicalDecl()) {
194        Diag(IdLoc, diag::err_nested_name_member_ref_lookup_ambiguous)
195          << &II;
196        Diag(Template->getLocation(), diag::note_ambig_member_ref_object_type)
197          << QualType::getFromOpaquePtr(ObjectTypePtr);
198        Diag(OuterTemplate->getLocation(), diag::note_ambig_member_ref_scope);
199
200        // Recover by taking the template that we found in the object
201        // expression's type.
202      }
203    }
204  }
205
206  if (SS && SS->isSet() && !SS->isInvalid()) {
207    NestedNameSpecifier *Qualifier
208      = static_cast<NestedNameSpecifier *>(SS->getScopeRep());
209    if (OverloadedFunctionDecl *Ovl
210          = dyn_cast<OverloadedFunctionDecl>(Template))
211      TemplateResult
212        = TemplateTy::make(Context.getQualifiedTemplateName(Qualifier, false,
213                                                            Ovl));
214    else
215      TemplateResult
216        = TemplateTy::make(Context.getQualifiedTemplateName(Qualifier, false,
217                                                 cast<TemplateDecl>(Template)));
218  } else if (OverloadedFunctionDecl *Ovl
219               = dyn_cast<OverloadedFunctionDecl>(Template)) {
220    TemplateResult = TemplateTy::make(TemplateName(Ovl));
221  } else {
222    TemplateResult = TemplateTy::make(
223                                  TemplateName(cast<TemplateDecl>(Template)));
224  }
225
226  if (isa<ClassTemplateDecl>(Template) ||
227      isa<TemplateTemplateParmDecl>(Template))
228    return TNK_Type_template;
229
230  assert((isa<FunctionTemplateDecl>(Template) ||
231          isa<OverloadedFunctionDecl>(Template)) &&
232         "Unhandled template kind in Sema::isTemplateName");
233  return TNK_Function_template;
234}
235
236/// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
237/// that the template parameter 'PrevDecl' is being shadowed by a new
238/// declaration at location Loc. Returns true to indicate that this is
239/// an error, and false otherwise.
240bool Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
241  assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
242
243  // Microsoft Visual C++ permits template parameters to be shadowed.
244  if (getLangOptions().Microsoft)
245    return false;
246
247  // C++ [temp.local]p4:
248  //   A template-parameter shall not be redeclared within its
249  //   scope (including nested scopes).
250  Diag(Loc, diag::err_template_param_shadow)
251    << cast<NamedDecl>(PrevDecl)->getDeclName();
252  Diag(PrevDecl->getLocation(), diag::note_template_param_here);
253  return true;
254}
255
256/// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
257/// the parameter D to reference the templated declaration and return a pointer
258/// to the template declaration. Otherwise, do nothing to D and return null.
259TemplateDecl *Sema::AdjustDeclIfTemplate(DeclPtrTy &D) {
260  if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D.getAs<Decl>())) {
261    D = DeclPtrTy::make(Temp->getTemplatedDecl());
262    return Temp;
263  }
264  return 0;
265}
266
267/// ActOnTypeParameter - Called when a C++ template type parameter
268/// (e.g., "typename T") has been parsed. Typename specifies whether
269/// the keyword "typename" was used to declare the type parameter
270/// (otherwise, "class" was used), and KeyLoc is the location of the
271/// "class" or "typename" keyword. ParamName is the name of the
272/// parameter (NULL indicates an unnamed template parameter) and
273/// ParamName is the location of the parameter name (if any).
274/// If the type parameter has a default argument, it will be added
275/// later via ActOnTypeParameterDefault.
276Sema::DeclPtrTy Sema::ActOnTypeParameter(Scope *S, bool Typename, bool Ellipsis,
277                                         SourceLocation EllipsisLoc,
278                                         SourceLocation KeyLoc,
279                                         IdentifierInfo *ParamName,
280                                         SourceLocation ParamNameLoc,
281                                         unsigned Depth, unsigned Position) {
282  assert(S->isTemplateParamScope() &&
283         "Template type parameter not in template parameter scope!");
284  bool Invalid = false;
285
286  if (ParamName) {
287    NamedDecl *PrevDecl = LookupName(S, ParamName, LookupTagName);
288    if (PrevDecl && PrevDecl->isTemplateParameter())
289      Invalid = Invalid || DiagnoseTemplateParameterShadow(ParamNameLoc,
290                                                           PrevDecl);
291  }
292
293  SourceLocation Loc = ParamNameLoc;
294  if (!ParamName)
295    Loc = KeyLoc;
296
297  TemplateTypeParmDecl *Param
298    = TemplateTypeParmDecl::Create(Context, CurContext, Loc,
299                                   Depth, Position, ParamName, Typename,
300                                   Ellipsis);
301  if (Invalid)
302    Param->setInvalidDecl();
303
304  if (ParamName) {
305    // Add the template parameter into the current scope.
306    S->AddDecl(DeclPtrTy::make(Param));
307    IdResolver.AddDecl(Param);
308  }
309
310  return DeclPtrTy::make(Param);
311}
312
313/// ActOnTypeParameterDefault - Adds a default argument (the type
314/// Default) to the given template type parameter (TypeParam).
315void Sema::ActOnTypeParameterDefault(DeclPtrTy TypeParam,
316                                     SourceLocation EqualLoc,
317                                     SourceLocation DefaultLoc,
318                                     TypeTy *DefaultT) {
319  TemplateTypeParmDecl *Parm
320    = cast<TemplateTypeParmDecl>(TypeParam.getAs<Decl>());
321  // FIXME: Preserve type source info.
322  QualType Default = GetTypeFromParser(DefaultT);
323
324  // C++0x [temp.param]p9:
325  // A default template-argument may be specified for any kind of
326  // template-parameter that is not a template parameter pack.
327  if (Parm->isParameterPack()) {
328    Diag(DefaultLoc, diag::err_template_param_pack_default_arg);
329    return;
330  }
331
332  // C++ [temp.param]p14:
333  //   A template-parameter shall not be used in its own default argument.
334  // FIXME: Implement this check! Needs a recursive walk over the types.
335
336  // Check the template argument itself.
337  if (CheckTemplateArgument(Parm, Default, DefaultLoc)) {
338    Parm->setInvalidDecl();
339    return;
340  }
341
342  Parm->setDefaultArgument(Default, DefaultLoc, false);
343}
344
345/// \brief Check that the type of a non-type template parameter is
346/// well-formed.
347///
348/// \returns the (possibly-promoted) parameter type if valid;
349/// otherwise, produces a diagnostic and returns a NULL type.
350QualType
351Sema::CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc) {
352  // C++ [temp.param]p4:
353  //
354  // A non-type template-parameter shall have one of the following
355  // (optionally cv-qualified) types:
356  //
357  //       -- integral or enumeration type,
358  if (T->isIntegralType() || T->isEnumeralType() ||
359      //   -- pointer to object or pointer to function,
360      (T->isPointerType() &&
361       (T->getAs<PointerType>()->getPointeeType()->isObjectType() ||
362        T->getAs<PointerType>()->getPointeeType()->isFunctionType())) ||
363      //   -- reference to object or reference to function,
364      T->isReferenceType() ||
365      //   -- pointer to member.
366      T->isMemberPointerType() ||
367      // If T is a dependent type, we can't do the check now, so we
368      // assume that it is well-formed.
369      T->isDependentType())
370    return T;
371  // C++ [temp.param]p8:
372  //
373  //   A non-type template-parameter of type "array of T" or
374  //   "function returning T" is adjusted to be of type "pointer to
375  //   T" or "pointer to function returning T", respectively.
376  else if (T->isArrayType())
377    // FIXME: Keep the type prior to promotion?
378    return Context.getArrayDecayedType(T);
379  else if (T->isFunctionType())
380    // FIXME: Keep the type prior to promotion?
381    return Context.getPointerType(T);
382
383  Diag(Loc, diag::err_template_nontype_parm_bad_type)
384    << T;
385
386  return QualType();
387}
388
389/// ActOnNonTypeTemplateParameter - Called when a C++ non-type
390/// template parameter (e.g., "int Size" in "template<int Size>
391/// class Array") has been parsed. S is the current scope and D is
392/// the parsed declarator.
393Sema::DeclPtrTy Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
394                                                    unsigned Depth,
395                                                    unsigned Position) {
396  DeclaratorInfo *DInfo = 0;
397  QualType T = GetTypeForDeclarator(D, S, &DInfo);
398
399  assert(S->isTemplateParamScope() &&
400         "Non-type template parameter not in template parameter scope!");
401  bool Invalid = false;
402
403  IdentifierInfo *ParamName = D.getIdentifier();
404  if (ParamName) {
405    NamedDecl *PrevDecl = LookupName(S, ParamName, LookupTagName);
406    if (PrevDecl && PrevDecl->isTemplateParameter())
407      Invalid = Invalid || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
408                                                           PrevDecl);
409  }
410
411  T = CheckNonTypeTemplateParameterType(T, D.getIdentifierLoc());
412  if (T.isNull()) {
413    T = Context.IntTy; // Recover with an 'int' type.
414    Invalid = true;
415  }
416
417  NonTypeTemplateParmDecl *Param
418    = NonTypeTemplateParmDecl::Create(Context, CurContext, D.getIdentifierLoc(),
419                                      Depth, Position, ParamName, T, DInfo);
420  if (Invalid)
421    Param->setInvalidDecl();
422
423  if (D.getIdentifier()) {
424    // Add the template parameter into the current scope.
425    S->AddDecl(DeclPtrTy::make(Param));
426    IdResolver.AddDecl(Param);
427  }
428  return DeclPtrTy::make(Param);
429}
430
431/// \brief Adds a default argument to the given non-type template
432/// parameter.
433void Sema::ActOnNonTypeTemplateParameterDefault(DeclPtrTy TemplateParamD,
434                                                SourceLocation EqualLoc,
435                                                ExprArg DefaultE) {
436  NonTypeTemplateParmDecl *TemplateParm
437    = cast<NonTypeTemplateParmDecl>(TemplateParamD.getAs<Decl>());
438  Expr *Default = static_cast<Expr *>(DefaultE.get());
439
440  // C++ [temp.param]p14:
441  //   A template-parameter shall not be used in its own default argument.
442  // FIXME: Implement this check! Needs a recursive walk over the types.
443
444  // Check the well-formedness of the default template argument.
445  TemplateArgument Converted;
446  if (CheckTemplateArgument(TemplateParm, TemplateParm->getType(), Default,
447                            Converted)) {
448    TemplateParm->setInvalidDecl();
449    return;
450  }
451
452  TemplateParm->setDefaultArgument(DefaultE.takeAs<Expr>());
453}
454
455
456/// ActOnTemplateTemplateParameter - Called when a C++ template template
457/// parameter (e.g. T in template <template <typename> class T> class array)
458/// has been parsed. S is the current scope.
459Sema::DeclPtrTy Sema::ActOnTemplateTemplateParameter(Scope* S,
460                                                     SourceLocation TmpLoc,
461                                                     TemplateParamsTy *Params,
462                                                     IdentifierInfo *Name,
463                                                     SourceLocation NameLoc,
464                                                     unsigned Depth,
465                                                     unsigned Position) {
466  assert(S->isTemplateParamScope() &&
467         "Template template parameter not in template parameter scope!");
468
469  // Construct the parameter object.
470  TemplateTemplateParmDecl *Param =
471    TemplateTemplateParmDecl::Create(Context, CurContext, TmpLoc, Depth,
472                                     Position, Name,
473                                     (TemplateParameterList*)Params);
474
475  // Make sure the parameter is valid.
476  // FIXME: Decl object is not currently invalidated anywhere so this doesn't
477  // do anything yet. However, if the template parameter list or (eventual)
478  // default value is ever invalidated, that will propagate here.
479  bool Invalid = false;
480  if (Invalid) {
481    Param->setInvalidDecl();
482  }
483
484  // If the tt-param has a name, then link the identifier into the scope
485  // and lookup mechanisms.
486  if (Name) {
487    S->AddDecl(DeclPtrTy::make(Param));
488    IdResolver.AddDecl(Param);
489  }
490
491  return DeclPtrTy::make(Param);
492}
493
494/// \brief Adds a default argument to the given template template
495/// parameter.
496void Sema::ActOnTemplateTemplateParameterDefault(DeclPtrTy TemplateParamD,
497                                                 SourceLocation EqualLoc,
498                                                 ExprArg DefaultE) {
499  TemplateTemplateParmDecl *TemplateParm
500    = cast<TemplateTemplateParmDecl>(TemplateParamD.getAs<Decl>());
501
502  // Since a template-template parameter's default argument is an
503  // id-expression, it must be a DeclRefExpr.
504  DeclRefExpr *Default
505    = cast<DeclRefExpr>(static_cast<Expr *>(DefaultE.get()));
506
507  // C++ [temp.param]p14:
508  //   A template-parameter shall not be used in its own default argument.
509  // FIXME: Implement this check! Needs a recursive walk over the types.
510
511  // Check the well-formedness of the template argument.
512  if (!isa<TemplateDecl>(Default->getDecl())) {
513    Diag(Default->getSourceRange().getBegin(),
514         diag::err_template_arg_must_be_template)
515      << Default->getSourceRange();
516    TemplateParm->setInvalidDecl();
517    return;
518  }
519  if (CheckTemplateArgument(TemplateParm, Default)) {
520    TemplateParm->setInvalidDecl();
521    return;
522  }
523
524  DefaultE.release();
525  TemplateParm->setDefaultArgument(Default);
526}
527
528/// ActOnTemplateParameterList - Builds a TemplateParameterList that
529/// contains the template parameters in Params/NumParams.
530Sema::TemplateParamsTy *
531Sema::ActOnTemplateParameterList(unsigned Depth,
532                                 SourceLocation ExportLoc,
533                                 SourceLocation TemplateLoc,
534                                 SourceLocation LAngleLoc,
535                                 DeclPtrTy *Params, unsigned NumParams,
536                                 SourceLocation RAngleLoc) {
537  if (ExportLoc.isValid())
538    Diag(ExportLoc, diag::note_template_export_unsupported);
539
540  return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
541                                       (NamedDecl**)Params, NumParams,
542                                       RAngleLoc);
543}
544
545Sema::DeclResult
546Sema::CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
547                         SourceLocation KWLoc, const CXXScopeSpec &SS,
548                         IdentifierInfo *Name, SourceLocation NameLoc,
549                         AttributeList *Attr,
550                         TemplateParameterList *TemplateParams,
551                         AccessSpecifier AS) {
552  assert(TemplateParams && TemplateParams->size() > 0 &&
553         "No template parameters");
554  assert(TUK != TUK_Reference && "Can only declare or define class templates");
555  bool Invalid = false;
556
557  // Check that we can declare a template here.
558  if (CheckTemplateDeclScope(S, TemplateParams))
559    return true;
560
561  TagDecl::TagKind Kind = TagDecl::getTagKindForTypeSpec(TagSpec);
562  assert(Kind != TagDecl::TK_enum && "can't build template of enumerated type");
563
564  // There is no such thing as an unnamed class template.
565  if (!Name) {
566    Diag(KWLoc, diag::err_template_unnamed_class);
567    return true;
568  }
569
570  // Find any previous declaration with this name.
571  DeclContext *SemanticContext;
572  LookupResult Previous;
573  if (SS.isNotEmpty() && !SS.isInvalid()) {
574    SemanticContext = computeDeclContext(SS, true);
575    if (!SemanticContext) {
576      // FIXME: Produce a reasonable diagnostic here
577      return true;
578    }
579
580    Previous = LookupQualifiedName(SemanticContext, Name, LookupOrdinaryName,
581                                   true);
582  } else {
583    SemanticContext = CurContext;
584    Previous = LookupName(S, Name, LookupOrdinaryName, true);
585  }
586
587  assert(!Previous.isAmbiguous() && "Ambiguity in class template redecl?");
588  NamedDecl *PrevDecl = 0;
589  if (Previous.begin() != Previous.end())
590    PrevDecl = *Previous.begin();
591
592  if (PrevDecl && TUK == TUK_Friend) {
593    // C++ [namespace.memdef]p3:
594    //   [...] When looking for a prior declaration of a class or a function
595    //   declared as a friend, and when the name of the friend class or
596    //   function is neither a qualified name nor a template-id, scopes outside
597    //   the innermost enclosing namespace scope are not considered.
598    DeclContext *OutermostContext = CurContext;
599    while (!OutermostContext->isFileContext())
600      OutermostContext = OutermostContext->getLookupParent();
601
602    if (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
603        OutermostContext->Encloses(PrevDecl->getDeclContext())) {
604      SemanticContext = PrevDecl->getDeclContext();
605    } else {
606      // Declarations in outer scopes don't matter. However, the outermost
607      // context we computed is the semntic context for our new
608      // declaration.
609      PrevDecl = 0;
610      SemanticContext = OutermostContext;
611    }
612  } else if (PrevDecl && !isDeclInScope(PrevDecl, SemanticContext, S))
613    PrevDecl = 0;
614
615  // If there is a previous declaration with the same name, check
616  // whether this is a valid redeclaration.
617  ClassTemplateDecl *PrevClassTemplate
618    = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
619  if (PrevClassTemplate) {
620    // Ensure that the template parameter lists are compatible.
621    if (!TemplateParameterListsAreEqual(TemplateParams,
622                                   PrevClassTemplate->getTemplateParameters(),
623                                        /*Complain=*/true))
624      return true;
625
626    // C++ [temp.class]p4:
627    //   In a redeclaration, partial specialization, explicit
628    //   specialization or explicit instantiation of a class template,
629    //   the class-key shall agree in kind with the original class
630    //   template declaration (7.1.5.3).
631    RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
632    if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind, KWLoc, *Name)) {
633      Diag(KWLoc, diag::err_use_with_wrong_tag)
634        << Name
635        << CodeModificationHint::CreateReplacement(KWLoc,
636                            PrevRecordDecl->getKindName());
637      Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
638      Kind = PrevRecordDecl->getTagKind();
639    }
640
641    // Check for redefinition of this class template.
642    if (TUK == TUK_Definition) {
643      if (TagDecl *Def = PrevRecordDecl->getDefinition(Context)) {
644        Diag(NameLoc, diag::err_redefinition) << Name;
645        Diag(Def->getLocation(), diag::note_previous_definition);
646        // FIXME: Would it make sense to try to "forget" the previous
647        // definition, as part of error recovery?
648        return true;
649      }
650    }
651  } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
652    // Maybe we will complain about the shadowed template parameter.
653    DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
654    // Just pretend that we didn't see the previous declaration.
655    PrevDecl = 0;
656  } else if (PrevDecl) {
657    // C++ [temp]p5:
658    //   A class template shall not have the same name as any other
659    //   template, class, function, object, enumeration, enumerator,
660    //   namespace, or type in the same scope (3.3), except as specified
661    //   in (14.5.4).
662    Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
663    Diag(PrevDecl->getLocation(), diag::note_previous_definition);
664    return true;
665  }
666
667  // Check the template parameter list of this declaration, possibly
668  // merging in the template parameter list from the previous class
669  // template declaration.
670  if (CheckTemplateParameterList(TemplateParams,
671            PrevClassTemplate? PrevClassTemplate->getTemplateParameters() : 0))
672    Invalid = true;
673
674  // FIXME: If we had a scope specifier, we better have a previous template
675  // declaration!
676
677  CXXRecordDecl *NewClass =
678    CXXRecordDecl::Create(Context, Kind, SemanticContext, NameLoc, Name, KWLoc,
679                          PrevClassTemplate?
680                            PrevClassTemplate->getTemplatedDecl() : 0,
681                          /*DelayTypeCreation=*/true);
682
683  ClassTemplateDecl *NewTemplate
684    = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
685                                DeclarationName(Name), TemplateParams,
686                                NewClass, PrevClassTemplate);
687  NewClass->setDescribedClassTemplate(NewTemplate);
688
689  // Build the type for the class template declaration now.
690  QualType T =
691    Context.getTypeDeclType(NewClass,
692                            PrevClassTemplate?
693                              PrevClassTemplate->getTemplatedDecl() : 0);
694  assert(T->isDependentType() && "Class template type is not dependent?");
695  (void)T;
696
697  // Set the access specifier.
698  if (!Invalid && TUK != TUK_Friend)
699    SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
700
701  // Set the lexical context of these templates
702  NewClass->setLexicalDeclContext(CurContext);
703  NewTemplate->setLexicalDeclContext(CurContext);
704
705  if (TUK == TUK_Definition)
706    NewClass->startDefinition();
707
708  if (Attr)
709    ProcessDeclAttributeList(S, NewClass, Attr);
710
711  if (TUK != TUK_Friend)
712    PushOnScopeChains(NewTemplate, S);
713  else {
714    if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
715      NewTemplate->setAccess(PrevClassTemplate->getAccess());
716      NewClass->setAccess(PrevClassTemplate->getAccess());
717    }
718
719    NewTemplate->setObjectOfFriendDecl(/* PreviouslyDeclared = */
720                                       PrevClassTemplate != NULL);
721
722    // Friend templates are visible in fairly strange ways.
723    if (!CurContext->isDependentContext()) {
724      DeclContext *DC = SemanticContext->getLookupContext();
725      DC->makeDeclVisibleInContext(NewTemplate, /* Recoverable = */ false);
726      if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
727        PushOnScopeChains(NewTemplate, EnclosingScope,
728                          /* AddToContext = */ false);
729    }
730
731    FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
732                                            NewClass->getLocation(),
733                                            NewTemplate,
734                                    /*FIXME:*/NewClass->getLocation());
735    Friend->setAccess(AS_public);
736    CurContext->addDecl(Friend);
737  }
738
739  if (Invalid) {
740    NewTemplate->setInvalidDecl();
741    NewClass->setInvalidDecl();
742  }
743  return DeclPtrTy::make(NewTemplate);
744}
745
746/// \brief Checks the validity of a template parameter list, possibly
747/// considering the template parameter list from a previous
748/// declaration.
749///
750/// If an "old" template parameter list is provided, it must be
751/// equivalent (per TemplateParameterListsAreEqual) to the "new"
752/// template parameter list.
753///
754/// \param NewParams Template parameter list for a new template
755/// declaration. This template parameter list will be updated with any
756/// default arguments that are carried through from the previous
757/// template parameter list.
758///
759/// \param OldParams If provided, template parameter list from a
760/// previous declaration of the same template. Default template
761/// arguments will be merged from the old template parameter list to
762/// the new template parameter list.
763///
764/// \returns true if an error occurred, false otherwise.
765bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
766                                      TemplateParameterList *OldParams) {
767  bool Invalid = false;
768
769  // C++ [temp.param]p10:
770  //   The set of default template-arguments available for use with a
771  //   template declaration or definition is obtained by merging the
772  //   default arguments from the definition (if in scope) and all
773  //   declarations in scope in the same way default function
774  //   arguments are (8.3.6).
775  bool SawDefaultArgument = false;
776  SourceLocation PreviousDefaultArgLoc;
777
778  bool SawParameterPack = false;
779  SourceLocation ParameterPackLoc;
780
781  // Dummy initialization to avoid warnings.
782  TemplateParameterList::iterator OldParam = NewParams->end();
783  if (OldParams)
784    OldParam = OldParams->begin();
785
786  for (TemplateParameterList::iterator NewParam = NewParams->begin(),
787                                    NewParamEnd = NewParams->end();
788       NewParam != NewParamEnd; ++NewParam) {
789    // Variables used to diagnose redundant default arguments
790    bool RedundantDefaultArg = false;
791    SourceLocation OldDefaultLoc;
792    SourceLocation NewDefaultLoc;
793
794    // Variables used to diagnose missing default arguments
795    bool MissingDefaultArg = false;
796
797    // C++0x [temp.param]p11:
798    // If a template parameter of a class template is a template parameter pack,
799    // it must be the last template parameter.
800    if (SawParameterPack) {
801      Diag(ParameterPackLoc,
802           diag::err_template_param_pack_must_be_last_template_parameter);
803      Invalid = true;
804    }
805
806    // Merge default arguments for template type parameters.
807    if (TemplateTypeParmDecl *NewTypeParm
808          = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
809      TemplateTypeParmDecl *OldTypeParm
810          = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : 0;
811
812      if (NewTypeParm->isParameterPack()) {
813        assert(!NewTypeParm->hasDefaultArgument() &&
814               "Parameter packs can't have a default argument!");
815        SawParameterPack = true;
816        ParameterPackLoc = NewTypeParm->getLocation();
817      } else if (OldTypeParm && OldTypeParm->hasDefaultArgument() &&
818          NewTypeParm->hasDefaultArgument()) {
819        OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
820        NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
821        SawDefaultArgument = true;
822        RedundantDefaultArg = true;
823        PreviousDefaultArgLoc = NewDefaultLoc;
824      } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
825        // Merge the default argument from the old declaration to the
826        // new declaration.
827        SawDefaultArgument = true;
828        NewTypeParm->setDefaultArgument(OldTypeParm->getDefaultArgument(),
829                                        OldTypeParm->getDefaultArgumentLoc(),
830                                        true);
831        PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
832      } else if (NewTypeParm->hasDefaultArgument()) {
833        SawDefaultArgument = true;
834        PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
835      } else if (SawDefaultArgument)
836        MissingDefaultArg = true;
837    } else if (NonTypeTemplateParmDecl *NewNonTypeParm
838               = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
839      // Merge default arguments for non-type template parameters
840      NonTypeTemplateParmDecl *OldNonTypeParm
841        = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : 0;
842      if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument() &&
843          NewNonTypeParm->hasDefaultArgument()) {
844        OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
845        NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
846        SawDefaultArgument = true;
847        RedundantDefaultArg = true;
848        PreviousDefaultArgLoc = NewDefaultLoc;
849      } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
850        // Merge the default argument from the old declaration to the
851        // new declaration.
852        SawDefaultArgument = true;
853        // FIXME: We need to create a new kind of "default argument"
854        // expression that points to a previous template template
855        // parameter.
856        NewNonTypeParm->setDefaultArgument(
857                                        OldNonTypeParm->getDefaultArgument());
858        PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
859      } else if (NewNonTypeParm->hasDefaultArgument()) {
860        SawDefaultArgument = true;
861        PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
862      } else if (SawDefaultArgument)
863        MissingDefaultArg = true;
864    } else {
865    // Merge default arguments for template template parameters
866      TemplateTemplateParmDecl *NewTemplateParm
867        = cast<TemplateTemplateParmDecl>(*NewParam);
868      TemplateTemplateParmDecl *OldTemplateParm
869        = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : 0;
870      if (OldTemplateParm && OldTemplateParm->hasDefaultArgument() &&
871          NewTemplateParm->hasDefaultArgument()) {
872        OldDefaultLoc = OldTemplateParm->getDefaultArgumentLoc();
873        NewDefaultLoc = NewTemplateParm->getDefaultArgumentLoc();
874        SawDefaultArgument = true;
875        RedundantDefaultArg = true;
876        PreviousDefaultArgLoc = NewDefaultLoc;
877      } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
878        // Merge the default argument from the old declaration to the
879        // new declaration.
880        SawDefaultArgument = true;
881        // FIXME: We need to create a new kind of "default argument" expression
882        // that points to a previous template template parameter.
883        NewTemplateParm->setDefaultArgument(
884                                        OldTemplateParm->getDefaultArgument());
885        PreviousDefaultArgLoc = OldTemplateParm->getDefaultArgumentLoc();
886      } else if (NewTemplateParm->hasDefaultArgument()) {
887        SawDefaultArgument = true;
888        PreviousDefaultArgLoc = NewTemplateParm->getDefaultArgumentLoc();
889      } else if (SawDefaultArgument)
890        MissingDefaultArg = true;
891    }
892
893    if (RedundantDefaultArg) {
894      // C++ [temp.param]p12:
895      //   A template-parameter shall not be given default arguments
896      //   by two different declarations in the same scope.
897      Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
898      Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
899      Invalid = true;
900    } else if (MissingDefaultArg) {
901      // C++ [temp.param]p11:
902      //   If a template-parameter has a default template-argument,
903      //   all subsequent template-parameters shall have a default
904      //   template-argument supplied.
905      Diag((*NewParam)->getLocation(),
906           diag::err_template_param_default_arg_missing);
907      Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
908      Invalid = true;
909    }
910
911    // If we have an old template parameter list that we're merging
912    // in, move on to the next parameter.
913    if (OldParams)
914      ++OldParam;
915  }
916
917  return Invalid;
918}
919
920/// \brief Match the given template parameter lists to the given scope
921/// specifier, returning the template parameter list that applies to the
922/// name.
923///
924/// \param DeclStartLoc the start of the declaration that has a scope
925/// specifier or a template parameter list.
926///
927/// \param SS the scope specifier that will be matched to the given template
928/// parameter lists. This scope specifier precedes a qualified name that is
929/// being declared.
930///
931/// \param ParamLists the template parameter lists, from the outermost to the
932/// innermost template parameter lists.
933///
934/// \param NumParamLists the number of template parameter lists in ParamLists.
935///
936/// \returns the template parameter list, if any, that corresponds to the
937/// name that is preceded by the scope specifier @p SS. This template
938/// parameter list may be have template parameters (if we're declaring a
939/// template) or may have no template parameters (if we're declaring a
940/// template specialization), or may be NULL (if we were's declaring isn't
941/// itself a template).
942TemplateParameterList *
943Sema::MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc,
944                                              const CXXScopeSpec &SS,
945                                          TemplateParameterList **ParamLists,
946                                              unsigned NumParamLists) {
947  // Find the template-ids that occur within the nested-name-specifier. These
948  // template-ids will match up with the template parameter lists.
949  llvm::SmallVector<const TemplateSpecializationType *, 4>
950    TemplateIdsInSpecifier;
951  for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
952       NNS; NNS = NNS->getPrefix()) {
953    if (const TemplateSpecializationType *SpecType
954          = dyn_cast_or_null<TemplateSpecializationType>(NNS->getAsType())) {
955      TemplateDecl *Template = SpecType->getTemplateName().getAsTemplateDecl();
956      if (!Template)
957        continue; // FIXME: should this be an error? probably...
958
959      if (const RecordType *Record = SpecType->getAs<RecordType>()) {
960        ClassTemplateSpecializationDecl *SpecDecl
961          = cast<ClassTemplateSpecializationDecl>(Record->getDecl());
962        // If the nested name specifier refers to an explicit specialization,
963        // we don't need a template<> header.
964        // FIXME: revisit this approach once we cope with specializations
965        // properly.
966        if (SpecDecl->getSpecializationKind() == TSK_ExplicitSpecialization)
967          continue;
968      }
969
970      TemplateIdsInSpecifier.push_back(SpecType);
971    }
972  }
973
974  // Reverse the list of template-ids in the scope specifier, so that we can
975  // more easily match up the template-ids and the template parameter lists.
976  std::reverse(TemplateIdsInSpecifier.begin(), TemplateIdsInSpecifier.end());
977
978  SourceLocation FirstTemplateLoc = DeclStartLoc;
979  if (NumParamLists)
980    FirstTemplateLoc = ParamLists[0]->getTemplateLoc();
981
982  // Match the template-ids found in the specifier to the template parameter
983  // lists.
984  unsigned Idx = 0;
985  for (unsigned NumTemplateIds = TemplateIdsInSpecifier.size();
986       Idx != NumTemplateIds; ++Idx) {
987    QualType TemplateId = QualType(TemplateIdsInSpecifier[Idx], 0);
988    bool DependentTemplateId = TemplateId->isDependentType();
989    if (Idx >= NumParamLists) {
990      // We have a template-id without a corresponding template parameter
991      // list.
992      if (DependentTemplateId) {
993        // FIXME: the location information here isn't great.
994        Diag(SS.getRange().getBegin(),
995             diag::err_template_spec_needs_template_parameters)
996          << TemplateId
997          << SS.getRange();
998      } else {
999        Diag(SS.getRange().getBegin(), diag::err_template_spec_needs_header)
1000          << SS.getRange()
1001          << CodeModificationHint::CreateInsertion(FirstTemplateLoc,
1002                                                   "template<> ");
1003      }
1004      return 0;
1005    }
1006
1007    // Check the template parameter list against its corresponding template-id.
1008    if (DependentTemplateId) {
1009      TemplateDecl *Template
1010        = TemplateIdsInSpecifier[Idx]->getTemplateName().getAsTemplateDecl();
1011
1012      if (ClassTemplateDecl *ClassTemplate
1013            = dyn_cast<ClassTemplateDecl>(Template)) {
1014        TemplateParameterList *ExpectedTemplateParams = 0;
1015        // Is this template-id naming the primary template?
1016        if (Context.hasSameType(TemplateId,
1017                             ClassTemplate->getInjectedClassNameType(Context)))
1018          ExpectedTemplateParams = ClassTemplate->getTemplateParameters();
1019        // ... or a partial specialization?
1020        else if (ClassTemplatePartialSpecializationDecl *PartialSpec
1021                   = ClassTemplate->findPartialSpecialization(TemplateId))
1022          ExpectedTemplateParams = PartialSpec->getTemplateParameters();
1023
1024        if (ExpectedTemplateParams)
1025          TemplateParameterListsAreEqual(ParamLists[Idx],
1026                                         ExpectedTemplateParams,
1027                                         true);
1028      }
1029    } else if (ParamLists[Idx]->size() > 0)
1030      Diag(ParamLists[Idx]->getTemplateLoc(),
1031           diag::err_template_param_list_matches_nontemplate)
1032        << TemplateId
1033        << ParamLists[Idx]->getSourceRange();
1034  }
1035
1036  // If there were at least as many template-ids as there were template
1037  // parameter lists, then there are no template parameter lists remaining for
1038  // the declaration itself.
1039  if (Idx >= NumParamLists)
1040    return 0;
1041
1042  // If there were too many template parameter lists, complain about that now.
1043  if (Idx != NumParamLists - 1) {
1044    while (Idx < NumParamLists - 1) {
1045      Diag(ParamLists[Idx]->getTemplateLoc(),
1046           diag::err_template_spec_extra_headers)
1047        << SourceRange(ParamLists[Idx]->getTemplateLoc(),
1048                       ParamLists[Idx]->getRAngleLoc());
1049      ++Idx;
1050    }
1051  }
1052
1053  // Return the last template parameter list, which corresponds to the
1054  // entity being declared.
1055  return ParamLists[NumParamLists - 1];
1056}
1057
1058/// \brief Translates template arguments as provided by the parser
1059/// into template arguments used by semantic analysis.
1060void Sema::translateTemplateArguments(ASTTemplateArgsPtr &TemplateArgsIn,
1061                                      SourceLocation *TemplateArgLocs,
1062                     llvm::SmallVector<TemplateArgument, 16> &TemplateArgs) {
1063  TemplateArgs.reserve(TemplateArgsIn.size());
1064
1065  void **Args = TemplateArgsIn.getArgs();
1066  bool *ArgIsType = TemplateArgsIn.getArgIsType();
1067  for (unsigned Arg = 0, Last = TemplateArgsIn.size(); Arg != Last; ++Arg) {
1068    TemplateArgs.push_back(
1069      ArgIsType[Arg]? TemplateArgument(TemplateArgLocs[Arg],
1070                                       //FIXME: Preserve type source info.
1071                                       Sema::GetTypeFromParser(Args[Arg]))
1072                    : TemplateArgument(reinterpret_cast<Expr *>(Args[Arg])));
1073  }
1074}
1075
1076QualType Sema::CheckTemplateIdType(TemplateName Name,
1077                                   SourceLocation TemplateLoc,
1078                                   SourceLocation LAngleLoc,
1079                                   const TemplateArgument *TemplateArgs,
1080                                   unsigned NumTemplateArgs,
1081                                   SourceLocation RAngleLoc) {
1082  TemplateDecl *Template = Name.getAsTemplateDecl();
1083  if (!Template) {
1084    // The template name does not resolve to a template, so we just
1085    // build a dependent template-id type.
1086    return Context.getTemplateSpecializationType(Name, TemplateArgs,
1087                                                 NumTemplateArgs);
1088  }
1089
1090  // Check that the template argument list is well-formed for this
1091  // template.
1092  TemplateArgumentListBuilder Converted(Template->getTemplateParameters(),
1093                                        NumTemplateArgs);
1094  if (CheckTemplateArgumentList(Template, TemplateLoc, LAngleLoc,
1095                                TemplateArgs, NumTemplateArgs, RAngleLoc,
1096                                false, Converted))
1097    return QualType();
1098
1099  assert((Converted.structuredSize() ==
1100            Template->getTemplateParameters()->size()) &&
1101         "Converted template argument list is too short!");
1102
1103  QualType CanonType;
1104
1105  if (TemplateSpecializationType::anyDependentTemplateArguments(
1106                                                      TemplateArgs,
1107                                                      NumTemplateArgs)) {
1108    // This class template specialization is a dependent
1109    // type. Therefore, its canonical type is another class template
1110    // specialization type that contains all of the converted
1111    // arguments in canonical form. This ensures that, e.g., A<T> and
1112    // A<T, T> have identical types when A is declared as:
1113    //
1114    //   template<typename T, typename U = T> struct A;
1115    TemplateName CanonName = Context.getCanonicalTemplateName(Name);
1116    CanonType = Context.getTemplateSpecializationType(CanonName,
1117                                                   Converted.getFlatArguments(),
1118                                                   Converted.flatSize());
1119
1120    // FIXME: CanonType is not actually the canonical type, and unfortunately
1121    // it is a TemplateTypeSpecializationType that we will never use again.
1122    // In the future, we need to teach getTemplateSpecializationType to only
1123    // build the canonical type and return that to us.
1124    CanonType = Context.getCanonicalType(CanonType);
1125  } else if (ClassTemplateDecl *ClassTemplate
1126               = dyn_cast<ClassTemplateDecl>(Template)) {
1127    // Find the class template specialization declaration that
1128    // corresponds to these arguments.
1129    llvm::FoldingSetNodeID ID;
1130    ClassTemplateSpecializationDecl::Profile(ID,
1131                                             Converted.getFlatArguments(),
1132                                             Converted.flatSize(),
1133                                             Context);
1134    void *InsertPos = 0;
1135    ClassTemplateSpecializationDecl *Decl
1136      = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
1137    if (!Decl) {
1138      // This is the first time we have referenced this class template
1139      // specialization. Create the canonical declaration and add it to
1140      // the set of specializations.
1141      Decl = ClassTemplateSpecializationDecl::Create(Context,
1142                                    ClassTemplate->getDeclContext(),
1143                                    ClassTemplate->getLocation(),
1144                                    ClassTemplate,
1145                                    Converted, 0);
1146      ClassTemplate->getSpecializations().InsertNode(Decl, InsertPos);
1147      Decl->setLexicalDeclContext(CurContext);
1148    }
1149
1150    CanonType = Context.getTypeDeclType(Decl);
1151  }
1152
1153  // Build the fully-sugared type for this class template
1154  // specialization, which refers back to the class template
1155  // specialization we created or found.
1156  //FIXME: Preserve type source info.
1157  return Context.getTemplateSpecializationType(Name, TemplateArgs,
1158                                               NumTemplateArgs, CanonType);
1159}
1160
1161Action::TypeResult
1162Sema::ActOnTemplateIdType(TemplateTy TemplateD, SourceLocation TemplateLoc,
1163                          SourceLocation LAngleLoc,
1164                          ASTTemplateArgsPtr TemplateArgsIn,
1165                          SourceLocation *TemplateArgLocs,
1166                          SourceLocation RAngleLoc) {
1167  TemplateName Template = TemplateD.getAsVal<TemplateName>();
1168
1169  // Translate the parser's template argument list in our AST format.
1170  llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
1171  translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
1172
1173  QualType Result = CheckTemplateIdType(Template, TemplateLoc, LAngleLoc,
1174                                        TemplateArgs.data(),
1175                                        TemplateArgs.size(),
1176                                        RAngleLoc);
1177  TemplateArgsIn.release();
1178
1179  if (Result.isNull())
1180    return true;
1181
1182  return Result.getAsOpaquePtr();
1183}
1184
1185Sema::TypeResult Sema::ActOnTagTemplateIdType(TypeResult TypeResult,
1186                                              TagUseKind TUK,
1187                                              DeclSpec::TST TagSpec,
1188                                              SourceLocation TagLoc) {
1189  if (TypeResult.isInvalid())
1190    return Sema::TypeResult();
1191
1192  QualType Type = QualType::getFromOpaquePtr(TypeResult.get());
1193
1194  // Verify the tag specifier.
1195  TagDecl::TagKind TagKind = TagDecl::getTagKindForTypeSpec(TagSpec);
1196
1197  if (const RecordType *RT = Type->getAs<RecordType>()) {
1198    RecordDecl *D = RT->getDecl();
1199
1200    IdentifierInfo *Id = D->getIdentifier();
1201    assert(Id && "templated class must have an identifier");
1202
1203    if (!isAcceptableTagRedeclaration(D, TagKind, TagLoc, *Id)) {
1204      Diag(TagLoc, diag::err_use_with_wrong_tag)
1205        << Type
1206        << CodeModificationHint::CreateReplacement(SourceRange(TagLoc),
1207                                                   D->getKindName());
1208      Diag(D->getLocation(), diag::note_previous_use);
1209    }
1210  }
1211
1212  QualType ElabType = Context.getElaboratedType(Type, TagKind);
1213
1214  return ElabType.getAsOpaquePtr();
1215}
1216
1217Sema::OwningExprResult Sema::BuildTemplateIdExpr(TemplateName Template,
1218                                                 SourceLocation TemplateNameLoc,
1219                                                 SourceLocation LAngleLoc,
1220                                           const TemplateArgument *TemplateArgs,
1221                                                 unsigned NumTemplateArgs,
1222                                                 SourceLocation RAngleLoc) {
1223  // FIXME: Can we do any checking at this point? I guess we could check the
1224  // template arguments that we have against the template name, if the template
1225  // name refers to a single template. That's not a terribly common case,
1226  // though.
1227  return Owned(TemplateIdRefExpr::Create(Context,
1228                                         /*FIXME: New type?*/Context.OverloadTy,
1229                                         /*FIXME: Necessary?*/0,
1230                                         /*FIXME: Necessary?*/SourceRange(),
1231                                         Template, TemplateNameLoc, LAngleLoc,
1232                                         TemplateArgs,
1233                                         NumTemplateArgs, RAngleLoc));
1234}
1235
1236Sema::OwningExprResult Sema::ActOnTemplateIdExpr(TemplateTy TemplateD,
1237                                                 SourceLocation TemplateNameLoc,
1238                                                 SourceLocation LAngleLoc,
1239                                              ASTTemplateArgsPtr TemplateArgsIn,
1240                                                SourceLocation *TemplateArgLocs,
1241                                                 SourceLocation RAngleLoc) {
1242  TemplateName Template = TemplateD.getAsVal<TemplateName>();
1243
1244  // Translate the parser's template argument list in our AST format.
1245  llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
1246  translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
1247  TemplateArgsIn.release();
1248
1249  return BuildTemplateIdExpr(Template, TemplateNameLoc, LAngleLoc,
1250                             TemplateArgs.data(), TemplateArgs.size(),
1251                             RAngleLoc);
1252}
1253
1254Sema::OwningExprResult
1255Sema::ActOnMemberTemplateIdReferenceExpr(Scope *S, ExprArg Base,
1256                                         SourceLocation OpLoc,
1257                                         tok::TokenKind OpKind,
1258                                         const CXXScopeSpec &SS,
1259                                         TemplateTy TemplateD,
1260                                         SourceLocation TemplateNameLoc,
1261                                         SourceLocation LAngleLoc,
1262                                         ASTTemplateArgsPtr TemplateArgsIn,
1263                                         SourceLocation *TemplateArgLocs,
1264                                         SourceLocation RAngleLoc) {
1265  TemplateName Template = TemplateD.getAsVal<TemplateName>();
1266
1267  // FIXME: We're going to end up looking up the template based on its name,
1268  // twice!
1269  DeclarationName Name;
1270  if (TemplateDecl *ActualTemplate = Template.getAsTemplateDecl())
1271    Name = ActualTemplate->getDeclName();
1272  else if (OverloadedFunctionDecl *Ovl = Template.getAsOverloadedFunctionDecl())
1273    Name = Ovl->getDeclName();
1274  else
1275    Name = Template.getAsDependentTemplateName()->getName();
1276
1277  // Translate the parser's template argument list in our AST format.
1278  llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
1279  translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
1280  TemplateArgsIn.release();
1281
1282  // Do we have the save the actual template name? We might need it...
1283  return BuildMemberReferenceExpr(S, move(Base), OpLoc, OpKind, TemplateNameLoc,
1284                                  Name, true, LAngleLoc,
1285                                  TemplateArgs.data(), TemplateArgs.size(),
1286                                  RAngleLoc, DeclPtrTy(), &SS);
1287}
1288
1289/// \brief Form a dependent template name.
1290///
1291/// This action forms a dependent template name given the template
1292/// name and its (presumably dependent) scope specifier. For
1293/// example, given "MetaFun::template apply", the scope specifier \p
1294/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
1295/// of the "template" keyword, and "apply" is the \p Name.
1296Sema::TemplateTy
1297Sema::ActOnDependentTemplateName(SourceLocation TemplateKWLoc,
1298                                 const IdentifierInfo &Name,
1299                                 SourceLocation NameLoc,
1300                                 const CXXScopeSpec &SS,
1301                                 TypeTy *ObjectType) {
1302  if ((ObjectType &&
1303       computeDeclContext(QualType::getFromOpaquePtr(ObjectType))) ||
1304      (SS.isSet() && computeDeclContext(SS, false))) {
1305    // C++0x [temp.names]p5:
1306    //   If a name prefixed by the keyword template is not the name of
1307    //   a template, the program is ill-formed. [Note: the keyword
1308    //   template may not be applied to non-template members of class
1309    //   templates. -end note ] [ Note: as is the case with the
1310    //   typename prefix, the template prefix is allowed in cases
1311    //   where it is not strictly necessary; i.e., when the
1312    //   nested-name-specifier or the expression on the left of the ->
1313    //   or . is not dependent on a template-parameter, or the use
1314    //   does not appear in the scope of a template. -end note]
1315    //
1316    // Note: C++03 was more strict here, because it banned the use of
1317    // the "template" keyword prior to a template-name that was not a
1318    // dependent name. C++ DR468 relaxed this requirement (the
1319    // "template" keyword is now permitted). We follow the C++0x
1320    // rules, even in C++03 mode, retroactively applying the DR.
1321    TemplateTy Template;
1322    TemplateNameKind TNK = isTemplateName(0, Name, NameLoc, &SS, ObjectType,
1323                                          false, Template);
1324    if (TNK == TNK_Non_template) {
1325      Diag(NameLoc, diag::err_template_kw_refers_to_non_template)
1326        << &Name;
1327      return TemplateTy();
1328    }
1329
1330    return Template;
1331  }
1332
1333  NestedNameSpecifier *Qualifier
1334    = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
1335  return TemplateTy::make(Context.getDependentTemplateName(Qualifier, &Name));
1336}
1337
1338bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
1339                                     const TemplateArgument &Arg,
1340                                     TemplateArgumentListBuilder &Converted) {
1341  // Check template type parameter.
1342  if (Arg.getKind() != TemplateArgument::Type) {
1343    // C++ [temp.arg.type]p1:
1344    //   A template-argument for a template-parameter which is a
1345    //   type shall be a type-id.
1346
1347    // We have a template type parameter but the template argument
1348    // is not a type.
1349    Diag(Arg.getLocation(), diag::err_template_arg_must_be_type);
1350    Diag(Param->getLocation(), diag::note_template_param_here);
1351
1352    return true;
1353  }
1354
1355  if (CheckTemplateArgument(Param, Arg.getAsType(), Arg.getLocation()))
1356    return true;
1357
1358  // Add the converted template type argument.
1359  Converted.Append(
1360                 TemplateArgument(Arg.getLocation(),
1361                                  Context.getCanonicalType(Arg.getAsType())));
1362  return false;
1363}
1364
1365/// \brief Check that the given template argument list is well-formed
1366/// for specializing the given template.
1367bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
1368                                     SourceLocation TemplateLoc,
1369                                     SourceLocation LAngleLoc,
1370                                     const TemplateArgument *TemplateArgs,
1371                                     unsigned NumTemplateArgs,
1372                                     SourceLocation RAngleLoc,
1373                                     bool PartialTemplateArgs,
1374                                     TemplateArgumentListBuilder &Converted) {
1375  TemplateParameterList *Params = Template->getTemplateParameters();
1376  unsigned NumParams = Params->size();
1377  unsigned NumArgs = NumTemplateArgs;
1378  bool Invalid = false;
1379
1380  bool HasParameterPack =
1381    NumParams > 0 && Params->getParam(NumParams - 1)->isTemplateParameterPack();
1382
1383  if ((NumArgs > NumParams && !HasParameterPack) ||
1384      (NumArgs < Params->getMinRequiredArguments() &&
1385       !PartialTemplateArgs)) {
1386    // FIXME: point at either the first arg beyond what we can handle,
1387    // or the '>', depending on whether we have too many or too few
1388    // arguments.
1389    SourceRange Range;
1390    if (NumArgs > NumParams)
1391      Range = SourceRange(TemplateArgs[NumParams].getLocation(), RAngleLoc);
1392    Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
1393      << (NumArgs > NumParams)
1394      << (isa<ClassTemplateDecl>(Template)? 0 :
1395          isa<FunctionTemplateDecl>(Template)? 1 :
1396          isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
1397      << Template << Range;
1398    Diag(Template->getLocation(), diag::note_template_decl_here)
1399      << Params->getSourceRange();
1400    Invalid = true;
1401  }
1402
1403  // C++ [temp.arg]p1:
1404  //   [...] The type and form of each template-argument specified in
1405  //   a template-id shall match the type and form specified for the
1406  //   corresponding parameter declared by the template in its
1407  //   template-parameter-list.
1408  unsigned ArgIdx = 0;
1409  for (TemplateParameterList::iterator Param = Params->begin(),
1410                                       ParamEnd = Params->end();
1411       Param != ParamEnd; ++Param, ++ArgIdx) {
1412    if (ArgIdx > NumArgs && PartialTemplateArgs)
1413      break;
1414
1415    // Decode the template argument
1416    TemplateArgument Arg;
1417    if (ArgIdx >= NumArgs) {
1418      // Retrieve the default template argument from the template
1419      // parameter.
1420      if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
1421        if (TTP->isParameterPack()) {
1422          // We have an empty argument pack.
1423          Converted.BeginPack();
1424          Converted.EndPack();
1425          break;
1426        }
1427
1428        if (!TTP->hasDefaultArgument())
1429          break;
1430
1431        QualType ArgType = TTP->getDefaultArgument();
1432
1433        // If the argument type is dependent, instantiate it now based
1434        // on the previously-computed template arguments.
1435        if (ArgType->isDependentType()) {
1436          InstantiatingTemplate Inst(*this, TemplateLoc,
1437                                     Template, Converted.getFlatArguments(),
1438                                     Converted.flatSize(),
1439                                     SourceRange(TemplateLoc, RAngleLoc));
1440
1441          TemplateArgumentList TemplateArgs(Context, Converted,
1442                                            /*TakeArgs=*/false);
1443          ArgType = SubstType(ArgType,
1444                              MultiLevelTemplateArgumentList(TemplateArgs),
1445                              TTP->getDefaultArgumentLoc(),
1446                              TTP->getDeclName());
1447        }
1448
1449        if (ArgType.isNull())
1450          return true;
1451
1452        Arg = TemplateArgument(TTP->getLocation(), ArgType);
1453      } else if (NonTypeTemplateParmDecl *NTTP
1454                   = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
1455        if (!NTTP->hasDefaultArgument())
1456          break;
1457
1458        InstantiatingTemplate Inst(*this, TemplateLoc,
1459                                   Template, Converted.getFlatArguments(),
1460                                   Converted.flatSize(),
1461                                   SourceRange(TemplateLoc, RAngleLoc));
1462
1463        TemplateArgumentList TemplateArgs(Context, Converted,
1464                                          /*TakeArgs=*/false);
1465
1466        Sema::OwningExprResult E
1467          = SubstExpr(NTTP->getDefaultArgument(),
1468                      MultiLevelTemplateArgumentList(TemplateArgs));
1469        if (E.isInvalid())
1470          return true;
1471
1472        Arg = TemplateArgument(E.takeAs<Expr>());
1473      } else {
1474        TemplateTemplateParmDecl *TempParm
1475          = cast<TemplateTemplateParmDecl>(*Param);
1476
1477        if (!TempParm->hasDefaultArgument())
1478          break;
1479
1480        // FIXME: Subst default argument
1481        Arg = TemplateArgument(TempParm->getDefaultArgument());
1482      }
1483    } else {
1484      // Retrieve the template argument produced by the user.
1485      Arg = TemplateArgs[ArgIdx];
1486    }
1487
1488
1489    if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
1490      if (TTP->isParameterPack()) {
1491        Converted.BeginPack();
1492        // Check all the remaining arguments (if any).
1493        for (; ArgIdx < NumArgs; ++ArgIdx) {
1494          if (CheckTemplateTypeArgument(TTP, TemplateArgs[ArgIdx], Converted))
1495            Invalid = true;
1496        }
1497
1498        Converted.EndPack();
1499      } else {
1500        if (CheckTemplateTypeArgument(TTP, Arg, Converted))
1501          Invalid = true;
1502      }
1503    } else if (NonTypeTemplateParmDecl *NTTP
1504                 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
1505      // Check non-type template parameters.
1506
1507      // Do substitution on the type of the non-type template parameter
1508      // with the template arguments we've seen thus far.
1509      QualType NTTPType = NTTP->getType();
1510      if (NTTPType->isDependentType()) {
1511        // Do substitution on the type of the non-type template parameter.
1512        InstantiatingTemplate Inst(*this, TemplateLoc,
1513                                   Template, Converted.getFlatArguments(),
1514                                   Converted.flatSize(),
1515                                   SourceRange(TemplateLoc, RAngleLoc));
1516
1517        TemplateArgumentList TemplateArgs(Context, Converted,
1518                                          /*TakeArgs=*/false);
1519        NTTPType = SubstType(NTTPType,
1520                             MultiLevelTemplateArgumentList(TemplateArgs),
1521                             NTTP->getLocation(),
1522                             NTTP->getDeclName());
1523        // If that worked, check the non-type template parameter type
1524        // for validity.
1525        if (!NTTPType.isNull())
1526          NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
1527                                                       NTTP->getLocation());
1528        if (NTTPType.isNull()) {
1529          Invalid = true;
1530          break;
1531        }
1532      }
1533
1534      switch (Arg.getKind()) {
1535      case TemplateArgument::Null:
1536        assert(false && "Should never see a NULL template argument here");
1537        break;
1538
1539      case TemplateArgument::Expression: {
1540        Expr *E = Arg.getAsExpr();
1541        TemplateArgument Result;
1542        if (CheckTemplateArgument(NTTP, NTTPType, E, Result))
1543          Invalid = true;
1544        else
1545          Converted.Append(Result);
1546        break;
1547      }
1548
1549      case TemplateArgument::Declaration:
1550      case TemplateArgument::Integral:
1551        // We've already checked this template argument, so just copy
1552        // it to the list of converted arguments.
1553        Converted.Append(Arg);
1554        break;
1555
1556      case TemplateArgument::Type:
1557        // We have a non-type template parameter but the template
1558        // argument is a type.
1559
1560        // C++ [temp.arg]p2:
1561        //   In a template-argument, an ambiguity between a type-id and
1562        //   an expression is resolved to a type-id, regardless of the
1563        //   form of the corresponding template-parameter.
1564        //
1565        // We warn specifically about this case, since it can be rather
1566        // confusing for users.
1567        if (Arg.getAsType()->isFunctionType())
1568          Diag(Arg.getLocation(), diag::err_template_arg_nontype_ambig)
1569            << Arg.getAsType();
1570        else
1571          Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr);
1572        Diag((*Param)->getLocation(), diag::note_template_param_here);
1573        Invalid = true;
1574        break;
1575
1576      case TemplateArgument::Pack:
1577        assert(0 && "FIXME: Implement!");
1578        break;
1579      }
1580    } else {
1581      // Check template template parameters.
1582      TemplateTemplateParmDecl *TempParm
1583        = cast<TemplateTemplateParmDecl>(*Param);
1584
1585      switch (Arg.getKind()) {
1586      case TemplateArgument::Null:
1587        assert(false && "Should never see a NULL template argument here");
1588        break;
1589
1590      case TemplateArgument::Expression: {
1591        Expr *ArgExpr = Arg.getAsExpr();
1592        if (ArgExpr && isa<DeclRefExpr>(ArgExpr) &&
1593            isa<TemplateDecl>(cast<DeclRefExpr>(ArgExpr)->getDecl())) {
1594          if (CheckTemplateArgument(TempParm, cast<DeclRefExpr>(ArgExpr)))
1595            Invalid = true;
1596
1597          // Add the converted template argument.
1598          Decl *D
1599            = cast<DeclRefExpr>(ArgExpr)->getDecl()->getCanonicalDecl();
1600          Converted.Append(TemplateArgument(Arg.getLocation(), D));
1601          continue;
1602        }
1603      }
1604        // fall through
1605
1606      case TemplateArgument::Type: {
1607        // We have a template template parameter but the template
1608        // argument does not refer to a template.
1609        Diag(Arg.getLocation(), diag::err_template_arg_must_be_template);
1610        Invalid = true;
1611        break;
1612      }
1613
1614      case TemplateArgument::Declaration:
1615        // We've already checked this template argument, so just copy
1616        // it to the list of converted arguments.
1617        Converted.Append(Arg);
1618        break;
1619
1620      case TemplateArgument::Integral:
1621        assert(false && "Integral argument with template template parameter");
1622        break;
1623
1624      case TemplateArgument::Pack:
1625        assert(0 && "FIXME: Implement!");
1626        break;
1627      }
1628    }
1629  }
1630
1631  return Invalid;
1632}
1633
1634/// \brief Check a template argument against its corresponding
1635/// template type parameter.
1636///
1637/// This routine implements the semantics of C++ [temp.arg.type]. It
1638/// returns true if an error occurred, and false otherwise.
1639bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
1640                                 QualType Arg, SourceLocation ArgLoc) {
1641  // C++ [temp.arg.type]p2:
1642  //   A local type, a type with no linkage, an unnamed type or a type
1643  //   compounded from any of these types shall not be used as a
1644  //   template-argument for a template type-parameter.
1645  //
1646  // FIXME: Perform the recursive and no-linkage type checks.
1647  const TagType *Tag = 0;
1648  if (const EnumType *EnumT = Arg->getAs<EnumType>())
1649    Tag = EnumT;
1650  else if (const RecordType *RecordT = Arg->getAs<RecordType>())
1651    Tag = RecordT;
1652  if (Tag && Tag->getDecl()->getDeclContext()->isFunctionOrMethod())
1653    return Diag(ArgLoc, diag::err_template_arg_local_type)
1654      << QualType(Tag, 0);
1655  else if (Tag && !Tag->getDecl()->getDeclName() &&
1656           !Tag->getDecl()->getTypedefForAnonDecl()) {
1657    Diag(ArgLoc, diag::err_template_arg_unnamed_type);
1658    Diag(Tag->getDecl()->getLocation(), diag::note_template_unnamed_type_here);
1659    return true;
1660  }
1661
1662  return false;
1663}
1664
1665/// \brief Checks whether the given template argument is the address
1666/// of an object or function according to C++ [temp.arg.nontype]p1.
1667bool Sema::CheckTemplateArgumentAddressOfObjectOrFunction(Expr *Arg,
1668                                                          NamedDecl *&Entity) {
1669  bool Invalid = false;
1670
1671  // See through any implicit casts we added to fix the type.
1672  if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
1673    Arg = Cast->getSubExpr();
1674
1675  // C++0x allows nullptr, and there's no further checking to be done for that.
1676  if (Arg->getType()->isNullPtrType())
1677    return false;
1678
1679  // C++ [temp.arg.nontype]p1:
1680  //
1681  //   A template-argument for a non-type, non-template
1682  //   template-parameter shall be one of: [...]
1683  //
1684  //     -- the address of an object or function with external
1685  //        linkage, including function templates and function
1686  //        template-ids but excluding non-static class members,
1687  //        expressed as & id-expression where the & is optional if
1688  //        the name refers to a function or array, or if the
1689  //        corresponding template-parameter is a reference; or
1690  DeclRefExpr *DRE = 0;
1691
1692  // Ignore (and complain about) any excess parentheses.
1693  while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
1694    if (!Invalid) {
1695      Diag(Arg->getSourceRange().getBegin(),
1696           diag::err_template_arg_extra_parens)
1697        << Arg->getSourceRange();
1698      Invalid = true;
1699    }
1700
1701    Arg = Parens->getSubExpr();
1702  }
1703
1704  if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
1705    if (UnOp->getOpcode() == UnaryOperator::AddrOf)
1706      DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
1707  } else
1708    DRE = dyn_cast<DeclRefExpr>(Arg);
1709
1710  if (!DRE || !isa<ValueDecl>(DRE->getDecl()))
1711    return Diag(Arg->getSourceRange().getBegin(),
1712                diag::err_template_arg_not_object_or_func_form)
1713      << Arg->getSourceRange();
1714
1715  // Cannot refer to non-static data members
1716  if (FieldDecl *Field = dyn_cast<FieldDecl>(DRE->getDecl()))
1717    return Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_field)
1718      << Field << Arg->getSourceRange();
1719
1720  // Cannot refer to non-static member functions
1721  if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(DRE->getDecl()))
1722    if (!Method->isStatic())
1723      return Diag(Arg->getSourceRange().getBegin(),
1724                  diag::err_template_arg_method)
1725        << Method << Arg->getSourceRange();
1726
1727  // Functions must have external linkage.
1728  if (FunctionDecl *Func = dyn_cast<FunctionDecl>(DRE->getDecl())) {
1729    if (Func->getStorageClass() == FunctionDecl::Static) {
1730      Diag(Arg->getSourceRange().getBegin(),
1731           diag::err_template_arg_function_not_extern)
1732        << Func << Arg->getSourceRange();
1733      Diag(Func->getLocation(), diag::note_template_arg_internal_object)
1734        << true;
1735      return true;
1736    }
1737
1738    // Okay: we've named a function with external linkage.
1739    Entity = Func;
1740    return Invalid;
1741  }
1742
1743  if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
1744    if (!Var->hasGlobalStorage()) {
1745      Diag(Arg->getSourceRange().getBegin(),
1746           diag::err_template_arg_object_not_extern)
1747        << Var << Arg->getSourceRange();
1748      Diag(Var->getLocation(), diag::note_template_arg_internal_object)
1749        << true;
1750      return true;
1751    }
1752
1753    // Okay: we've named an object with external linkage
1754    Entity = Var;
1755    return Invalid;
1756  }
1757
1758  // We found something else, but we don't know specifically what it is.
1759  Diag(Arg->getSourceRange().getBegin(),
1760       diag::err_template_arg_not_object_or_func)
1761      << Arg->getSourceRange();
1762  Diag(DRE->getDecl()->getLocation(),
1763       diag::note_template_arg_refers_here);
1764  return true;
1765}
1766
1767/// \brief Checks whether the given template argument is a pointer to
1768/// member constant according to C++ [temp.arg.nontype]p1.
1769bool
1770Sema::CheckTemplateArgumentPointerToMember(Expr *Arg, NamedDecl *&Member) {
1771  bool Invalid = false;
1772
1773  // See through any implicit casts we added to fix the type.
1774  if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
1775    Arg = Cast->getSubExpr();
1776
1777  // C++0x allows nullptr, and there's no further checking to be done for that.
1778  if (Arg->getType()->isNullPtrType())
1779    return false;
1780
1781  // C++ [temp.arg.nontype]p1:
1782  //
1783  //   A template-argument for a non-type, non-template
1784  //   template-parameter shall be one of: [...]
1785  //
1786  //     -- a pointer to member expressed as described in 5.3.1.
1787  QualifiedDeclRefExpr *DRE = 0;
1788
1789  // Ignore (and complain about) any excess parentheses.
1790  while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
1791    if (!Invalid) {
1792      Diag(Arg->getSourceRange().getBegin(),
1793           diag::err_template_arg_extra_parens)
1794        << Arg->getSourceRange();
1795      Invalid = true;
1796    }
1797
1798    Arg = Parens->getSubExpr();
1799  }
1800
1801  if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg))
1802    if (UnOp->getOpcode() == UnaryOperator::AddrOf)
1803      DRE = dyn_cast<QualifiedDeclRefExpr>(UnOp->getSubExpr());
1804
1805  if (!DRE)
1806    return Diag(Arg->getSourceRange().getBegin(),
1807                diag::err_template_arg_not_pointer_to_member_form)
1808      << Arg->getSourceRange();
1809
1810  if (isa<FieldDecl>(DRE->getDecl()) || isa<CXXMethodDecl>(DRE->getDecl())) {
1811    assert((isa<FieldDecl>(DRE->getDecl()) ||
1812            !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
1813           "Only non-static member pointers can make it here");
1814
1815    // Okay: this is the address of a non-static member, and therefore
1816    // a member pointer constant.
1817    Member = DRE->getDecl();
1818    return Invalid;
1819  }
1820
1821  // We found something else, but we don't know specifically what it is.
1822  Diag(Arg->getSourceRange().getBegin(),
1823       diag::err_template_arg_not_pointer_to_member_form)
1824      << Arg->getSourceRange();
1825  Diag(DRE->getDecl()->getLocation(),
1826       diag::note_template_arg_refers_here);
1827  return true;
1828}
1829
1830/// \brief Check a template argument against its corresponding
1831/// non-type template parameter.
1832///
1833/// This routine implements the semantics of C++ [temp.arg.nontype].
1834/// It returns true if an error occurred, and false otherwise. \p
1835/// InstantiatedParamType is the type of the non-type template
1836/// parameter after it has been instantiated.
1837///
1838/// If no error was detected, Converted receives the converted template argument.
1839bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
1840                                 QualType InstantiatedParamType, Expr *&Arg,
1841                                 TemplateArgument &Converted) {
1842  SourceLocation StartLoc = Arg->getSourceRange().getBegin();
1843
1844  // If either the parameter has a dependent type or the argument is
1845  // type-dependent, there's nothing we can check now.
1846  // FIXME: Add template argument to Converted!
1847  if (InstantiatedParamType->isDependentType() || Arg->isTypeDependent()) {
1848    // FIXME: Produce a cloned, canonical expression?
1849    Converted = TemplateArgument(Arg);
1850    return false;
1851  }
1852
1853  // C++ [temp.arg.nontype]p5:
1854  //   The following conversions are performed on each expression used
1855  //   as a non-type template-argument. If a non-type
1856  //   template-argument cannot be converted to the type of the
1857  //   corresponding template-parameter then the program is
1858  //   ill-formed.
1859  //
1860  //     -- for a non-type template-parameter of integral or
1861  //        enumeration type, integral promotions (4.5) and integral
1862  //        conversions (4.7) are applied.
1863  QualType ParamType = InstantiatedParamType;
1864  QualType ArgType = Arg->getType();
1865  if (ParamType->isIntegralType() || ParamType->isEnumeralType()) {
1866    // C++ [temp.arg.nontype]p1:
1867    //   A template-argument for a non-type, non-template
1868    //   template-parameter shall be one of:
1869    //
1870    //     -- an integral constant-expression of integral or enumeration
1871    //        type; or
1872    //     -- the name of a non-type template-parameter; or
1873    SourceLocation NonConstantLoc;
1874    llvm::APSInt Value;
1875    if (!ArgType->isIntegralType() && !ArgType->isEnumeralType()) {
1876      Diag(Arg->getSourceRange().getBegin(),
1877           diag::err_template_arg_not_integral_or_enumeral)
1878        << ArgType << Arg->getSourceRange();
1879      Diag(Param->getLocation(), diag::note_template_param_here);
1880      return true;
1881    } else if (!Arg->isValueDependent() &&
1882               !Arg->isIntegerConstantExpr(Value, Context, &NonConstantLoc)) {
1883      Diag(NonConstantLoc, diag::err_template_arg_not_ice)
1884        << ArgType << Arg->getSourceRange();
1885      return true;
1886    }
1887
1888    // FIXME: We need some way to more easily get the unqualified form
1889    // of the types without going all the way to the
1890    // canonical type.
1891    if (Context.getCanonicalType(ParamType).getCVRQualifiers())
1892      ParamType = Context.getCanonicalType(ParamType).getUnqualifiedType();
1893    if (Context.getCanonicalType(ArgType).getCVRQualifiers())
1894      ArgType = Context.getCanonicalType(ArgType).getUnqualifiedType();
1895
1896    // Try to convert the argument to the parameter's type.
1897    if (ParamType == ArgType) {
1898      // Okay: no conversion necessary
1899    } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
1900               !ParamType->isEnumeralType()) {
1901      // This is an integral promotion or conversion.
1902      ImpCastExprToType(Arg, ParamType);
1903    } else {
1904      // We can't perform this conversion.
1905      Diag(Arg->getSourceRange().getBegin(),
1906           diag::err_template_arg_not_convertible)
1907        << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
1908      Diag(Param->getLocation(), diag::note_template_param_here);
1909      return true;
1910    }
1911
1912    QualType IntegerType = Context.getCanonicalType(ParamType);
1913    if (const EnumType *Enum = IntegerType->getAs<EnumType>())
1914      IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
1915
1916    if (!Arg->isValueDependent()) {
1917      // Check that an unsigned parameter does not receive a negative
1918      // value.
1919      if (IntegerType->isUnsignedIntegerType()
1920          && (Value.isSigned() && Value.isNegative())) {
1921        Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_negative)
1922          << Value.toString(10) << Param->getType()
1923          << Arg->getSourceRange();
1924        Diag(Param->getLocation(), diag::note_template_param_here);
1925        return true;
1926      }
1927
1928      // Check that we don't overflow the template parameter type.
1929      unsigned AllowedBits = Context.getTypeSize(IntegerType);
1930      if (Value.getActiveBits() > AllowedBits) {
1931        Diag(Arg->getSourceRange().getBegin(),
1932             diag::err_template_arg_too_large)
1933          << Value.toString(10) << Param->getType()
1934          << Arg->getSourceRange();
1935        Diag(Param->getLocation(), diag::note_template_param_here);
1936        return true;
1937      }
1938
1939      if (Value.getBitWidth() != AllowedBits)
1940        Value.extOrTrunc(AllowedBits);
1941      Value.setIsSigned(IntegerType->isSignedIntegerType());
1942    }
1943
1944    // Add the value of this argument to the list of converted
1945    // arguments. We use the bitwidth and signedness of the template
1946    // parameter.
1947    if (Arg->isValueDependent()) {
1948      // The argument is value-dependent. Create a new
1949      // TemplateArgument with the converted expression.
1950      Converted = TemplateArgument(Arg);
1951      return false;
1952    }
1953
1954    Converted = TemplateArgument(StartLoc, Value,
1955                                 ParamType->isEnumeralType() ? ParamType
1956                                                             : IntegerType);
1957    return false;
1958  }
1959
1960  // Handle pointer-to-function, reference-to-function, and
1961  // pointer-to-member-function all in (roughly) the same way.
1962  if (// -- For a non-type template-parameter of type pointer to
1963      //    function, only the function-to-pointer conversion (4.3) is
1964      //    applied. If the template-argument represents a set of
1965      //    overloaded functions (or a pointer to such), the matching
1966      //    function is selected from the set (13.4).
1967      // In C++0x, any std::nullptr_t value can be converted.
1968      (ParamType->isPointerType() &&
1969       ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
1970      // -- For a non-type template-parameter of type reference to
1971      //    function, no conversions apply. If the template-argument
1972      //    represents a set of overloaded functions, the matching
1973      //    function is selected from the set (13.4).
1974      (ParamType->isReferenceType() &&
1975       ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
1976      // -- For a non-type template-parameter of type pointer to
1977      //    member function, no conversions apply. If the
1978      //    template-argument represents a set of overloaded member
1979      //    functions, the matching member function is selected from
1980      //    the set (13.4).
1981      // Again, C++0x allows a std::nullptr_t value.
1982      (ParamType->isMemberPointerType() &&
1983       ParamType->getAs<MemberPointerType>()->getPointeeType()
1984         ->isFunctionType())) {
1985    if (Context.hasSameUnqualifiedType(ArgType,
1986                                       ParamType.getNonReferenceType())) {
1987      // We don't have to do anything: the types already match.
1988    } else if (ArgType->isNullPtrType() && (ParamType->isPointerType() ||
1989                 ParamType->isMemberPointerType())) {
1990      ArgType = ParamType;
1991      ImpCastExprToType(Arg, ParamType);
1992    } else if (ArgType->isFunctionType() && ParamType->isPointerType()) {
1993      ArgType = Context.getPointerType(ArgType);
1994      ImpCastExprToType(Arg, ArgType);
1995    } else if (FunctionDecl *Fn
1996                 = ResolveAddressOfOverloadedFunction(Arg, ParamType, true)) {
1997      if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
1998        return true;
1999
2000      FixOverloadedFunctionReference(Arg, Fn);
2001      ArgType = Arg->getType();
2002      if (ArgType->isFunctionType() && ParamType->isPointerType()) {
2003        ArgType = Context.getPointerType(Arg->getType());
2004        ImpCastExprToType(Arg, ArgType);
2005      }
2006    }
2007
2008    if (!Context.hasSameUnqualifiedType(ArgType,
2009                                        ParamType.getNonReferenceType())) {
2010      // We can't perform this conversion.
2011      Diag(Arg->getSourceRange().getBegin(),
2012           diag::err_template_arg_not_convertible)
2013        << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
2014      Diag(Param->getLocation(), diag::note_template_param_here);
2015      return true;
2016    }
2017
2018    if (ParamType->isMemberPointerType()) {
2019      NamedDecl *Member = 0;
2020      if (CheckTemplateArgumentPointerToMember(Arg, Member))
2021        return true;
2022
2023      if (Member)
2024        Member = cast<NamedDecl>(Member->getCanonicalDecl());
2025      Converted = TemplateArgument(StartLoc, Member);
2026      return false;
2027    }
2028
2029    NamedDecl *Entity = 0;
2030    if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
2031      return true;
2032
2033    if (Entity)
2034      Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
2035    Converted = TemplateArgument(StartLoc, Entity);
2036    return false;
2037  }
2038
2039  if (ParamType->isPointerType()) {
2040    //   -- for a non-type template-parameter of type pointer to
2041    //      object, qualification conversions (4.4) and the
2042    //      array-to-pointer conversion (4.2) are applied.
2043    // C++0x also allows a value of std::nullptr_t.
2044    assert(ParamType->getAs<PointerType>()->getPointeeType()->isObjectType() &&
2045           "Only object pointers allowed here");
2046
2047    if (ArgType->isNullPtrType()) {
2048      ArgType = ParamType;
2049      ImpCastExprToType(Arg, ParamType);
2050    } else if (ArgType->isArrayType()) {
2051      ArgType = Context.getArrayDecayedType(ArgType);
2052      ImpCastExprToType(Arg, ArgType);
2053    }
2054
2055    if (IsQualificationConversion(ArgType, ParamType)) {
2056      ArgType = ParamType;
2057      ImpCastExprToType(Arg, ParamType);
2058    }
2059
2060    if (!Context.hasSameUnqualifiedType(ArgType, ParamType)) {
2061      // We can't perform this conversion.
2062      Diag(Arg->getSourceRange().getBegin(),
2063           diag::err_template_arg_not_convertible)
2064        << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
2065      Diag(Param->getLocation(), diag::note_template_param_here);
2066      return true;
2067    }
2068
2069    NamedDecl *Entity = 0;
2070    if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
2071      return true;
2072
2073    if (Entity)
2074      Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
2075    Converted = TemplateArgument(StartLoc, Entity);
2076    return false;
2077  }
2078
2079  if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
2080    //   -- For a non-type template-parameter of type reference to
2081    //      object, no conversions apply. The type referred to by the
2082    //      reference may be more cv-qualified than the (otherwise
2083    //      identical) type of the template-argument. The
2084    //      template-parameter is bound directly to the
2085    //      template-argument, which must be an lvalue.
2086    assert(ParamRefType->getPointeeType()->isObjectType() &&
2087           "Only object references allowed here");
2088
2089    if (!Context.hasSameUnqualifiedType(ParamRefType->getPointeeType(), ArgType)) {
2090      Diag(Arg->getSourceRange().getBegin(),
2091           diag::err_template_arg_no_ref_bind)
2092        << InstantiatedParamType << Arg->getType()
2093        << Arg->getSourceRange();
2094      Diag(Param->getLocation(), diag::note_template_param_here);
2095      return true;
2096    }
2097
2098    unsigned ParamQuals
2099      = Context.getCanonicalType(ParamType).getCVRQualifiers();
2100    unsigned ArgQuals = Context.getCanonicalType(ArgType).getCVRQualifiers();
2101
2102    if ((ParamQuals | ArgQuals) != ParamQuals) {
2103      Diag(Arg->getSourceRange().getBegin(),
2104           diag::err_template_arg_ref_bind_ignores_quals)
2105        << InstantiatedParamType << Arg->getType()
2106        << Arg->getSourceRange();
2107      Diag(Param->getLocation(), diag::note_template_param_here);
2108      return true;
2109    }
2110
2111    NamedDecl *Entity = 0;
2112    if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
2113      return true;
2114
2115    Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
2116    Converted = TemplateArgument(StartLoc, Entity);
2117    return false;
2118  }
2119
2120  //     -- For a non-type template-parameter of type pointer to data
2121  //        member, qualification conversions (4.4) are applied.
2122  // C++0x allows std::nullptr_t values.
2123  assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
2124
2125  if (Context.hasSameUnqualifiedType(ParamType, ArgType)) {
2126    // Types match exactly: nothing more to do here.
2127  } else if (ArgType->isNullPtrType()) {
2128    ImpCastExprToType(Arg, ParamType);
2129  } else if (IsQualificationConversion(ArgType, ParamType)) {
2130    ImpCastExprToType(Arg, ParamType);
2131  } else {
2132    // We can't perform this conversion.
2133    Diag(Arg->getSourceRange().getBegin(),
2134         diag::err_template_arg_not_convertible)
2135      << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
2136    Diag(Param->getLocation(), diag::note_template_param_here);
2137    return true;
2138  }
2139
2140  NamedDecl *Member = 0;
2141  if (CheckTemplateArgumentPointerToMember(Arg, Member))
2142    return true;
2143
2144  if (Member)
2145    Member = cast<NamedDecl>(Member->getCanonicalDecl());
2146  Converted = TemplateArgument(StartLoc, Member);
2147  return false;
2148}
2149
2150/// \brief Check a template argument against its corresponding
2151/// template template parameter.
2152///
2153/// This routine implements the semantics of C++ [temp.arg.template].
2154/// It returns true if an error occurred, and false otherwise.
2155bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
2156                                 DeclRefExpr *Arg) {
2157  assert(isa<TemplateDecl>(Arg->getDecl()) && "Only template decls allowed");
2158  TemplateDecl *Template = cast<TemplateDecl>(Arg->getDecl());
2159
2160  // C++ [temp.arg.template]p1:
2161  //   A template-argument for a template template-parameter shall be
2162  //   the name of a class template, expressed as id-expression. Only
2163  //   primary class templates are considered when matching the
2164  //   template template argument with the corresponding parameter;
2165  //   partial specializations are not considered even if their
2166  //   parameter lists match that of the template template parameter.
2167  //
2168  // Note that we also allow template template parameters here, which
2169  // will happen when we are dealing with, e.g., class template
2170  // partial specializations.
2171  if (!isa<ClassTemplateDecl>(Template) &&
2172      !isa<TemplateTemplateParmDecl>(Template)) {
2173    assert(isa<FunctionTemplateDecl>(Template) &&
2174           "Only function templates are possible here");
2175    Diag(Arg->getLocStart(), diag::err_template_arg_not_class_template);
2176    Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
2177      << Template;
2178  }
2179
2180  return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
2181                                         Param->getTemplateParameters(),
2182                                         true, true,
2183                                         Arg->getSourceRange().getBegin());
2184}
2185
2186/// \brief Determine whether the given template parameter lists are
2187/// equivalent.
2188///
2189/// \param New  The new template parameter list, typically written in the
2190/// source code as part of a new template declaration.
2191///
2192/// \param Old  The old template parameter list, typically found via
2193/// name lookup of the template declared with this template parameter
2194/// list.
2195///
2196/// \param Complain  If true, this routine will produce a diagnostic if
2197/// the template parameter lists are not equivalent.
2198///
2199/// \param IsTemplateTemplateParm  If true, this routine is being
2200/// called to compare the template parameter lists of a template
2201/// template parameter.
2202///
2203/// \param TemplateArgLoc If this source location is valid, then we
2204/// are actually checking the template parameter list of a template
2205/// argument (New) against the template parameter list of its
2206/// corresponding template template parameter (Old). We produce
2207/// slightly different diagnostics in this scenario.
2208///
2209/// \returns True if the template parameter lists are equal, false
2210/// otherwise.
2211bool
2212Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
2213                                     TemplateParameterList *Old,
2214                                     bool Complain,
2215                                     bool IsTemplateTemplateParm,
2216                                     SourceLocation TemplateArgLoc) {
2217  if (Old->size() != New->size()) {
2218    if (Complain) {
2219      unsigned NextDiag = diag::err_template_param_list_different_arity;
2220      if (TemplateArgLoc.isValid()) {
2221        Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
2222        NextDiag = diag::note_template_param_list_different_arity;
2223      }
2224      Diag(New->getTemplateLoc(), NextDiag)
2225          << (New->size() > Old->size())
2226          << IsTemplateTemplateParm
2227          << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
2228      Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
2229        << IsTemplateTemplateParm
2230        << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
2231    }
2232
2233    return false;
2234  }
2235
2236  for (TemplateParameterList::iterator OldParm = Old->begin(),
2237         OldParmEnd = Old->end(), NewParm = New->begin();
2238       OldParm != OldParmEnd; ++OldParm, ++NewParm) {
2239    if ((*OldParm)->getKind() != (*NewParm)->getKind()) {
2240      if (Complain) {
2241        unsigned NextDiag = diag::err_template_param_different_kind;
2242        if (TemplateArgLoc.isValid()) {
2243          Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
2244          NextDiag = diag::note_template_param_different_kind;
2245        }
2246        Diag((*NewParm)->getLocation(), NextDiag)
2247        << IsTemplateTemplateParm;
2248        Diag((*OldParm)->getLocation(), diag::note_template_prev_declaration)
2249        << IsTemplateTemplateParm;
2250      }
2251      return false;
2252    }
2253
2254    if (isa<TemplateTypeParmDecl>(*OldParm)) {
2255      // Okay; all template type parameters are equivalent (since we
2256      // know we're at the same index).
2257#if 0
2258      // FIXME: Enable this code in debug mode *after* we properly go through
2259      // and "instantiate" the template parameter lists of template template
2260      // parameters. It's only after this instantiation that (1) any dependent
2261      // types within the template parameter list of the template template
2262      // parameter can be checked, and (2) the template type parameter depths
2263      // will match up.
2264      QualType OldParmType
2265        = Context.getTypeDeclType(cast<TemplateTypeParmDecl>(*OldParm));
2266      QualType NewParmType
2267        = Context.getTypeDeclType(cast<TemplateTypeParmDecl>(*NewParm));
2268      assert(Context.getCanonicalType(OldParmType) ==
2269             Context.getCanonicalType(NewParmType) &&
2270             "type parameter mismatch?");
2271#endif
2272    } else if (NonTypeTemplateParmDecl *OldNTTP
2273                 = dyn_cast<NonTypeTemplateParmDecl>(*OldParm)) {
2274      // The types of non-type template parameters must agree.
2275      NonTypeTemplateParmDecl *NewNTTP
2276        = cast<NonTypeTemplateParmDecl>(*NewParm);
2277      if (Context.getCanonicalType(OldNTTP->getType()) !=
2278            Context.getCanonicalType(NewNTTP->getType())) {
2279        if (Complain) {
2280          unsigned NextDiag = diag::err_template_nontype_parm_different_type;
2281          if (TemplateArgLoc.isValid()) {
2282            Diag(TemplateArgLoc,
2283                 diag::err_template_arg_template_params_mismatch);
2284            NextDiag = diag::note_template_nontype_parm_different_type;
2285          }
2286          Diag(NewNTTP->getLocation(), NextDiag)
2287            << NewNTTP->getType()
2288            << IsTemplateTemplateParm;
2289          Diag(OldNTTP->getLocation(),
2290               diag::note_template_nontype_parm_prev_declaration)
2291            << OldNTTP->getType();
2292        }
2293        return false;
2294      }
2295    } else {
2296      // The template parameter lists of template template
2297      // parameters must agree.
2298      // FIXME: Could we perform a faster "type" comparison here?
2299      assert(isa<TemplateTemplateParmDecl>(*OldParm) &&
2300             "Only template template parameters handled here");
2301      TemplateTemplateParmDecl *OldTTP
2302        = cast<TemplateTemplateParmDecl>(*OldParm);
2303      TemplateTemplateParmDecl *NewTTP
2304        = cast<TemplateTemplateParmDecl>(*NewParm);
2305      if (!TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
2306                                          OldTTP->getTemplateParameters(),
2307                                          Complain,
2308                                          /*IsTemplateTemplateParm=*/true,
2309                                          TemplateArgLoc))
2310        return false;
2311    }
2312  }
2313
2314  return true;
2315}
2316
2317/// \brief Check whether a template can be declared within this scope.
2318///
2319/// If the template declaration is valid in this scope, returns
2320/// false. Otherwise, issues a diagnostic and returns true.
2321bool
2322Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
2323  // Find the nearest enclosing declaration scope.
2324  while ((S->getFlags() & Scope::DeclScope) == 0 ||
2325         (S->getFlags() & Scope::TemplateParamScope) != 0)
2326    S = S->getParent();
2327
2328  // C++ [temp]p2:
2329  //   A template-declaration can appear only as a namespace scope or
2330  //   class scope declaration.
2331  DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
2332  if (Ctx && isa<LinkageSpecDecl>(Ctx) &&
2333      cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx)
2334    return Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
2335             << TemplateParams->getSourceRange();
2336
2337  while (Ctx && isa<LinkageSpecDecl>(Ctx))
2338    Ctx = Ctx->getParent();
2339
2340  if (Ctx && (Ctx->isFileContext() || Ctx->isRecord()))
2341    return false;
2342
2343  return Diag(TemplateParams->getTemplateLoc(),
2344              diag::err_template_outside_namespace_or_class_scope)
2345    << TemplateParams->getSourceRange();
2346}
2347
2348/// \brief Determine what kind of template specialization the given declaration
2349/// is.
2350static TemplateSpecializationKind getTemplateSpecializationKind(NamedDecl *D) {
2351  if (!D)
2352    return TSK_Undeclared;
2353
2354  if (ClassTemplateSpecializationDecl *CTS
2355        = dyn_cast<ClassTemplateSpecializationDecl>(D))
2356    return CTS->getSpecializationKind();
2357  if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
2358    return Function->getTemplateSpecializationKind();
2359
2360  // FIXME: static data members!
2361  // FIXME: member classes of class templates!
2362  return TSK_Undeclared;
2363}
2364
2365/// \brief Check whether a specialization or explicit instantiation is
2366/// well-formed in the current context.
2367///
2368/// This routine determines whether a template specialization or
2369/// explicit instantiation can be declared in the current context
2370/// (C++ [temp.expl.spec]p2, C++0x [temp.explicit]p2).
2371///
2372/// \param S the semantic analysis object for which this check is being
2373/// performed.
2374///
2375/// \param Specialized the entity being specialized or instantiated, which
2376/// may be a kind of template (class template, function template, etc.) or
2377/// a member of a class template (member function, static data member,
2378/// member class).
2379///
2380/// \param PrevDecl the previous declaration of this entity, if any.
2381///
2382/// \param Loc the location of the explicit specialization or instantiation of
2383/// this entity.
2384///
2385/// \param IsPartialSpecialization whether this is a partial specialization of
2386/// a class template.
2387///
2388/// \param TSK the kind of specialization or implicit instantiation being
2389/// performed.
2390///
2391/// \returns true if there was an error that we cannot recover from, false
2392/// otherwise.
2393static bool CheckTemplateSpecializationScope(Sema &S,
2394                                             NamedDecl *Specialized,
2395                                             NamedDecl *PrevDecl,
2396                                             SourceLocation Loc,
2397                                             bool IsPartialSpecialization,
2398                                             TemplateSpecializationKind TSK) {
2399  // Keep these "kind" numbers in sync with the %select statements in the
2400  // various diagnostics emitted by this routine.
2401  int EntityKind = 0;
2402  if (isa<ClassTemplateDecl>(Specialized))
2403    EntityKind = IsPartialSpecialization? 1 : 0;
2404  else if (isa<FunctionTemplateDecl>(Specialized))
2405    EntityKind = 2;
2406  else if (isa<CXXMethodDecl>(Specialized))
2407    EntityKind = 3;
2408  else if (isa<VarDecl>(Specialized))
2409    EntityKind = 4;
2410  else if (isa<RecordDecl>(Specialized))
2411    EntityKind = 5;
2412  else {
2413    S.Diag(Loc, diag::err_template_spec_unknown_kind) << TSK;
2414    S.Diag(Specialized->getLocation(), diag::note_specialized_entity) << TSK;
2415    return true;
2416  }
2417
2418  // C++ [temp.expl.spec]p2:
2419  //   An explicit specialization shall be declared in the namespace
2420  //   of which the template is a member, or, for member templates, in
2421  //   the namespace of which the enclosing class or enclosing class
2422  //   template is a member. An explicit specialization of a member
2423  //   function, member class or static data member of a class
2424  //   template shall be declared in the namespace of which the class
2425  //   template is a member. Such a declaration may also be a
2426  //   definition. If the declaration is not a definition, the
2427  //   specialization may be defined later in the name- space in which
2428  //   the explicit specialization was declared, or in a namespace
2429  //   that encloses the one in which the explicit specialization was
2430  //   declared.
2431  if (S.CurContext->getLookupContext()->isFunctionOrMethod()) {
2432    S.Diag(Loc, diag::err_template_spec_decl_function_scope)
2433      << TSK << Specialized;
2434    return true;
2435  }
2436
2437  if (S.CurContext->isRecord() && !IsPartialSpecialization) {
2438    S.Diag(Loc, diag::err_template_spec_decl_class_scope)
2439      << TSK << Specialized;
2440    return true;
2441  }
2442
2443  // C++ [temp.class.spec]p6:
2444  //   A class template partial specialization may be declared or redeclared
2445  //   in any namespace scope in which its definition may be defined (14.5.1
2446  //   and 14.5.2).
2447  bool ComplainedAboutScope = false;
2448  DeclContext *SpecializedContext
2449    = Specialized->getDeclContext()->getEnclosingNamespaceContext();
2450  DeclContext *DC = S.CurContext->getEnclosingNamespaceContext();
2451  if (TSK == TSK_ExplicitSpecialization) {
2452    if ((!PrevDecl ||
2453         getTemplateSpecializationKind(PrevDecl) == TSK_Undeclared ||
2454         getTemplateSpecializationKind(PrevDecl) == TSK_ImplicitInstantiation)){
2455      // There is no prior declaration of this entity, so this
2456      // specialization must be in the same context as the template
2457      // itself.
2458      if (!DC->Equals(SpecializedContext)) {
2459        if (isa<TranslationUnitDecl>(SpecializedContext))
2460          S.Diag(Loc, diag::err_template_spec_decl_out_of_scope_global)
2461          << EntityKind << Specialized;
2462        else if (isa<NamespaceDecl>(SpecializedContext))
2463          S.Diag(Loc, diag::err_template_spec_decl_out_of_scope)
2464          << EntityKind << Specialized
2465          << cast<NamedDecl>(SpecializedContext);
2466
2467        S.Diag(Specialized->getLocation(), diag::note_template_decl_here);
2468        ComplainedAboutScope = true;
2469      }
2470    }
2471  }
2472
2473  // Make sure that this redeclaration (or definition) occurs in an enclosing
2474  // namespace. We perform this check for explicit specializations and, in
2475  // C++0x, for explicit instantiations as well (per DR275).
2476  // FIXME: -Wc++0x should make these warnings.
2477  // Note that HandleDeclarator() performs this check for explicit
2478  // specializations of function templates, static data members, and member
2479  // functions, so we skip the check here for those kinds of entities.
2480  // FIXME: HandleDeclarator's diagnostics aren't quite as good, though.
2481  // Should we refactor that check, so that it occurs later?
2482  if (!ComplainedAboutScope && !DC->Encloses(SpecializedContext) &&
2483      ((TSK == TSK_ExplicitSpecialization &&
2484        !(isa<FunctionTemplateDecl>(Specialized) || isa<VarDecl>(Specialized) ||
2485          isa<FunctionDecl>(Specialized))) ||
2486        S.getLangOptions().CPlusPlus0x)) {
2487    if (isa<TranslationUnitDecl>(SpecializedContext))
2488      S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
2489        << EntityKind << Specialized;
2490    else if (isa<NamespaceDecl>(SpecializedContext))
2491      S.Diag(Loc, diag::err_template_spec_redecl_out_of_scope)
2492        << EntityKind << Specialized
2493        << cast<NamedDecl>(SpecializedContext);
2494
2495    S.Diag(Specialized->getLocation(), diag::note_template_decl_here);
2496  }
2497
2498  // FIXME: check for specialization-after-instantiation errors and such.
2499
2500  return false;
2501}
2502
2503/// \brief Check the non-type template arguments of a class template
2504/// partial specialization according to C++ [temp.class.spec]p9.
2505///
2506/// \param TemplateParams the template parameters of the primary class
2507/// template.
2508///
2509/// \param TemplateArg the template arguments of the class template
2510/// partial specialization.
2511///
2512/// \param MirrorsPrimaryTemplate will be set true if the class
2513/// template partial specialization arguments are identical to the
2514/// implicit template arguments of the primary template. This is not
2515/// necessarily an error (C++0x), and it is left to the caller to diagnose
2516/// this condition when it is an error.
2517///
2518/// \returns true if there was an error, false otherwise.
2519bool Sema::CheckClassTemplatePartialSpecializationArgs(
2520                                        TemplateParameterList *TemplateParams,
2521                             const TemplateArgumentListBuilder &TemplateArgs,
2522                                        bool &MirrorsPrimaryTemplate) {
2523  // FIXME: the interface to this function will have to change to
2524  // accommodate variadic templates.
2525  MirrorsPrimaryTemplate = true;
2526
2527  const TemplateArgument *ArgList = TemplateArgs.getFlatArguments();
2528
2529  for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
2530    // Determine whether the template argument list of the partial
2531    // specialization is identical to the implicit argument list of
2532    // the primary template. The caller may need to diagnostic this as
2533    // an error per C++ [temp.class.spec]p9b3.
2534    if (MirrorsPrimaryTemplate) {
2535      if (TemplateTypeParmDecl *TTP
2536            = dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(I))) {
2537        if (Context.getCanonicalType(Context.getTypeDeclType(TTP)) !=
2538              Context.getCanonicalType(ArgList[I].getAsType()))
2539          MirrorsPrimaryTemplate = false;
2540      } else if (TemplateTemplateParmDecl *TTP
2541                   = dyn_cast<TemplateTemplateParmDecl>(
2542                                                 TemplateParams->getParam(I))) {
2543        // FIXME: We should settle on either Declaration storage or
2544        // Expression storage for template template parameters.
2545        TemplateTemplateParmDecl *ArgDecl
2546          = dyn_cast_or_null<TemplateTemplateParmDecl>(
2547                                                  ArgList[I].getAsDecl());
2548        if (!ArgDecl)
2549          if (DeclRefExpr *DRE
2550                = dyn_cast_or_null<DeclRefExpr>(ArgList[I].getAsExpr()))
2551            ArgDecl = dyn_cast<TemplateTemplateParmDecl>(DRE->getDecl());
2552
2553        if (!ArgDecl ||
2554            ArgDecl->getIndex() != TTP->getIndex() ||
2555            ArgDecl->getDepth() != TTP->getDepth())
2556          MirrorsPrimaryTemplate = false;
2557      }
2558    }
2559
2560    NonTypeTemplateParmDecl *Param
2561      = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
2562    if (!Param) {
2563      continue;
2564    }
2565
2566    Expr *ArgExpr = ArgList[I].getAsExpr();
2567    if (!ArgExpr) {
2568      MirrorsPrimaryTemplate = false;
2569      continue;
2570    }
2571
2572    // C++ [temp.class.spec]p8:
2573    //   A non-type argument is non-specialized if it is the name of a
2574    //   non-type parameter. All other non-type arguments are
2575    //   specialized.
2576    //
2577    // Below, we check the two conditions that only apply to
2578    // specialized non-type arguments, so skip any non-specialized
2579    // arguments.
2580    if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
2581      if (NonTypeTemplateParmDecl *NTTP
2582            = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl())) {
2583        if (MirrorsPrimaryTemplate &&
2584            (Param->getIndex() != NTTP->getIndex() ||
2585             Param->getDepth() != NTTP->getDepth()))
2586          MirrorsPrimaryTemplate = false;
2587
2588        continue;
2589      }
2590
2591    // C++ [temp.class.spec]p9:
2592    //   Within the argument list of a class template partial
2593    //   specialization, the following restrictions apply:
2594    //     -- A partially specialized non-type argument expression
2595    //        shall not involve a template parameter of the partial
2596    //        specialization except when the argument expression is a
2597    //        simple identifier.
2598    if (ArgExpr->isTypeDependent() || ArgExpr->isValueDependent()) {
2599      Diag(ArgExpr->getLocStart(),
2600           diag::err_dependent_non_type_arg_in_partial_spec)
2601        << ArgExpr->getSourceRange();
2602      return true;
2603    }
2604
2605    //     -- The type of a template parameter corresponding to a
2606    //        specialized non-type argument shall not be dependent on a
2607    //        parameter of the specialization.
2608    if (Param->getType()->isDependentType()) {
2609      Diag(ArgExpr->getLocStart(),
2610           diag::err_dependent_typed_non_type_arg_in_partial_spec)
2611        << Param->getType()
2612        << ArgExpr->getSourceRange();
2613      Diag(Param->getLocation(), diag::note_template_param_here);
2614      return true;
2615    }
2616
2617    MirrorsPrimaryTemplate = false;
2618  }
2619
2620  return false;
2621}
2622
2623Sema::DeclResult
2624Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec,
2625                                       TagUseKind TUK,
2626                                       SourceLocation KWLoc,
2627                                       const CXXScopeSpec &SS,
2628                                       TemplateTy TemplateD,
2629                                       SourceLocation TemplateNameLoc,
2630                                       SourceLocation LAngleLoc,
2631                                       ASTTemplateArgsPtr TemplateArgsIn,
2632                                       SourceLocation *TemplateArgLocs,
2633                                       SourceLocation RAngleLoc,
2634                                       AttributeList *Attr,
2635                               MultiTemplateParamsArg TemplateParameterLists) {
2636  assert(TUK != TUK_Reference && "References are not specializations");
2637
2638  // Find the class template we're specializing
2639  TemplateName Name = TemplateD.getAsVal<TemplateName>();
2640  ClassTemplateDecl *ClassTemplate
2641    = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
2642
2643  bool isPartialSpecialization = false;
2644
2645  // Check the validity of the template headers that introduce this
2646  // template.
2647  // FIXME: We probably shouldn't complain about these headers for
2648  // friend declarations.
2649  TemplateParameterList *TemplateParams
2650    = MatchTemplateParametersToScopeSpecifier(TemplateNameLoc, SS,
2651                        (TemplateParameterList**)TemplateParameterLists.get(),
2652                                              TemplateParameterLists.size());
2653  if (TemplateParams && TemplateParams->size() > 0) {
2654    isPartialSpecialization = true;
2655
2656    // C++ [temp.class.spec]p10:
2657    //   The template parameter list of a specialization shall not
2658    //   contain default template argument values.
2659    for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
2660      Decl *Param = TemplateParams->getParam(I);
2661      if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
2662        if (TTP->hasDefaultArgument()) {
2663          Diag(TTP->getDefaultArgumentLoc(),
2664               diag::err_default_arg_in_partial_spec);
2665          TTP->setDefaultArgument(QualType(), SourceLocation(), false);
2666        }
2667      } else if (NonTypeTemplateParmDecl *NTTP
2668                   = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
2669        if (Expr *DefArg = NTTP->getDefaultArgument()) {
2670          Diag(NTTP->getDefaultArgumentLoc(),
2671               diag::err_default_arg_in_partial_spec)
2672            << DefArg->getSourceRange();
2673          NTTP->setDefaultArgument(0);
2674          DefArg->Destroy(Context);
2675        }
2676      } else {
2677        TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
2678        if (Expr *DefArg = TTP->getDefaultArgument()) {
2679          Diag(TTP->getDefaultArgumentLoc(),
2680               diag::err_default_arg_in_partial_spec)
2681            << DefArg->getSourceRange();
2682          TTP->setDefaultArgument(0);
2683          DefArg->Destroy(Context);
2684        }
2685      }
2686    }
2687  } else if (!TemplateParams && TUK != TUK_Friend)
2688    Diag(KWLoc, diag::err_template_spec_needs_header)
2689      << CodeModificationHint::CreateInsertion(KWLoc, "template<> ");
2690
2691  // Check that the specialization uses the same tag kind as the
2692  // original template.
2693  TagDecl::TagKind Kind;
2694  switch (TagSpec) {
2695  default: assert(0 && "Unknown tag type!");
2696  case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
2697  case DeclSpec::TST_union:  Kind = TagDecl::TK_union; break;
2698  case DeclSpec::TST_class:  Kind = TagDecl::TK_class; break;
2699  }
2700  if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
2701                                    Kind, KWLoc,
2702                                    *ClassTemplate->getIdentifier())) {
2703    Diag(KWLoc, diag::err_use_with_wrong_tag)
2704      << ClassTemplate
2705      << CodeModificationHint::CreateReplacement(KWLoc,
2706                            ClassTemplate->getTemplatedDecl()->getKindName());
2707    Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
2708         diag::note_previous_use);
2709    Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
2710  }
2711
2712  // Translate the parser's template argument list in our AST format.
2713  llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
2714  translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
2715
2716  // Check that the template argument list is well-formed for this
2717  // template.
2718  TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
2719                                        TemplateArgs.size());
2720  if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, LAngleLoc,
2721                                TemplateArgs.data(), TemplateArgs.size(),
2722                                RAngleLoc, false, Converted))
2723    return true;
2724
2725  assert((Converted.structuredSize() ==
2726            ClassTemplate->getTemplateParameters()->size()) &&
2727         "Converted template argument list is too short!");
2728
2729  // Find the class template (partial) specialization declaration that
2730  // corresponds to these arguments.
2731  llvm::FoldingSetNodeID ID;
2732  if (isPartialSpecialization) {
2733    bool MirrorsPrimaryTemplate;
2734    if (CheckClassTemplatePartialSpecializationArgs(
2735                                         ClassTemplate->getTemplateParameters(),
2736                                         Converted, MirrorsPrimaryTemplate))
2737      return true;
2738
2739    if (MirrorsPrimaryTemplate) {
2740      // C++ [temp.class.spec]p9b3:
2741      //
2742      //   -- The argument list of the specialization shall not be identical
2743      //      to the implicit argument list of the primary template.
2744      Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
2745        << (TUK == TUK_Definition)
2746        << CodeModificationHint::CreateRemoval(SourceRange(LAngleLoc,
2747                                                           RAngleLoc));
2748      return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
2749                                ClassTemplate->getIdentifier(),
2750                                TemplateNameLoc,
2751                                Attr,
2752                                TemplateParams,
2753                                AS_none);
2754    }
2755
2756    // FIXME: Diagnose friend partial specializations
2757
2758    // FIXME: Template parameter list matters, too
2759    ClassTemplatePartialSpecializationDecl::Profile(ID,
2760                                                   Converted.getFlatArguments(),
2761                                                   Converted.flatSize(),
2762                                                    Context);
2763  } else
2764    ClassTemplateSpecializationDecl::Profile(ID,
2765                                             Converted.getFlatArguments(),
2766                                             Converted.flatSize(),
2767                                             Context);
2768  void *InsertPos = 0;
2769  ClassTemplateSpecializationDecl *PrevDecl = 0;
2770
2771  if (isPartialSpecialization)
2772    PrevDecl
2773      = ClassTemplate->getPartialSpecializations().FindNodeOrInsertPos(ID,
2774                                                                    InsertPos);
2775  else
2776    PrevDecl
2777      = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
2778
2779  ClassTemplateSpecializationDecl *Specialization = 0;
2780
2781  // Check whether we can declare a class template specialization in
2782  // the current scope.
2783  if (TUK != TUK_Friend &&
2784      CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
2785                                       TemplateNameLoc, isPartialSpecialization,
2786                                       TSK_ExplicitSpecialization))
2787    return true;
2788
2789  // The canonical type
2790  QualType CanonType;
2791  if (PrevDecl &&
2792      (PrevDecl->getSpecializationKind() == TSK_Undeclared ||
2793       TUK == TUK_Friend)) {
2794    // Since the only prior class template specialization with these
2795    // arguments was referenced but not declared, or we're only
2796    // referencing this specialization as a friend, reuse that
2797    // declaration node as our own, updating its source location to
2798    // reflect our new declaration.
2799    Specialization = PrevDecl;
2800    Specialization->setLocation(TemplateNameLoc);
2801    PrevDecl = 0;
2802    CanonType = Context.getTypeDeclType(Specialization);
2803  } else if (isPartialSpecialization) {
2804    // Build the canonical type that describes the converted template
2805    // arguments of the class template partial specialization.
2806    CanonType = Context.getTemplateSpecializationType(
2807                                                  TemplateName(ClassTemplate),
2808                                                  Converted.getFlatArguments(),
2809                                                  Converted.flatSize());
2810
2811    // Create a new class template partial specialization declaration node.
2812    TemplateParameterList *TemplateParams
2813      = static_cast<TemplateParameterList*>(*TemplateParameterLists.get());
2814    ClassTemplatePartialSpecializationDecl *PrevPartial
2815      = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
2816    ClassTemplatePartialSpecializationDecl *Partial
2817      = ClassTemplatePartialSpecializationDecl::Create(Context,
2818                                             ClassTemplate->getDeclContext(),
2819                                                       TemplateNameLoc,
2820                                                       TemplateParams,
2821                                                       ClassTemplate,
2822                                                       Converted,
2823                                                       PrevPartial);
2824
2825    if (PrevPartial) {
2826      ClassTemplate->getPartialSpecializations().RemoveNode(PrevPartial);
2827      ClassTemplate->getPartialSpecializations().GetOrInsertNode(Partial);
2828    } else {
2829      ClassTemplate->getPartialSpecializations().InsertNode(Partial, InsertPos);
2830    }
2831    Specialization = Partial;
2832
2833    // Check that all of the template parameters of the class template
2834    // partial specialization are deducible from the template
2835    // arguments. If not, this class template partial specialization
2836    // will never be used.
2837    llvm::SmallVector<bool, 8> DeducibleParams;
2838    DeducibleParams.resize(TemplateParams->size());
2839    MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
2840                               DeducibleParams);
2841    unsigned NumNonDeducible = 0;
2842    for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I)
2843      if (!DeducibleParams[I])
2844        ++NumNonDeducible;
2845
2846    if (NumNonDeducible) {
2847      Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
2848        << (NumNonDeducible > 1)
2849        << SourceRange(TemplateNameLoc, RAngleLoc);
2850      for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
2851        if (!DeducibleParams[I]) {
2852          NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
2853          if (Param->getDeclName())
2854            Diag(Param->getLocation(),
2855                 diag::note_partial_spec_unused_parameter)
2856              << Param->getDeclName();
2857          else
2858            Diag(Param->getLocation(),
2859                 diag::note_partial_spec_unused_parameter)
2860              << std::string("<anonymous>");
2861        }
2862      }
2863    }
2864  } else {
2865    // Create a new class template specialization declaration node for
2866    // this explicit specialization or friend declaration.
2867    Specialization
2868      = ClassTemplateSpecializationDecl::Create(Context,
2869                                             ClassTemplate->getDeclContext(),
2870                                                TemplateNameLoc,
2871                                                ClassTemplate,
2872                                                Converted,
2873                                                PrevDecl);
2874
2875    if (PrevDecl) {
2876      ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
2877      ClassTemplate->getSpecializations().GetOrInsertNode(Specialization);
2878    } else {
2879      ClassTemplate->getSpecializations().InsertNode(Specialization,
2880                                                     InsertPos);
2881    }
2882
2883    CanonType = Context.getTypeDeclType(Specialization);
2884  }
2885
2886  // If this is not a friend, note that this is an explicit specialization.
2887  if (TUK != TUK_Friend)
2888    Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
2889
2890  // Check that this isn't a redefinition of this specialization.
2891  if (TUK == TUK_Definition) {
2892    if (RecordDecl *Def = Specialization->getDefinition(Context)) {
2893      // FIXME: Should also handle explicit specialization after implicit
2894      // instantiation with a special diagnostic.
2895      SourceRange Range(TemplateNameLoc, RAngleLoc);
2896      Diag(TemplateNameLoc, diag::err_redefinition)
2897        << Context.getTypeDeclType(Specialization) << Range;
2898      Diag(Def->getLocation(), diag::note_previous_definition);
2899      Specialization->setInvalidDecl();
2900      return true;
2901    }
2902  }
2903
2904  // Build the fully-sugared type for this class template
2905  // specialization as the user wrote in the specialization
2906  // itself. This means that we'll pretty-print the type retrieved
2907  // from the specialization's declaration the way that the user
2908  // actually wrote the specialization, rather than formatting the
2909  // name based on the "canonical" representation used to store the
2910  // template arguments in the specialization.
2911  QualType WrittenTy
2912    = Context.getTemplateSpecializationType(Name,
2913                                            TemplateArgs.data(),
2914                                            TemplateArgs.size(),
2915                                            CanonType);
2916  if (TUK != TUK_Friend)
2917    Specialization->setTypeAsWritten(WrittenTy);
2918  TemplateArgsIn.release();
2919
2920  // C++ [temp.expl.spec]p9:
2921  //   A template explicit specialization is in the scope of the
2922  //   namespace in which the template was defined.
2923  //
2924  // We actually implement this paragraph where we set the semantic
2925  // context (in the creation of the ClassTemplateSpecializationDecl),
2926  // but we also maintain the lexical context where the actual
2927  // definition occurs.
2928  Specialization->setLexicalDeclContext(CurContext);
2929
2930  // We may be starting the definition of this specialization.
2931  if (TUK == TUK_Definition)
2932    Specialization->startDefinition();
2933
2934  if (TUK == TUK_Friend) {
2935    FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
2936                                            TemplateNameLoc,
2937                                            WrittenTy.getTypePtr(),
2938                                            /*FIXME:*/KWLoc);
2939    Friend->setAccess(AS_public);
2940    CurContext->addDecl(Friend);
2941  } else {
2942    // Add the specialization into its lexical context, so that it can
2943    // be seen when iterating through the list of declarations in that
2944    // context. However, specializations are not found by name lookup.
2945    CurContext->addDecl(Specialization);
2946  }
2947  return DeclPtrTy::make(Specialization);
2948}
2949
2950Sema::DeclPtrTy
2951Sema::ActOnTemplateDeclarator(Scope *S,
2952                              MultiTemplateParamsArg TemplateParameterLists,
2953                              Declarator &D) {
2954  return HandleDeclarator(S, D, move(TemplateParameterLists), false);
2955}
2956
2957Sema::DeclPtrTy
2958Sema::ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope,
2959                               MultiTemplateParamsArg TemplateParameterLists,
2960                                      Declarator &D) {
2961  assert(getCurFunctionDecl() == 0 && "Function parsing confused");
2962  assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
2963         "Not a function declarator!");
2964  DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2965
2966  if (FTI.hasPrototype) {
2967    // FIXME: Diagnose arguments without names in C.
2968  }
2969
2970  Scope *ParentScope = FnBodyScope->getParent();
2971
2972  DeclPtrTy DP = HandleDeclarator(ParentScope, D,
2973                                  move(TemplateParameterLists),
2974                                  /*IsFunctionDefinition=*/true);
2975  if (FunctionTemplateDecl *FunctionTemplate
2976        = dyn_cast_or_null<FunctionTemplateDecl>(DP.getAs<Decl>()))
2977    return ActOnStartOfFunctionDef(FnBodyScope,
2978                      DeclPtrTy::make(FunctionTemplate->getTemplatedDecl()));
2979  if (FunctionDecl *Function = dyn_cast_or_null<FunctionDecl>(DP.getAs<Decl>()))
2980    return ActOnStartOfFunctionDef(FnBodyScope, DeclPtrTy::make(Function));
2981  return DeclPtrTy();
2982}
2983
2984/// \brief Perform semantic analysis for the given function template
2985/// specialization.
2986///
2987/// This routine performs all of the semantic analysis required for an
2988/// explicit function template specialization. On successful completion,
2989/// the function declaration \p FD will become a function template
2990/// specialization.
2991///
2992/// \param FD the function declaration, which will be updated to become a
2993/// function template specialization.
2994///
2995/// \param HasExplicitTemplateArgs whether any template arguments were
2996/// explicitly provided.
2997///
2998/// \param LAngleLoc the location of the left angle bracket ('<'), if
2999/// template arguments were explicitly provided.
3000///
3001/// \param ExplicitTemplateArgs the explicitly-provided template arguments,
3002/// if any.
3003///
3004/// \param NumExplicitTemplateArgs the number of explicitly-provided template
3005/// arguments. This number may be zero even when HasExplicitTemplateArgs is
3006/// true as in, e.g., \c void sort<>(char*, char*);
3007///
3008/// \param RAngleLoc the location of the right angle bracket ('>'), if
3009/// template arguments were explicitly provided.
3010///
3011/// \param PrevDecl the set of declarations that
3012bool
3013Sema::CheckFunctionTemplateSpecialization(FunctionDecl *FD,
3014                                          bool HasExplicitTemplateArgs,
3015                                          SourceLocation LAngleLoc,
3016                              const TemplateArgument *ExplicitTemplateArgs,
3017                                          unsigned NumExplicitTemplateArgs,
3018                                          SourceLocation RAngleLoc,
3019                                          NamedDecl *&PrevDecl) {
3020  // The set of function template specializations that could match this
3021  // explicit function template specialization.
3022  typedef llvm::SmallVector<FunctionDecl *, 8> CandidateSet;
3023  CandidateSet Candidates;
3024
3025  DeclContext *FDLookupContext = FD->getDeclContext()->getLookupContext();
3026  for (OverloadIterator Ovl(PrevDecl), OvlEnd; Ovl != OvlEnd; ++Ovl) {
3027    if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(*Ovl)) {
3028      // Only consider templates found within the same semantic lookup scope as
3029      // FD.
3030      if (!FDLookupContext->Equals(Ovl->getDeclContext()->getLookupContext()))
3031        continue;
3032
3033      // C++ [temp.expl.spec]p11:
3034      //   A trailing template-argument can be left unspecified in the
3035      //   template-id naming an explicit function template specialization
3036      //   provided it can be deduced from the function argument type.
3037      // Perform template argument deduction to determine whether we may be
3038      // specializing this template.
3039      // FIXME: It is somewhat wasteful to build
3040      TemplateDeductionInfo Info(Context);
3041      FunctionDecl *Specialization = 0;
3042      if (TemplateDeductionResult TDK
3043            = DeduceTemplateArguments(FunTmpl, HasExplicitTemplateArgs,
3044                                      ExplicitTemplateArgs,
3045                                      NumExplicitTemplateArgs,
3046                                      FD->getType(),
3047                                      Specialization,
3048                                      Info)) {
3049        // FIXME: Template argument deduction failed; record why it failed, so
3050        // that we can provide nifty diagnostics.
3051        (void)TDK;
3052        continue;
3053      }
3054
3055      // Record this candidate.
3056      Candidates.push_back(Specialization);
3057    }
3058  }
3059
3060  // Find the most specialized function template.
3061  FunctionDecl *Specialization = getMostSpecialized(Candidates.data(),
3062                                                    Candidates.size(),
3063                                                    TPOC_Other,
3064                                                    FD->getLocation(),
3065                  PartialDiagnostic(diag::err_function_template_spec_no_match)
3066                    << FD->getDeclName(),
3067                  PartialDiagnostic(diag::err_function_template_spec_ambiguous)
3068                    << FD->getDeclName() << HasExplicitTemplateArgs,
3069                  PartialDiagnostic(diag::note_function_template_spec_matched));
3070  if (!Specialization)
3071    return true;
3072
3073  // FIXME: Check if the prior specialization has a point of instantiation.
3074  // If so, we have run afoul of C++ [temp.expl.spec]p6.
3075
3076  // Check the scope of this explicit specialization.
3077  if (CheckTemplateSpecializationScope(*this,
3078                                       Specialization->getPrimaryTemplate(),
3079                                       Specialization, FD->getLocation(),
3080                                       false, TSK_ExplicitSpecialization))
3081    return true;
3082
3083  // Mark the prior declaration as an explicit specialization, so that later
3084  // clients know that this is an explicit specialization.
3085  // FIXME: Check for prior explicit instantiations?
3086  Specialization->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
3087
3088  // Turn the given function declaration into a function template
3089  // specialization, with the template arguments from the previous
3090  // specialization.
3091  FD->setFunctionTemplateSpecialization(Context,
3092                                        Specialization->getPrimaryTemplate(),
3093                         new (Context) TemplateArgumentList(
3094                             *Specialization->getTemplateSpecializationArgs()),
3095                                        /*InsertPos=*/0,
3096                                        TSK_ExplicitSpecialization);
3097
3098  // The "previous declaration" for this function template specialization is
3099  // the prior function template specialization.
3100  PrevDecl = Specialization;
3101  return false;
3102}
3103
3104// Explicit instantiation of a class template specialization
3105// FIXME: Implement extern template semantics
3106Sema::DeclResult
3107Sema::ActOnExplicitInstantiation(Scope *S,
3108                                 SourceLocation ExternLoc,
3109                                 SourceLocation TemplateLoc,
3110                                 unsigned TagSpec,
3111                                 SourceLocation KWLoc,
3112                                 const CXXScopeSpec &SS,
3113                                 TemplateTy TemplateD,
3114                                 SourceLocation TemplateNameLoc,
3115                                 SourceLocation LAngleLoc,
3116                                 ASTTemplateArgsPtr TemplateArgsIn,
3117                                 SourceLocation *TemplateArgLocs,
3118                                 SourceLocation RAngleLoc,
3119                                 AttributeList *Attr) {
3120  // Find the class template we're specializing
3121  TemplateName Name = TemplateD.getAsVal<TemplateName>();
3122  ClassTemplateDecl *ClassTemplate
3123    = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
3124
3125  // Check that the specialization uses the same tag kind as the
3126  // original template.
3127  TagDecl::TagKind Kind;
3128  switch (TagSpec) {
3129  default: assert(0 && "Unknown tag type!");
3130  case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
3131  case DeclSpec::TST_union:  Kind = TagDecl::TK_union; break;
3132  case DeclSpec::TST_class:  Kind = TagDecl::TK_class; break;
3133  }
3134  if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
3135                                    Kind, KWLoc,
3136                                    *ClassTemplate->getIdentifier())) {
3137    Diag(KWLoc, diag::err_use_with_wrong_tag)
3138      << ClassTemplate
3139      << CodeModificationHint::CreateReplacement(KWLoc,
3140                            ClassTemplate->getTemplatedDecl()->getKindName());
3141    Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
3142         diag::note_previous_use);
3143    Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
3144  }
3145
3146  TemplateSpecializationKind TSK
3147    = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
3148                           : TSK_ExplicitInstantiationDeclaration;
3149
3150  // Translate the parser's template argument list in our AST format.
3151  llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
3152  translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
3153
3154  // Check that the template argument list is well-formed for this
3155  // template.
3156  TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
3157                                        TemplateArgs.size());
3158  if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, LAngleLoc,
3159                                TemplateArgs.data(), TemplateArgs.size(),
3160                                RAngleLoc, false, Converted))
3161    return true;
3162
3163  assert((Converted.structuredSize() ==
3164            ClassTemplate->getTemplateParameters()->size()) &&
3165         "Converted template argument list is too short!");
3166
3167  // Find the class template specialization declaration that
3168  // corresponds to these arguments.
3169  llvm::FoldingSetNodeID ID;
3170  ClassTemplateSpecializationDecl::Profile(ID,
3171                                           Converted.getFlatArguments(),
3172                                           Converted.flatSize(),
3173                                           Context);
3174  void *InsertPos = 0;
3175  ClassTemplateSpecializationDecl *PrevDecl
3176    = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
3177
3178  // C++0x [temp.explicit]p2:
3179  //   [...] An explicit instantiation shall appear in an enclosing
3180  //   namespace of its template. [...]
3181  //
3182  // This is C++ DR 275.
3183  if (CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
3184                                       TemplateNameLoc, false,
3185                                       TSK))
3186    return true;
3187
3188  ClassTemplateSpecializationDecl *Specialization = 0;
3189
3190  bool SpecializationRequiresInstantiation = true;
3191  if (PrevDecl) {
3192    if (PrevDecl->getSpecializationKind()
3193          == TSK_ExplicitInstantiationDefinition) {
3194      // This particular specialization has already been declared or
3195      // instantiated. We cannot explicitly instantiate it.
3196      Diag(TemplateNameLoc, diag::err_explicit_instantiation_duplicate)
3197        << Context.getTypeDeclType(PrevDecl);
3198      Diag(PrevDecl->getLocation(),
3199           diag::note_previous_explicit_instantiation);
3200      return DeclPtrTy::make(PrevDecl);
3201    }
3202
3203    if (PrevDecl->getSpecializationKind() == TSK_ExplicitSpecialization) {
3204      // C++ DR 259, C++0x [temp.explicit]p4:
3205      //   For a given set of template parameters, if an explicit
3206      //   instantiation of a template appears after a declaration of
3207      //   an explicit specialization for that template, the explicit
3208      //   instantiation has no effect.
3209      if (!getLangOptions().CPlusPlus0x) {
3210        Diag(TemplateNameLoc,
3211             diag::ext_explicit_instantiation_after_specialization)
3212          << Context.getTypeDeclType(PrevDecl);
3213        Diag(PrevDecl->getLocation(),
3214             diag::note_previous_template_specialization);
3215      }
3216
3217      // Create a new class template specialization declaration node
3218      // for this explicit specialization. This node is only used to
3219      // record the existence of this explicit instantiation for
3220      // accurate reproduction of the source code; we don't actually
3221      // use it for anything, since it is semantically irrelevant.
3222      Specialization
3223        = ClassTemplateSpecializationDecl::Create(Context,
3224                                             ClassTemplate->getDeclContext(),
3225                                                  TemplateNameLoc,
3226                                                  ClassTemplate,
3227                                                  Converted, 0);
3228      Specialization->setLexicalDeclContext(CurContext);
3229      CurContext->addDecl(Specialization);
3230      return DeclPtrTy::make(PrevDecl);
3231    }
3232
3233    // If we have already (implicitly) instantiated this
3234    // specialization, there is less work to do.
3235    if (PrevDecl->getSpecializationKind() == TSK_ImplicitInstantiation)
3236      SpecializationRequiresInstantiation = false;
3237
3238    if (PrevDecl->getSpecializationKind() == TSK_ImplicitInstantiation ||
3239        PrevDecl->getSpecializationKind() == TSK_Undeclared) {
3240      // Since the only prior class template specialization with these
3241      // arguments was referenced but not declared, reuse that
3242      // declaration node as our own, updating its source location to
3243      // reflect our new declaration.
3244      Specialization = PrevDecl;
3245      Specialization->setLocation(TemplateNameLoc);
3246      PrevDecl = 0;
3247    }
3248  }
3249
3250  if (!Specialization) {
3251    // Create a new class template specialization declaration node for
3252    // this explicit specialization.
3253    Specialization
3254      = ClassTemplateSpecializationDecl::Create(Context,
3255                                             ClassTemplate->getDeclContext(),
3256                                                TemplateNameLoc,
3257                                                ClassTemplate,
3258                                                Converted, PrevDecl);
3259
3260    if (PrevDecl) {
3261      // Remove the previous declaration from the folding set, since we want
3262      // to introduce a new declaration.
3263      ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
3264      ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
3265    }
3266
3267    // Insert the new specialization.
3268    ClassTemplate->getSpecializations().InsertNode(Specialization, InsertPos);
3269  }
3270
3271  // Build the fully-sugared type for this explicit instantiation as
3272  // the user wrote in the explicit instantiation itself. This means
3273  // that we'll pretty-print the type retrieved from the
3274  // specialization's declaration the way that the user actually wrote
3275  // the explicit instantiation, rather than formatting the name based
3276  // on the "canonical" representation used to store the template
3277  // arguments in the specialization.
3278  QualType WrittenTy
3279    = Context.getTemplateSpecializationType(Name,
3280                                            TemplateArgs.data(),
3281                                            TemplateArgs.size(),
3282                                  Context.getTypeDeclType(Specialization));
3283  Specialization->setTypeAsWritten(WrittenTy);
3284  TemplateArgsIn.release();
3285
3286  // Add the explicit instantiation into its lexical context. However,
3287  // since explicit instantiations are never found by name lookup, we
3288  // just put it into the declaration context directly.
3289  Specialization->setLexicalDeclContext(CurContext);
3290  CurContext->addDecl(Specialization);
3291
3292  Specialization->setPointOfInstantiation(TemplateNameLoc);
3293
3294  // C++ [temp.explicit]p3:
3295  //   A definition of a class template or class member template
3296  //   shall be in scope at the point of the explicit instantiation of
3297  //   the class template or class member template.
3298  //
3299  // This check comes when we actually try to perform the
3300  // instantiation.
3301  if (SpecializationRequiresInstantiation)
3302    InstantiateClassTemplateSpecialization(Specialization, TSK);
3303  else // Instantiate the members of this class template specialization.
3304    InstantiateClassTemplateSpecializationMembers(TemplateLoc, Specialization,
3305                                                  TSK);
3306
3307  return DeclPtrTy::make(Specialization);
3308}
3309
3310// Explicit instantiation of a member class of a class template.
3311Sema::DeclResult
3312Sema::ActOnExplicitInstantiation(Scope *S,
3313                                 SourceLocation ExternLoc,
3314                                 SourceLocation TemplateLoc,
3315                                 unsigned TagSpec,
3316                                 SourceLocation KWLoc,
3317                                 const CXXScopeSpec &SS,
3318                                 IdentifierInfo *Name,
3319                                 SourceLocation NameLoc,
3320                                 AttributeList *Attr) {
3321
3322  bool Owned = false;
3323  bool IsDependent = false;
3324  DeclPtrTy TagD = ActOnTag(S, TagSpec, Action::TUK_Reference,
3325                            KWLoc, SS, Name, NameLoc, Attr, AS_none,
3326                            MultiTemplateParamsArg(*this, 0, 0),
3327                            Owned, IsDependent);
3328  assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
3329
3330  if (!TagD)
3331    return true;
3332
3333  TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>());
3334  if (Tag->isEnum()) {
3335    Diag(TemplateLoc, diag::err_explicit_instantiation_enum)
3336      << Context.getTypeDeclType(Tag);
3337    return true;
3338  }
3339
3340  if (Tag->isInvalidDecl())
3341    return true;
3342
3343  CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
3344  CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
3345  if (!Pattern) {
3346    Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
3347      << Context.getTypeDeclType(Record);
3348    Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
3349    return true;
3350  }
3351
3352  // C++0x [temp.explicit]p2:
3353  //   [...] An explicit instantiation shall appear in an enclosing
3354  //   namespace of its template. [...]
3355  //
3356  // This is C++ DR 275.
3357  if (getLangOptions().CPlusPlus0x) {
3358    // FIXME: In C++98, we would like to turn these errors into warnings,
3359    // dependent on a -Wc++0x flag.
3360    DeclContext *PatternContext
3361      = Pattern->getDeclContext()->getEnclosingNamespaceContext();
3362    if (!CurContext->Encloses(PatternContext)) {
3363      Diag(TemplateLoc, diag::err_explicit_instantiation_out_of_scope)
3364        << Record << cast<NamedDecl>(PatternContext) << SS.getRange();
3365      Diag(Pattern->getLocation(), diag::note_previous_declaration);
3366    }
3367  }
3368
3369  TemplateSpecializationKind TSK
3370    = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
3371                           : TSK_ExplicitInstantiationDeclaration;
3372
3373  if (!Record->getDefinition(Context)) {
3374    // If the class has a definition, instantiate it (and all of its
3375    // members, recursively).
3376    Pattern = cast_or_null<CXXRecordDecl>(Pattern->getDefinition(Context));
3377    if (Pattern && InstantiateClass(TemplateLoc, Record, Pattern,
3378                                    getTemplateInstantiationArgs(Record),
3379                                    TSK))
3380      return true;
3381  } else // Instantiate all of the members of the class.
3382    InstantiateClassMembers(TemplateLoc, Record,
3383                            getTemplateInstantiationArgs(Record), TSK);
3384
3385  // FIXME: We don't have any representation for explicit instantiations of
3386  // member classes. Such a representation is not needed for compilation, but it
3387  // should be available for clients that want to see all of the declarations in
3388  // the source code.
3389  return TagD;
3390}
3391
3392Sema::DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
3393                                                  SourceLocation ExternLoc,
3394                                                  SourceLocation TemplateLoc,
3395                                                  Declarator &D) {
3396  // Explicit instantiations always require a name.
3397  DeclarationName Name = GetNameForDeclarator(D);
3398  if (!Name) {
3399    if (!D.isInvalidType())
3400      Diag(D.getDeclSpec().getSourceRange().getBegin(),
3401           diag::err_explicit_instantiation_requires_name)
3402        << D.getDeclSpec().getSourceRange()
3403        << D.getSourceRange();
3404
3405    return true;
3406  }
3407
3408  // The scope passed in may not be a decl scope.  Zip up the scope tree until
3409  // we find one that is.
3410  while ((S->getFlags() & Scope::DeclScope) == 0 ||
3411         (S->getFlags() & Scope::TemplateParamScope) != 0)
3412    S = S->getParent();
3413
3414  // Determine the type of the declaration.
3415  QualType R = GetTypeForDeclarator(D, S, 0);
3416  if (R.isNull())
3417    return true;
3418
3419  if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
3420    // Cannot explicitly instantiate a typedef.
3421    Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
3422      << Name;
3423    return true;
3424  }
3425
3426  // Determine what kind of explicit instantiation we have.
3427  TemplateSpecializationKind TSK
3428    = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
3429                           : TSK_ExplicitInstantiationDeclaration;
3430
3431  LookupResult Previous = LookupParsedName(S, &D.getCXXScopeSpec(),
3432                                           Name, LookupOrdinaryName);
3433
3434  if (!R->isFunctionType()) {
3435    // C++ [temp.explicit]p1:
3436    //   A [...] static data member of a class template can be explicitly
3437    //   instantiated from the member definition associated with its class
3438    //   template.
3439    if (Previous.isAmbiguous()) {
3440      return DiagnoseAmbiguousLookup(Previous, Name, D.getIdentifierLoc(),
3441                                     D.getSourceRange());
3442    }
3443
3444    VarDecl *Prev = dyn_cast_or_null<VarDecl>(Previous.getAsDecl());
3445    if (!Prev || !Prev->isStaticDataMember()) {
3446      // We expect to see a data data member here.
3447      Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
3448        << Name;
3449      for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
3450           P != PEnd; ++P)
3451        Diag(P->getLocation(), diag::note_explicit_instantiation_here);
3452      return true;
3453    }
3454
3455    if (!Prev->getInstantiatedFromStaticDataMember()) {
3456      // FIXME: Check for explicit specialization?
3457      Diag(D.getIdentifierLoc(),
3458           diag::err_explicit_instantiation_data_member_not_instantiated)
3459        << Prev;
3460      Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
3461      // FIXME: Can we provide a note showing where this was declared?
3462      return true;
3463    }
3464
3465    // Instantiate static data member.
3466    // FIXME: Note that this is an explicit instantiation.
3467    if (TSK == TSK_ExplicitInstantiationDefinition)
3468      InstantiateStaticDataMemberDefinition(D.getIdentifierLoc(), Prev, false);
3469
3470    // FIXME: Create an ExplicitInstantiation node?
3471    return DeclPtrTy();
3472  }
3473
3474  // If the declarator is a template-id, translate the parser's template
3475  // argument list into our AST format.
3476  bool HasExplicitTemplateArgs = false;
3477  llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
3478  if (D.getKind() == Declarator::DK_TemplateId) {
3479    TemplateIdAnnotation *TemplateId = D.getTemplateId();
3480    ASTTemplateArgsPtr TemplateArgsPtr(*this,
3481                                       TemplateId->getTemplateArgs(),
3482                                       TemplateId->getTemplateArgIsType(),
3483                                       TemplateId->NumArgs);
3484    translateTemplateArguments(TemplateArgsPtr,
3485                               TemplateId->getTemplateArgLocations(),
3486                               TemplateArgs);
3487    HasExplicitTemplateArgs = true;
3488    TemplateArgsPtr.release();
3489  }
3490
3491  // C++ [temp.explicit]p1:
3492  //   A [...] function [...] can be explicitly instantiated from its template.
3493  //   A member function [...] of a class template can be explicitly
3494  //  instantiated from the member definition associated with its class
3495  //  template.
3496  llvm::SmallVector<FunctionDecl *, 8> Matches;
3497  for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
3498       P != PEnd; ++P) {
3499    NamedDecl *Prev = *P;
3500    if (!HasExplicitTemplateArgs) {
3501      if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
3502        if (Context.hasSameUnqualifiedType(Method->getType(), R)) {
3503          Matches.clear();
3504          Matches.push_back(Method);
3505          break;
3506        }
3507      }
3508    }
3509
3510    FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
3511    if (!FunTmpl)
3512      continue;
3513
3514    TemplateDeductionInfo Info(Context);
3515    FunctionDecl *Specialization = 0;
3516    if (TemplateDeductionResult TDK
3517          = DeduceTemplateArguments(FunTmpl, HasExplicitTemplateArgs,
3518                                    TemplateArgs.data(), TemplateArgs.size(),
3519                                    R, Specialization, Info)) {
3520      // FIXME: Keep track of almost-matches?
3521      (void)TDK;
3522      continue;
3523    }
3524
3525    Matches.push_back(Specialization);
3526  }
3527
3528  // Find the most specialized function template specialization.
3529  FunctionDecl *Specialization
3530    = getMostSpecialized(Matches.data(), Matches.size(), TPOC_Other,
3531                         D.getIdentifierLoc(),
3532          PartialDiagnostic(diag::err_explicit_instantiation_not_known) << Name,
3533          PartialDiagnostic(diag::err_explicit_instantiation_ambiguous) << Name,
3534                PartialDiagnostic(diag::note_explicit_instantiation_candidate));
3535
3536  if (!Specialization)
3537    return true;
3538
3539  switch (Specialization->getTemplateSpecializationKind()) {
3540  case TSK_Undeclared:
3541    Diag(D.getIdentifierLoc(),
3542         diag::err_explicit_instantiation_member_function_not_instantiated)
3543      << Specialization
3544      << (Specialization->getTemplateSpecializationKind() ==
3545          TSK_ExplicitSpecialization);
3546    Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
3547    return true;
3548
3549  case TSK_ExplicitSpecialization:
3550    // C++ [temp.explicit]p4:
3551    //   For a given set of template parameters, if an explicit instantiation
3552    //   of a template appears after a declaration of an explicit
3553    //   specialization for that template, the explicit instantiation has no
3554    //   effect.
3555    break;
3556
3557  case TSK_ExplicitInstantiationDefinition:
3558    // FIXME: Check that we aren't trying to perform an explicit instantiation
3559    // declaration now.
3560    // Fall through
3561
3562  case TSK_ImplicitInstantiation:
3563  case TSK_ExplicitInstantiationDeclaration:
3564    // Instantiate the function, if this is an explicit instantiation
3565    // definition.
3566    if (TSK == TSK_ExplicitInstantiationDefinition)
3567      InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization,
3568                                    false);
3569
3570    // FIXME: setTemplateSpecializationKind doesn't (yet) work for
3571    // non-templated member functions.
3572    if (!Specialization->getPrimaryTemplate())
3573      break;
3574
3575    Specialization->setTemplateSpecializationKind(TSK);
3576    break;
3577  }
3578
3579  // FIXME: Create some kind of ExplicitInstantiationDecl here.
3580  return DeclPtrTy();
3581}
3582
3583Sema::TypeResult
3584Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
3585                        const CXXScopeSpec &SS, IdentifierInfo *Name,
3586                        SourceLocation TagLoc, SourceLocation NameLoc) {
3587  // This has to hold, because SS is expected to be defined.
3588  assert(Name && "Expected a name in a dependent tag");
3589
3590  NestedNameSpecifier *NNS
3591    = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
3592  if (!NNS)
3593    return true;
3594
3595  QualType T = CheckTypenameType(NNS, *Name, SourceRange(TagLoc, NameLoc));
3596  if (T.isNull())
3597    return true;
3598
3599  TagDecl::TagKind TagKind = TagDecl::getTagKindForTypeSpec(TagSpec);
3600  QualType ElabType = Context.getElaboratedType(T, TagKind);
3601
3602  return ElabType.getAsOpaquePtr();
3603}
3604
3605Sema::TypeResult
3606Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
3607                        const IdentifierInfo &II, SourceLocation IdLoc) {
3608  NestedNameSpecifier *NNS
3609    = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
3610  if (!NNS)
3611    return true;
3612
3613  QualType T = CheckTypenameType(NNS, II, SourceRange(TypenameLoc, IdLoc));
3614  if (T.isNull())
3615    return true;
3616  return T.getAsOpaquePtr();
3617}
3618
3619Sema::TypeResult
3620Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
3621                        SourceLocation TemplateLoc, TypeTy *Ty) {
3622  QualType T = GetTypeFromParser(Ty);
3623  NestedNameSpecifier *NNS
3624    = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
3625  const TemplateSpecializationType *TemplateId
3626    = T->getAs<TemplateSpecializationType>();
3627  assert(TemplateId && "Expected a template specialization type");
3628
3629  if (computeDeclContext(SS, false)) {
3630    // If we can compute a declaration context, then the "typename"
3631    // keyword was superfluous. Just build a QualifiedNameType to keep
3632    // track of the nested-name-specifier.
3633
3634    // FIXME: Note that the QualifiedNameType had the "typename" keyword!
3635    return Context.getQualifiedNameType(NNS, T).getAsOpaquePtr();
3636  }
3637
3638  return Context.getTypenameType(NNS, TemplateId).getAsOpaquePtr();
3639}
3640
3641/// \brief Build the type that describes a C++ typename specifier,
3642/// e.g., "typename T::type".
3643QualType
3644Sema::CheckTypenameType(NestedNameSpecifier *NNS, const IdentifierInfo &II,
3645                        SourceRange Range) {
3646  CXXRecordDecl *CurrentInstantiation = 0;
3647  if (NNS->isDependent()) {
3648    CurrentInstantiation = getCurrentInstantiationOf(NNS);
3649
3650    // If the nested-name-specifier does not refer to the current
3651    // instantiation, then build a typename type.
3652    if (!CurrentInstantiation)
3653      return Context.getTypenameType(NNS, &II);
3654
3655    // The nested-name-specifier refers to the current instantiation, so the
3656    // "typename" keyword itself is superfluous. In C++03, the program is
3657    // actually ill-formed. However, DR 382 (in C++0x CD1) allows such
3658    // extraneous "typename" keywords, and we retroactively apply this DR to
3659    // C++03 code.
3660  }
3661
3662  DeclContext *Ctx = 0;
3663
3664  if (CurrentInstantiation)
3665    Ctx = CurrentInstantiation;
3666  else {
3667    CXXScopeSpec SS;
3668    SS.setScopeRep(NNS);
3669    SS.setRange(Range);
3670    if (RequireCompleteDeclContext(SS))
3671      return QualType();
3672
3673    Ctx = computeDeclContext(SS);
3674  }
3675  assert(Ctx && "No declaration context?");
3676
3677  DeclarationName Name(&II);
3678  LookupResult Result = LookupQualifiedName(Ctx, Name, LookupOrdinaryName,
3679                                            false);
3680  unsigned DiagID = 0;
3681  Decl *Referenced = 0;
3682  switch (Result.getKind()) {
3683  case LookupResult::NotFound:
3684    if (Ctx->isTranslationUnit())
3685      DiagID = diag::err_typename_nested_not_found_global;
3686    else
3687      DiagID = diag::err_typename_nested_not_found;
3688    break;
3689
3690  case LookupResult::Found:
3691    if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getAsDecl())) {
3692      // We found a type. Build a QualifiedNameType, since the
3693      // typename-specifier was just sugar. FIXME: Tell
3694      // QualifiedNameType that it has a "typename" prefix.
3695      return Context.getQualifiedNameType(NNS, Context.getTypeDeclType(Type));
3696    }
3697
3698    DiagID = diag::err_typename_nested_not_type;
3699    Referenced = Result.getAsDecl();
3700    break;
3701
3702  case LookupResult::FoundOverloaded:
3703    DiagID = diag::err_typename_nested_not_type;
3704    Referenced = *Result.begin();
3705    break;
3706
3707  case LookupResult::AmbiguousBaseSubobjectTypes:
3708  case LookupResult::AmbiguousBaseSubobjects:
3709  case LookupResult::AmbiguousReference:
3710    DiagnoseAmbiguousLookup(Result, Name, Range.getEnd(), Range);
3711    return QualType();
3712  }
3713
3714  // If we get here, it's because name lookup did not find a
3715  // type. Emit an appropriate diagnostic and return an error.
3716  if (NamedDecl *NamedCtx = dyn_cast<NamedDecl>(Ctx))
3717    Diag(Range.getEnd(), DiagID) << Range << Name << NamedCtx;
3718  else
3719    Diag(Range.getEnd(), DiagID) << Range << Name;
3720  if (Referenced)
3721    Diag(Referenced->getLocation(), diag::note_typename_refers_here)
3722      << Name;
3723  return QualType();
3724}
3725
3726namespace {
3727  // See Sema::RebuildTypeInCurrentInstantiation
3728  class VISIBILITY_HIDDEN CurrentInstantiationRebuilder
3729    : public TreeTransform<CurrentInstantiationRebuilder> {
3730    SourceLocation Loc;
3731    DeclarationName Entity;
3732
3733  public:
3734    CurrentInstantiationRebuilder(Sema &SemaRef,
3735                                  SourceLocation Loc,
3736                                  DeclarationName Entity)
3737    : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
3738      Loc(Loc), Entity(Entity) { }
3739
3740    /// \brief Determine whether the given type \p T has already been
3741    /// transformed.
3742    ///
3743    /// For the purposes of type reconstruction, a type has already been
3744    /// transformed if it is NULL or if it is not dependent.
3745    bool AlreadyTransformed(QualType T) {
3746      return T.isNull() || !T->isDependentType();
3747    }
3748
3749    /// \brief Returns the location of the entity whose type is being
3750    /// rebuilt.
3751    SourceLocation getBaseLocation() { return Loc; }
3752
3753    /// \brief Returns the name of the entity whose type is being rebuilt.
3754    DeclarationName getBaseEntity() { return Entity; }
3755
3756    /// \brief Transforms an expression by returning the expression itself
3757    /// (an identity function).
3758    ///
3759    /// FIXME: This is completely unsafe; we will need to actually clone the
3760    /// expressions.
3761    Sema::OwningExprResult TransformExpr(Expr *E) {
3762      return getSema().Owned(E);
3763    }
3764
3765    /// \brief Transforms a typename type by determining whether the type now
3766    /// refers to a member of the current instantiation, and then
3767    /// type-checking and building a QualifiedNameType (when possible).
3768    QualType TransformTypenameType(const TypenameType *T);
3769  };
3770}
3771
3772QualType
3773CurrentInstantiationRebuilder::TransformTypenameType(const TypenameType *T) {
3774  NestedNameSpecifier *NNS
3775    = TransformNestedNameSpecifier(T->getQualifier(),
3776                              /*FIXME:*/SourceRange(getBaseLocation()));
3777  if (!NNS)
3778    return QualType();
3779
3780  // If the nested-name-specifier did not change, and we cannot compute the
3781  // context corresponding to the nested-name-specifier, then this
3782  // typename type will not change; exit early.
3783  CXXScopeSpec SS;
3784  SS.setRange(SourceRange(getBaseLocation()));
3785  SS.setScopeRep(NNS);
3786  if (NNS == T->getQualifier() && getSema().computeDeclContext(SS) == 0)
3787    return QualType(T, 0);
3788
3789  // Rebuild the typename type, which will probably turn into a
3790  // QualifiedNameType.
3791  if (const TemplateSpecializationType *TemplateId = T->getTemplateId()) {
3792    QualType NewTemplateId
3793      = TransformType(QualType(TemplateId, 0));
3794    if (NewTemplateId.isNull())
3795      return QualType();
3796
3797    if (NNS == T->getQualifier() &&
3798        NewTemplateId == QualType(TemplateId, 0))
3799      return QualType(T, 0);
3800
3801    return getDerived().RebuildTypenameType(NNS, NewTemplateId);
3802  }
3803
3804  return getDerived().RebuildTypenameType(NNS, T->getIdentifier());
3805}
3806
3807/// \brief Rebuilds a type within the context of the current instantiation.
3808///
3809/// The type \p T is part of the type of an out-of-line member definition of
3810/// a class template (or class template partial specialization) that was parsed
3811/// and constructed before we entered the scope of the class template (or
3812/// partial specialization thereof). This routine will rebuild that type now
3813/// that we have entered the declarator's scope, which may produce different
3814/// canonical types, e.g.,
3815///
3816/// \code
3817/// template<typename T>
3818/// struct X {
3819///   typedef T* pointer;
3820///   pointer data();
3821/// };
3822///
3823/// template<typename T>
3824/// typename X<T>::pointer X<T>::data() { ... }
3825/// \endcode
3826///
3827/// Here, the type "typename X<T>::pointer" will be created as a TypenameType,
3828/// since we do not know that we can look into X<T> when we parsed the type.
3829/// This function will rebuild the type, performing the lookup of "pointer"
3830/// in X<T> and returning a QualifiedNameType whose canonical type is the same
3831/// as the canonical type of T*, allowing the return types of the out-of-line
3832/// definition and the declaration to match.
3833QualType Sema::RebuildTypeInCurrentInstantiation(QualType T, SourceLocation Loc,
3834                                                 DeclarationName Name) {
3835  if (T.isNull() || !T->isDependentType())
3836    return T;
3837
3838  CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
3839  return Rebuilder.TransformType(T);
3840}
3841
3842/// \brief Produces a formatted string that describes the binding of
3843/// template parameters to template arguments.
3844std::string
3845Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
3846                                      const TemplateArgumentList &Args) {
3847  std::string Result;
3848
3849  if (!Params || Params->size() == 0)
3850    return Result;
3851
3852  for (unsigned I = 0, N = Params->size(); I != N; ++I) {
3853    if (I == 0)
3854      Result += "[with ";
3855    else
3856      Result += ", ";
3857
3858    if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
3859      Result += Id->getName();
3860    } else {
3861      Result += '$';
3862      Result += llvm::utostr(I);
3863    }
3864
3865    Result += " = ";
3866
3867    switch (Args[I].getKind()) {
3868      case TemplateArgument::Null:
3869        Result += "<no value>";
3870        break;
3871
3872      case TemplateArgument::Type: {
3873        std::string TypeStr;
3874        Args[I].getAsType().getAsStringInternal(TypeStr,
3875                                                Context.PrintingPolicy);
3876        Result += TypeStr;
3877        break;
3878      }
3879
3880      case TemplateArgument::Declaration: {
3881        bool Unnamed = true;
3882        if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(Args[I].getAsDecl())) {
3883          if (ND->getDeclName()) {
3884            Unnamed = false;
3885            Result += ND->getNameAsString();
3886          }
3887        }
3888
3889        if (Unnamed) {
3890          Result += "<anonymous>";
3891        }
3892        break;
3893      }
3894
3895      case TemplateArgument::Integral: {
3896        Result += Args[I].getAsIntegral()->toString(10);
3897        break;
3898      }
3899
3900      case TemplateArgument::Expression: {
3901        assert(false && "No expressions in deduced template arguments!");
3902        Result += "<expression>";
3903        break;
3904      }
3905
3906      case TemplateArgument::Pack:
3907        // FIXME: Format template argument packs
3908        Result += "<template argument pack>";
3909        break;
3910    }
3911  }
3912
3913  Result += ']';
3914  return Result;
3915}
3916