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