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