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