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