SemaTemplate.cpp revision 16df850bb73e8e2a3dece830b59785ff167428bc
1//===------- SemaTemplate.cpp - Semantic Analysis for C++ Templates -------===/
2
3//
4//                     The LLVM Compiler Infrastructure
5//
6// This file is distributed under the University of Illinois Open Source
7// License. See LICENSE.TXT for details.
8//===----------------------------------------------------------------------===/
9
10//
11//  This file implements semantic analysis for C++ templates.
12//===----------------------------------------------------------------------===/
13
14#include "Sema.h"
15#include "clang/AST/ASTContext.h"
16#include "clang/AST/Expr.h"
17#include "clang/AST/ExprCXX.h"
18#include "clang/AST/DeclTemplate.h"
19#include "clang/Parse/DeclSpec.h"
20#include "clang/Basic/LangOptions.h"
21
22using namespace clang;
23
24/// isTemplateName - Determines whether the identifier II is a
25/// template name in the current scope, and returns the template
26/// declaration if II names a template. An optional CXXScope can be
27/// passed to indicate the C++ scope in which the identifier will be
28/// found.
29TemplateNameKind Sema::isTemplateName(const IdentifierInfo &II, Scope *S,
30                                      TemplateTy &TemplateResult,
31                                      const CXXScopeSpec *SS) {
32  NamedDecl *IIDecl = LookupParsedName(S, SS, &II, LookupOrdinaryName);
33
34  TemplateNameKind TNK = TNK_Non_template;
35  TemplateDecl *Template = 0;
36
37  if (IIDecl) {
38    if ((Template = dyn_cast<TemplateDecl>(IIDecl))) {
39      if (isa<FunctionTemplateDecl>(IIDecl))
40        TNK = TNK_Function_template;
41      else if (isa<ClassTemplateDecl>(IIDecl) ||
42               isa<TemplateTemplateParmDecl>(IIDecl))
43        TNK = TNK_Type_template;
44      else
45        assert(false && "Unknown template declaration kind");
46    } else if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(IIDecl)) {
47      // C++ [temp.local]p1:
48      //   Like normal (non-template) classes, class templates have an
49      //   injected-class-name (Clause 9). The injected-class-name
50      //   can be used with or without a template-argument-list. When
51      //   it is used without a template-argument-list, it is
52      //   equivalent to the injected-class-name followed by the
53      //   template-parameters of the class template enclosed in
54      //   <>. When it is used with a template-argument-list, it
55      //   refers to the specified class template specialization,
56      //   which could be the current specialization or another
57      //   specialization.
58      if (Record->isInjectedClassName()) {
59        Record = cast<CXXRecordDecl>(Context.getCanonicalDecl(Record));
60        if ((Template = Record->getDescribedClassTemplate()))
61          TNK = TNK_Type_template;
62        else if (ClassTemplateSpecializationDecl *Spec
63                   = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
64          Template = Spec->getSpecializedTemplate();
65          TNK = TNK_Type_template;
66        }
67      }
68    }
69
70    // FIXME: What follows is a gross hack.
71    if (FunctionDecl *FD = dyn_cast<FunctionDecl>(IIDecl)) {
72      if (FD->getType()->isDependentType()) {
73        TemplateResult = TemplateTy::make(FD);
74        return TNK_Function_template;
75      }
76    } else if (OverloadedFunctionDecl *Ovl
77                 = dyn_cast<OverloadedFunctionDecl>(IIDecl)) {
78      for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(),
79                                                  FEnd = Ovl->function_end();
80           F != FEnd; ++F) {
81        if ((*F)->getType()->isDependentType()) {
82          TemplateResult = TemplateTy::make(Ovl);
83          return TNK_Function_template;
84        }
85      }
86    }
87
88    if (TNK != TNK_Non_template) {
89      if (SS && SS->isSet() && !SS->isInvalid()) {
90        NestedNameSpecifier *Qualifier
91          = static_cast<NestedNameSpecifier *>(SS->getScopeRep());
92        TemplateResult
93          = TemplateTy::make(Context.getQualifiedTemplateName(Qualifier,
94                                                              false,
95                                                              Template));
96      } else
97        TemplateResult = TemplateTy::make(TemplateName(Template));
98    }
99  }
100  return TNK;
101}
102
103/// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
104/// that the template parameter 'PrevDecl' is being shadowed by a new
105/// declaration at location Loc. Returns true to indicate that this is
106/// an error, and false otherwise.
107bool Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
108  assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
109
110  // Microsoft Visual C++ permits template parameters to be shadowed.
111  if (getLangOptions().Microsoft)
112    return false;
113
114  // C++ [temp.local]p4:
115  //   A template-parameter shall not be redeclared within its
116  //   scope (including nested scopes).
117  Diag(Loc, diag::err_template_param_shadow)
118    << cast<NamedDecl>(PrevDecl)->getDeclName();
119  Diag(PrevDecl->getLocation(), diag::note_template_param_here);
120  return true;
121}
122
123/// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
124/// the parameter D to reference the templated declaration and return a pointer
125/// to the template declaration. Otherwise, do nothing to D and return null.
126TemplateDecl *Sema::AdjustDeclIfTemplate(DeclPtrTy &D) {
127  if (TemplateDecl *Temp = dyn_cast<TemplateDecl>(D.getAs<Decl>())) {
128    D = DeclPtrTy::make(Temp->getTemplatedDecl());
129    return Temp;
130  }
131  return 0;
132}
133
134/// ActOnTypeParameter - Called when a C++ template type parameter
135/// (e.g., "typename T") has been parsed. Typename specifies whether
136/// the keyword "typename" was used to declare the type parameter
137/// (otherwise, "class" was used), and KeyLoc is the location of the
138/// "class" or "typename" keyword. ParamName is the name of the
139/// parameter (NULL indicates an unnamed template parameter) and
140/// ParamName is the location of the parameter name (if any).
141/// If the type parameter has a default argument, it will be added
142/// later via ActOnTypeParameterDefault.
143Sema::DeclPtrTy Sema::ActOnTypeParameter(Scope *S, bool Typename, bool Ellipsis,
144                                         SourceLocation EllipsisLoc,
145                                         SourceLocation KeyLoc,
146                                         IdentifierInfo *ParamName,
147                                         SourceLocation ParamNameLoc,
148                                         unsigned Depth, unsigned Position) {
149  assert(S->isTemplateParamScope() &&
150	 "Template type parameter not in template parameter scope!");
151  bool Invalid = false;
152
153  if (ParamName) {
154    NamedDecl *PrevDecl = LookupName(S, ParamName, LookupTagName);
155    if (PrevDecl && PrevDecl->isTemplateParameter())
156      Invalid = Invalid || DiagnoseTemplateParameterShadow(ParamNameLoc,
157							   PrevDecl);
158  }
159
160  SourceLocation Loc = ParamNameLoc;
161  if (!ParamName)
162    Loc = KeyLoc;
163
164  TemplateTypeParmDecl *Param
165    = TemplateTypeParmDecl::Create(Context, CurContext, Loc,
166                                   Depth, Position, ParamName, Typename);
167  if (Invalid)
168    Param->setInvalidDecl();
169
170  if (ParamName) {
171    // Add the template parameter into the current scope.
172    S->AddDecl(DeclPtrTy::make(Param));
173    IdResolver.AddDecl(Param);
174  }
175
176  return DeclPtrTy::make(Param);
177}
178
179/// ActOnTypeParameterDefault - Adds a default argument (the type
180/// Default) to the given template type parameter (TypeParam).
181void Sema::ActOnTypeParameterDefault(DeclPtrTy TypeParam,
182                                     SourceLocation EqualLoc,
183                                     SourceLocation DefaultLoc,
184                                     TypeTy *DefaultT) {
185  TemplateTypeParmDecl *Parm
186    = cast<TemplateTypeParmDecl>(TypeParam.getAs<Decl>());
187  QualType Default = QualType::getFromOpaquePtr(DefaultT);
188
189  // C++ [temp.param]p14:
190  //   A template-parameter shall not be used in its own default argument.
191  // FIXME: Implement this check! Needs a recursive walk over the types.
192
193  // Check the template argument itself.
194  if (CheckTemplateArgument(Parm, Default, DefaultLoc)) {
195    Parm->setInvalidDecl();
196    return;
197  }
198
199  Parm->setDefaultArgument(Default, DefaultLoc, false);
200}
201
202/// \brief Check that the type of a non-type template parameter is
203/// well-formed.
204///
205/// \returns the (possibly-promoted) parameter type if valid;
206/// otherwise, produces a diagnostic and returns a NULL type.
207QualType
208Sema::CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc) {
209  // C++ [temp.param]p4:
210  //
211  // A non-type template-parameter shall have one of the following
212  // (optionally cv-qualified) types:
213  //
214  //       -- integral or enumeration type,
215  if (T->isIntegralType() || T->isEnumeralType() ||
216      //   -- pointer to object or pointer to function,
217      (T->isPointerType() &&
218       (T->getAsPointerType()->getPointeeType()->isObjectType() ||
219        T->getAsPointerType()->getPointeeType()->isFunctionType())) ||
220      //   -- reference to object or reference to function,
221      T->isReferenceType() ||
222      //   -- pointer to member.
223      T->isMemberPointerType() ||
224      // If T is a dependent type, we can't do the check now, so we
225      // assume that it is well-formed.
226      T->isDependentType())
227    return T;
228  // C++ [temp.param]p8:
229  //
230  //   A non-type template-parameter of type "array of T" or
231  //   "function returning T" is adjusted to be of type "pointer to
232  //   T" or "pointer to function returning T", respectively.
233  else if (T->isArrayType())
234    // FIXME: Keep the type prior to promotion?
235    return Context.getArrayDecayedType(T);
236  else if (T->isFunctionType())
237    // FIXME: Keep the type prior to promotion?
238    return Context.getPointerType(T);
239
240  Diag(Loc, diag::err_template_nontype_parm_bad_type)
241    << T;
242
243  return QualType();
244}
245
246/// ActOnNonTypeTemplateParameter - Called when a C++ non-type
247/// template parameter (e.g., "int Size" in "template<int Size>
248/// class Array") has been parsed. S is the current scope and D is
249/// the parsed declarator.
250Sema::DeclPtrTy Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
251                                                    unsigned Depth,
252                                                    unsigned Position) {
253  QualType T = GetTypeForDeclarator(D, S);
254
255  assert(S->isTemplateParamScope() &&
256         "Non-type template parameter not in template parameter scope!");
257  bool Invalid = false;
258
259  IdentifierInfo *ParamName = D.getIdentifier();
260  if (ParamName) {
261    NamedDecl *PrevDecl = LookupName(S, ParamName, LookupTagName);
262    if (PrevDecl && PrevDecl->isTemplateParameter())
263      Invalid = Invalid || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
264                                                           PrevDecl);
265  }
266
267  T = CheckNonTypeTemplateParameterType(T, D.getIdentifierLoc());
268  if (T.isNull()) {
269    T = Context.IntTy; // Recover with an 'int' type.
270    Invalid = true;
271  }
272
273  NonTypeTemplateParmDecl *Param
274    = NonTypeTemplateParmDecl::Create(Context, CurContext, D.getIdentifierLoc(),
275                                      Depth, Position, ParamName, T);
276  if (Invalid)
277    Param->setInvalidDecl();
278
279  if (D.getIdentifier()) {
280    // Add the template parameter into the current scope.
281    S->AddDecl(DeclPtrTy::make(Param));
282    IdResolver.AddDecl(Param);
283  }
284  return DeclPtrTy::make(Param);
285}
286
287/// \brief Adds a default argument to the given non-type template
288/// parameter.
289void Sema::ActOnNonTypeTemplateParameterDefault(DeclPtrTy TemplateParamD,
290                                                SourceLocation EqualLoc,
291                                                ExprArg DefaultE) {
292  NonTypeTemplateParmDecl *TemplateParm
293    = cast<NonTypeTemplateParmDecl>(TemplateParamD.getAs<Decl>());
294  Expr *Default = static_cast<Expr *>(DefaultE.get());
295
296  // C++ [temp.param]p14:
297  //   A template-parameter shall not be used in its own default argument.
298  // FIXME: Implement this check! Needs a recursive walk over the types.
299
300  // Check the well-formedness of the default template argument.
301  TemplateArgument Converted;
302  if (CheckTemplateArgument(TemplateParm, TemplateParm->getType(), Default,
303                            Converted)) {
304    TemplateParm->setInvalidDecl();
305    return;
306  }
307
308  TemplateParm->setDefaultArgument(DefaultE.takeAs<Expr>());
309}
310
311
312/// ActOnTemplateTemplateParameter - Called when a C++ template template
313/// parameter (e.g. T in template <template <typename> class T> class array)
314/// has been parsed. S is the current scope.
315Sema::DeclPtrTy Sema::ActOnTemplateTemplateParameter(Scope* S,
316                                                     SourceLocation TmpLoc,
317                                                     TemplateParamsTy *Params,
318                                                     IdentifierInfo *Name,
319                                                     SourceLocation NameLoc,
320                                                     unsigned Depth,
321                                                     unsigned Position)
322{
323  assert(S->isTemplateParamScope() &&
324         "Template template parameter not in template parameter scope!");
325
326  // Construct the parameter object.
327  TemplateTemplateParmDecl *Param =
328    TemplateTemplateParmDecl::Create(Context, CurContext, TmpLoc, Depth,
329                                     Position, Name,
330                                     (TemplateParameterList*)Params);
331
332  // Make sure the parameter is valid.
333  // FIXME: Decl object is not currently invalidated anywhere so this doesn't
334  // do anything yet. However, if the template parameter list or (eventual)
335  // default value is ever invalidated, that will propagate here.
336  bool Invalid = false;
337  if (Invalid) {
338    Param->setInvalidDecl();
339  }
340
341  // If the tt-param has a name, then link the identifier into the scope
342  // and lookup mechanisms.
343  if (Name) {
344    S->AddDecl(DeclPtrTy::make(Param));
345    IdResolver.AddDecl(Param);
346  }
347
348  return DeclPtrTy::make(Param);
349}
350
351/// \brief Adds a default argument to the given template template
352/// parameter.
353void Sema::ActOnTemplateTemplateParameterDefault(DeclPtrTy TemplateParamD,
354                                                 SourceLocation EqualLoc,
355                                                 ExprArg DefaultE) {
356  TemplateTemplateParmDecl *TemplateParm
357    = cast<TemplateTemplateParmDecl>(TemplateParamD.getAs<Decl>());
358
359  // Since a template-template parameter's default argument is an
360  // id-expression, it must be a DeclRefExpr.
361  DeclRefExpr *Default
362    = cast<DeclRefExpr>(static_cast<Expr *>(DefaultE.get()));
363
364  // C++ [temp.param]p14:
365  //   A template-parameter shall not be used in its own default argument.
366  // FIXME: Implement this check! Needs a recursive walk over the types.
367
368  // Check the well-formedness of the template argument.
369  if (!isa<TemplateDecl>(Default->getDecl())) {
370    Diag(Default->getSourceRange().getBegin(),
371         diag::err_template_arg_must_be_template)
372      << Default->getSourceRange();
373    TemplateParm->setInvalidDecl();
374    return;
375  }
376  if (CheckTemplateArgument(TemplateParm, Default)) {
377    TemplateParm->setInvalidDecl();
378    return;
379  }
380
381  DefaultE.release();
382  TemplateParm->setDefaultArgument(Default);
383}
384
385/// ActOnTemplateParameterList - Builds a TemplateParameterList that
386/// contains the template parameters in Params/NumParams.
387Sema::TemplateParamsTy *
388Sema::ActOnTemplateParameterList(unsigned Depth,
389                                 SourceLocation ExportLoc,
390                                 SourceLocation TemplateLoc,
391                                 SourceLocation LAngleLoc,
392                                 DeclPtrTy *Params, unsigned NumParams,
393                                 SourceLocation RAngleLoc) {
394  if (ExportLoc.isValid())
395    Diag(ExportLoc, diag::note_template_export_unsupported);
396
397  return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
398                                       (Decl**)Params, NumParams, RAngleLoc);
399}
400
401Sema::DeclResult
402Sema::ActOnClassTemplate(Scope *S, unsigned TagSpec, TagKind TK,
403                         SourceLocation KWLoc, const CXXScopeSpec &SS,
404                         IdentifierInfo *Name, SourceLocation NameLoc,
405                         AttributeList *Attr,
406                         MultiTemplateParamsArg TemplateParameterLists,
407                         AccessSpecifier AS) {
408  assert(TemplateParameterLists.size() > 0 && "No template parameter lists?");
409  assert(TK != TK_Reference && "Can only declare or define class templates");
410  bool Invalid = false;
411
412  // Check that we can declare a template here.
413  if (CheckTemplateDeclScope(S, TemplateParameterLists))
414    return true;
415
416  TagDecl::TagKind Kind;
417  switch (TagSpec) {
418  default: assert(0 && "Unknown tag type!");
419  case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
420  case DeclSpec::TST_union:  Kind = TagDecl::TK_union; break;
421  case DeclSpec::TST_class:  Kind = TagDecl::TK_class; break;
422  }
423
424  // There is no such thing as an unnamed class template.
425  if (!Name) {
426    Diag(KWLoc, diag::err_template_unnamed_class);
427    return true;
428  }
429
430  // Find any previous declaration with this name.
431  LookupResult Previous = LookupParsedName(S, &SS, Name, LookupOrdinaryName,
432                                           true);
433  assert(!Previous.isAmbiguous() && "Ambiguity in class template redecl?");
434  NamedDecl *PrevDecl = 0;
435  if (Previous.begin() != Previous.end())
436    PrevDecl = *Previous.begin();
437
438  DeclContext *SemanticContext = CurContext;
439  if (SS.isNotEmpty() && !SS.isInvalid()) {
440    SemanticContext = computeDeclContext(SS);
441
442    // FIXME: need to match up several levels of template parameter lists here.
443  }
444
445  // FIXME: member templates!
446  TemplateParameterList *TemplateParams
447    = static_cast<TemplateParameterList *>(*TemplateParameterLists.release());
448
449  // If there is a previous declaration with the same name, check
450  // whether this is a valid redeclaration.
451  ClassTemplateDecl *PrevClassTemplate
452    = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
453  if (PrevClassTemplate) {
454    // Ensure that the template parameter lists are compatible.
455    if (!TemplateParameterListsAreEqual(TemplateParams,
456                                   PrevClassTemplate->getTemplateParameters(),
457                                        /*Complain=*/true))
458      return true;
459
460    // C++ [temp.class]p4:
461    //   In a redeclaration, partial specialization, explicit
462    //   specialization or explicit instantiation of a class template,
463    //   the class-key shall agree in kind with the original class
464    //   template declaration (7.1.5.3).
465    RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
466    if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind, KWLoc, *Name)) {
467      Diag(KWLoc, diag::err_use_with_wrong_tag)
468        << Name
469        << CodeModificationHint::CreateReplacement(KWLoc,
470                            PrevRecordDecl->getKindName());
471      Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
472      Kind = PrevRecordDecl->getTagKind();
473    }
474
475    // Check for redefinition of this class template.
476    if (TK == TK_Definition) {
477      if (TagDecl *Def = PrevRecordDecl->getDefinition(Context)) {
478        Diag(NameLoc, diag::err_redefinition) << Name;
479        Diag(Def->getLocation(), diag::note_previous_definition);
480        // FIXME: Would it make sense to try to "forget" the previous
481        // definition, as part of error recovery?
482        return true;
483      }
484    }
485  } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
486    // Maybe we will complain about the shadowed template parameter.
487    DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
488    // Just pretend that we didn't see the previous declaration.
489    PrevDecl = 0;
490  } else if (PrevDecl) {
491    // C++ [temp]p5:
492    //   A class template shall not have the same name as any other
493    //   template, class, function, object, enumeration, enumerator,
494    //   namespace, or type in the same scope (3.3), except as specified
495    //   in (14.5.4).
496    Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
497    Diag(PrevDecl->getLocation(), diag::note_previous_definition);
498    return true;
499  }
500
501  // Check the template parameter list of this declaration, possibly
502  // merging in the template parameter list from the previous class
503  // template declaration.
504  if (CheckTemplateParameterList(TemplateParams,
505            PrevClassTemplate? PrevClassTemplate->getTemplateParameters() : 0))
506    Invalid = true;
507
508  // FIXME: If we had a scope specifier, we better have a previous template
509  // declaration!
510
511  CXXRecordDecl *NewClass =
512    CXXRecordDecl::Create(Context, Kind, SemanticContext, NameLoc, Name,
513                          PrevClassTemplate?
514                            PrevClassTemplate->getTemplatedDecl() : 0,
515                          /*DelayTypeCreation=*/true);
516
517  ClassTemplateDecl *NewTemplate
518    = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
519                                DeclarationName(Name), TemplateParams,
520                                NewClass, PrevClassTemplate);
521  NewClass->setDescribedClassTemplate(NewTemplate);
522
523  // Build the type for the class template declaration now.
524  QualType T =
525    Context.getTypeDeclType(NewClass,
526                            PrevClassTemplate?
527                              PrevClassTemplate->getTemplatedDecl() : 0);
528  assert(T->isDependentType() && "Class template type is not dependent?");
529  (void)T;
530
531  // Set the access specifier.
532  SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
533
534  // Set the lexical context of these templates
535  NewClass->setLexicalDeclContext(CurContext);
536  NewTemplate->setLexicalDeclContext(CurContext);
537
538  if (TK == TK_Definition)
539    NewClass->startDefinition();
540
541  if (Attr)
542    ProcessDeclAttributeList(NewClass, Attr);
543
544  PushOnScopeChains(NewTemplate, S);
545
546  if (Invalid) {
547    NewTemplate->setInvalidDecl();
548    NewClass->setInvalidDecl();
549  }
550  return DeclPtrTy::make(NewTemplate);
551}
552
553/// \brief Checks the validity of a template parameter list, possibly
554/// considering the template parameter list from a previous
555/// declaration.
556///
557/// If an "old" template parameter list is provided, it must be
558/// equivalent (per TemplateParameterListsAreEqual) to the "new"
559/// template parameter list.
560///
561/// \param NewParams Template parameter list for a new template
562/// declaration. This template parameter list will be updated with any
563/// default arguments that are carried through from the previous
564/// template parameter list.
565///
566/// \param OldParams If provided, template parameter list from a
567/// previous declaration of the same template. Default template
568/// arguments will be merged from the old template parameter list to
569/// the new template parameter list.
570///
571/// \returns true if an error occurred, false otherwise.
572bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
573                                      TemplateParameterList *OldParams) {
574  bool Invalid = false;
575
576  // C++ [temp.param]p10:
577  //   The set of default template-arguments available for use with a
578  //   template declaration or definition is obtained by merging the
579  //   default arguments from the definition (if in scope) and all
580  //   declarations in scope in the same way default function
581  //   arguments are (8.3.6).
582  bool SawDefaultArgument = false;
583  SourceLocation PreviousDefaultArgLoc;
584
585  // Dummy initialization to avoid warnings.
586  TemplateParameterList::iterator OldParam = NewParams->end();
587  if (OldParams)
588    OldParam = OldParams->begin();
589
590  for (TemplateParameterList::iterator NewParam = NewParams->begin(),
591                                    NewParamEnd = NewParams->end();
592       NewParam != NewParamEnd; ++NewParam) {
593    // Variables used to diagnose redundant default arguments
594    bool RedundantDefaultArg = false;
595    SourceLocation OldDefaultLoc;
596    SourceLocation NewDefaultLoc;
597
598    // Variables used to diagnose missing default arguments
599    bool MissingDefaultArg = false;
600
601    // Merge default arguments for template type parameters.
602    if (TemplateTypeParmDecl *NewTypeParm
603          = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
604      TemplateTypeParmDecl *OldTypeParm
605          = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : 0;
606
607      if (OldTypeParm && OldTypeParm->hasDefaultArgument() &&
608          NewTypeParm->hasDefaultArgument()) {
609        OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
610        NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
611        SawDefaultArgument = true;
612        RedundantDefaultArg = true;
613        PreviousDefaultArgLoc = NewDefaultLoc;
614      } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
615        // Merge the default argument from the old declaration to the
616        // new declaration.
617        SawDefaultArgument = true;
618        NewTypeParm->setDefaultArgument(OldTypeParm->getDefaultArgument(),
619                                        OldTypeParm->getDefaultArgumentLoc(),
620                                        true);
621        PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
622      } else if (NewTypeParm->hasDefaultArgument()) {
623        SawDefaultArgument = true;
624        PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
625      } else if (SawDefaultArgument)
626        MissingDefaultArg = true;
627    }
628    // Merge default arguments for non-type template parameters
629    else if (NonTypeTemplateParmDecl *NewNonTypeParm
630               = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
631      NonTypeTemplateParmDecl *OldNonTypeParm
632        = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : 0;
633      if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument() &&
634          NewNonTypeParm->hasDefaultArgument()) {
635        OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
636        NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
637        SawDefaultArgument = true;
638        RedundantDefaultArg = true;
639        PreviousDefaultArgLoc = NewDefaultLoc;
640      } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
641        // Merge the default argument from the old declaration to the
642        // new declaration.
643        SawDefaultArgument = true;
644        // FIXME: We need to create a new kind of "default argument"
645        // expression that points to a previous template template
646        // parameter.
647        NewNonTypeParm->setDefaultArgument(
648                                        OldNonTypeParm->getDefaultArgument());
649        PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
650      } else if (NewNonTypeParm->hasDefaultArgument()) {
651        SawDefaultArgument = true;
652        PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
653      } else if (SawDefaultArgument)
654        MissingDefaultArg = true;
655    }
656    // Merge default arguments for template template parameters
657    else {
658      TemplateTemplateParmDecl *NewTemplateParm
659        = cast<TemplateTemplateParmDecl>(*NewParam);
660      TemplateTemplateParmDecl *OldTemplateParm
661        = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : 0;
662      if (OldTemplateParm && OldTemplateParm->hasDefaultArgument() &&
663          NewTemplateParm->hasDefaultArgument()) {
664        OldDefaultLoc = OldTemplateParm->getDefaultArgumentLoc();
665        NewDefaultLoc = NewTemplateParm->getDefaultArgumentLoc();
666        SawDefaultArgument = true;
667        RedundantDefaultArg = true;
668        PreviousDefaultArgLoc = NewDefaultLoc;
669      } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
670        // Merge the default argument from the old declaration to the
671        // new declaration.
672        SawDefaultArgument = true;
673        // FIXME: We need to create a new kind of "default argument" expression
674        // that points to a previous template template parameter.
675        NewTemplateParm->setDefaultArgument(
676                                        OldTemplateParm->getDefaultArgument());
677        PreviousDefaultArgLoc = OldTemplateParm->getDefaultArgumentLoc();
678      } else if (NewTemplateParm->hasDefaultArgument()) {
679        SawDefaultArgument = true;
680        PreviousDefaultArgLoc = NewTemplateParm->getDefaultArgumentLoc();
681      } else if (SawDefaultArgument)
682        MissingDefaultArg = true;
683    }
684
685    if (RedundantDefaultArg) {
686      // C++ [temp.param]p12:
687      //   A template-parameter shall not be given default arguments
688      //   by two different declarations in the same scope.
689      Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
690      Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
691      Invalid = true;
692    } else if (MissingDefaultArg) {
693      // C++ [temp.param]p11:
694      //   If a template-parameter has a default template-argument,
695      //   all subsequent template-parameters shall have a default
696      //   template-argument supplied.
697      Diag((*NewParam)->getLocation(),
698           diag::err_template_param_default_arg_missing);
699      Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
700      Invalid = true;
701    }
702
703    // If we have an old template parameter list that we're merging
704    // in, move on to the next parameter.
705    if (OldParams)
706      ++OldParam;
707  }
708
709  return Invalid;
710}
711
712/// \brief Translates template arguments as provided by the parser
713/// into template arguments used by semantic analysis.
714static void
715translateTemplateArguments(ASTTemplateArgsPtr &TemplateArgsIn,
716                           SourceLocation *TemplateArgLocs,
717                     llvm::SmallVector<TemplateArgument, 16> &TemplateArgs) {
718  TemplateArgs.reserve(TemplateArgsIn.size());
719
720  void **Args = TemplateArgsIn.getArgs();
721  bool *ArgIsType = TemplateArgsIn.getArgIsType();
722  for (unsigned Arg = 0, Last = TemplateArgsIn.size(); Arg != Last; ++Arg) {
723    TemplateArgs.push_back(
724      ArgIsType[Arg]? TemplateArgument(TemplateArgLocs[Arg],
725                                       QualType::getFromOpaquePtr(Args[Arg]))
726                    : TemplateArgument(reinterpret_cast<Expr *>(Args[Arg])));
727  }
728}
729
730/// \brief Build a canonical version of a template argument list.
731///
732/// This function builds a canonical version of the given template
733/// argument list, where each of the template arguments has been
734/// converted into its canonical form. This routine is typically used
735/// to canonicalize a template argument list when the template name
736/// itself is dependent. When the template name refers to an actual
737/// template declaration, Sema::CheckTemplateArgumentList should be
738/// used to check and canonicalize the template arguments.
739///
740/// \param TemplateArgs The incoming template arguments.
741///
742/// \param NumTemplateArgs The number of template arguments in \p
743/// TemplateArgs.
744///
745/// \param Canonical A vector to be filled with the canonical versions
746/// of the template arguments.
747///
748/// \param Context The ASTContext in which the template arguments live.
749static void CanonicalizeTemplateArguments(const TemplateArgument *TemplateArgs,
750                                          unsigned NumTemplateArgs,
751                            llvm::SmallVectorImpl<TemplateArgument> &Canonical,
752                                          ASTContext &Context) {
753  Canonical.reserve(NumTemplateArgs);
754  for (unsigned Idx = 0; Idx < NumTemplateArgs; ++Idx) {
755    switch (TemplateArgs[Idx].getKind()) {
756    case TemplateArgument::Null:
757      assert(false && "Should never see a NULL template argument here");
758      break;
759
760    case TemplateArgument::Expression:
761      // FIXME: Build canonical expression (!)
762      Canonical.push_back(TemplateArgs[Idx]);
763      break;
764
765    case TemplateArgument::Declaration:
766      Canonical.push_back(
767                 TemplateArgument(SourceLocation(),
768                    Context.getCanonicalDecl(TemplateArgs[Idx].getAsDecl())));
769      break;
770
771    case TemplateArgument::Integral:
772      Canonical.push_back(TemplateArgument(SourceLocation(),
773                                           *TemplateArgs[Idx].getAsIntegral(),
774                                        TemplateArgs[Idx].getIntegralType()));
775      break;
776
777    case TemplateArgument::Type: {
778      QualType CanonType
779        = Context.getCanonicalType(TemplateArgs[Idx].getAsType());
780      Canonical.push_back(TemplateArgument(SourceLocation(), CanonType));
781      break;
782    }
783    }
784  }
785}
786
787QualType Sema::CheckTemplateIdType(TemplateName Name,
788                                   SourceLocation TemplateLoc,
789                                   SourceLocation LAngleLoc,
790                                   const TemplateArgument *TemplateArgs,
791                                   unsigned NumTemplateArgs,
792                                   SourceLocation RAngleLoc) {
793  TemplateDecl *Template = Name.getAsTemplateDecl();
794  if (!Template) {
795    // The template name does not resolve to a template, so we just
796    // build a dependent template-id type.
797
798    // Canonicalize the template arguments to build the canonical
799    // template-id type.
800    llvm::SmallVector<TemplateArgument, 16> CanonicalTemplateArgs;
801    CanonicalizeTemplateArguments(TemplateArgs, NumTemplateArgs,
802                                  CanonicalTemplateArgs, Context);
803
804    TemplateName CanonName = Context.getCanonicalTemplateName(Name);
805    QualType CanonType
806      = Context.getTemplateSpecializationType(CanonName,
807                                              &CanonicalTemplateArgs[0],
808                                              CanonicalTemplateArgs.size());
809
810    // Build the dependent template-id type.
811    return Context.getTemplateSpecializationType(Name, TemplateArgs,
812                                                 NumTemplateArgs, CanonType);
813  }
814
815  // Check that the template argument list is well-formed for this
816  // template.
817  TemplateArgumentListBuilder ConvertedTemplateArgs(Context);
818  if (CheckTemplateArgumentList(Template, TemplateLoc, LAngleLoc,
819                                TemplateArgs, NumTemplateArgs, RAngleLoc,
820                                ConvertedTemplateArgs))
821    return QualType();
822
823  assert((ConvertedTemplateArgs.size() ==
824            Template->getTemplateParameters()->size()) &&
825         "Converted template argument list is too short!");
826
827  QualType CanonType;
828
829  if (TemplateSpecializationType::anyDependentTemplateArguments(
830                                                      TemplateArgs,
831                                                      NumTemplateArgs)) {
832    // This class template specialization is a dependent
833    // type. Therefore, its canonical type is another class template
834    // specialization type that contains all of the converted
835    // arguments in canonical form. This ensures that, e.g., A<T> and
836    // A<T, T> have identical types when A is declared as:
837    //
838    //   template<typename T, typename U = T> struct A;
839    TemplateName CanonName = Context.getCanonicalTemplateName(Name);
840    CanonType = Context.getTemplateSpecializationType(CanonName,
841                                    ConvertedTemplateArgs.getFlatArgumentList(),
842                                    ConvertedTemplateArgs.flatSize());
843  } else if (ClassTemplateDecl *ClassTemplate
844               = dyn_cast<ClassTemplateDecl>(Template)) {
845    // Find the class template specialization declaration that
846    // corresponds to these arguments.
847    llvm::FoldingSetNodeID ID;
848    ClassTemplateSpecializationDecl::Profile(ID,
849                                    ConvertedTemplateArgs.getFlatArgumentList(),
850                                    ConvertedTemplateArgs.flatSize());
851    void *InsertPos = 0;
852    ClassTemplateSpecializationDecl *Decl
853      = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
854    if (!Decl) {
855      // This is the first time we have referenced this class template
856      // specialization. Create the canonical declaration and add it to
857      // the set of specializations.
858      Decl = ClassTemplateSpecializationDecl::Create(Context,
859                                    ClassTemplate->getDeclContext(),
860                                    TemplateLoc,
861                                    ClassTemplate,
862                                    ConvertedTemplateArgs, 0);
863      ClassTemplate->getSpecializations().InsertNode(Decl, InsertPos);
864      Decl->setLexicalDeclContext(CurContext);
865    }
866
867    CanonType = Context.getTypeDeclType(Decl);
868  }
869
870  // Build the fully-sugared type for this class template
871  // specialization, which refers back to the class template
872  // specialization we created or found.
873  return Context.getTemplateSpecializationType(Name, TemplateArgs,
874                                               NumTemplateArgs, CanonType);
875}
876
877Action::TypeResult
878Sema::ActOnTemplateIdType(TemplateTy TemplateD, SourceLocation TemplateLoc,
879                          SourceLocation LAngleLoc,
880                          ASTTemplateArgsPtr TemplateArgsIn,
881                          SourceLocation *TemplateArgLocs,
882                          SourceLocation RAngleLoc) {
883  TemplateName Template = TemplateD.getAsVal<TemplateName>();
884
885  // Translate the parser's template argument list in our AST format.
886  llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
887  translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
888
889  QualType Result = CheckTemplateIdType(Template, TemplateLoc, LAngleLoc,
890                                        TemplateArgs.data(),
891                                        TemplateArgs.size(),
892                                        RAngleLoc);
893  TemplateArgsIn.release();
894
895  if (Result.isNull())
896    return true;
897
898  return Result.getAsOpaquePtr();
899}
900
901/// \brief Form a dependent template name.
902///
903/// This action forms a dependent template name given the template
904/// name and its (presumably dependent) scope specifier. For
905/// example, given "MetaFun::template apply", the scope specifier \p
906/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
907/// of the "template" keyword, and "apply" is the \p Name.
908Sema::TemplateTy
909Sema::ActOnDependentTemplateName(SourceLocation TemplateKWLoc,
910                                 const IdentifierInfo &Name,
911                                 SourceLocation NameLoc,
912                                 const CXXScopeSpec &SS) {
913  if (!SS.isSet() || SS.isInvalid())
914    return TemplateTy();
915
916  NestedNameSpecifier *Qualifier
917    = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
918
919  // FIXME: member of the current instantiation
920
921  if (!Qualifier->isDependent()) {
922    // C++0x [temp.names]p5:
923    //   If a name prefixed by the keyword template is not the name of
924    //   a template, the program is ill-formed. [Note: the keyword
925    //   template may not be applied to non-template members of class
926    //   templates. -end note ] [ Note: as is the case with the
927    //   typename prefix, the template prefix is allowed in cases
928    //   where it is not strictly necessary; i.e., when the
929    //   nested-name-specifier or the expression on the left of the ->
930    //   or . is not dependent on a template-parameter, or the use
931    //   does not appear in the scope of a template. -end note]
932    //
933    // Note: C++03 was more strict here, because it banned the use of
934    // the "template" keyword prior to a template-name that was not a
935    // dependent name. C++ DR468 relaxed this requirement (the
936    // "template" keyword is now permitted). We follow the C++0x
937    // rules, even in C++03 mode, retroactively applying the DR.
938    TemplateTy Template;
939    TemplateNameKind TNK = isTemplateName(Name, 0, Template, &SS);
940    if (TNK == TNK_Non_template) {
941      Diag(NameLoc, diag::err_template_kw_refers_to_non_template)
942        << &Name;
943      return TemplateTy();
944    }
945
946    return Template;
947  }
948
949  return TemplateTy::make(Context.getDependentTemplateName(Qualifier, &Name));
950}
951
952/// \brief Check that the given template argument list is well-formed
953/// for specializing the given template.
954bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
955                                     SourceLocation TemplateLoc,
956                                     SourceLocation LAngleLoc,
957                                     const TemplateArgument *TemplateArgs,
958                                     unsigned NumTemplateArgs,
959                                     SourceLocation RAngleLoc,
960                                     TemplateArgumentListBuilder &Converted) {
961  TemplateParameterList *Params = Template->getTemplateParameters();
962  unsigned NumParams = Params->size();
963  unsigned NumArgs = NumTemplateArgs;
964  bool Invalid = false;
965
966  if (NumArgs > NumParams ||
967      NumArgs < Params->getMinRequiredArguments()) {
968    // FIXME: point at either the first arg beyond what we can handle,
969    // or the '>', depending on whether we have too many or too few
970    // arguments.
971    SourceRange Range;
972    if (NumArgs > NumParams)
973      Range = SourceRange(TemplateArgs[NumParams].getLocation(), RAngleLoc);
974    Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
975      << (NumArgs > NumParams)
976      << (isa<ClassTemplateDecl>(Template)? 0 :
977          isa<FunctionTemplateDecl>(Template)? 1 :
978          isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
979      << Template << Range;
980    Diag(Template->getLocation(), diag::note_template_decl_here)
981      << Params->getSourceRange();
982    Invalid = true;
983  }
984
985  // C++ [temp.arg]p1:
986  //   [...] The type and form of each template-argument specified in
987  //   a template-id shall match the type and form specified for the
988  //   corresponding parameter declared by the template in its
989  //   template-parameter-list.
990  unsigned ArgIdx = 0;
991  for (TemplateParameterList::iterator Param = Params->begin(),
992                                       ParamEnd = Params->end();
993       Param != ParamEnd; ++Param, ++ArgIdx) {
994    // Decode the template argument
995    TemplateArgument Arg;
996    if (ArgIdx >= NumArgs) {
997      // Retrieve the default template argument from the template
998      // parameter.
999      if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
1000        if (!TTP->hasDefaultArgument())
1001          break;
1002
1003        QualType ArgType = TTP->getDefaultArgument();
1004
1005        // If the argument type is dependent, instantiate it now based
1006        // on the previously-computed template arguments.
1007        if (ArgType->isDependentType()) {
1008          InstantiatingTemplate Inst(*this, TemplateLoc,
1009                                     Template, Converted.getFlatArgumentList(),
1010                                     Converted.flatSize(),
1011                                     SourceRange(TemplateLoc, RAngleLoc));
1012
1013          TemplateArgumentList TemplateArgs(Context, Converted,
1014                                            /*CopyArgs=*/false,
1015                                            /*FlattenArgs=*/false);
1016          ArgType = InstantiateType(ArgType, TemplateArgs,
1017                                    TTP->getDefaultArgumentLoc(),
1018                                    TTP->getDeclName());
1019        }
1020
1021        if (ArgType.isNull())
1022          return true;
1023
1024        Arg = TemplateArgument(TTP->getLocation(), ArgType);
1025      } else if (NonTypeTemplateParmDecl *NTTP
1026                   = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
1027        if (!NTTP->hasDefaultArgument())
1028          break;
1029
1030        InstantiatingTemplate Inst(*this, TemplateLoc,
1031                                   Template, Converted.getFlatArgumentList(),
1032                                   Converted.flatSize(),
1033                                   SourceRange(TemplateLoc, RAngleLoc));
1034
1035        TemplateArgumentList TemplateArgs(Context, Converted,
1036                                          /*CopyArgs=*/false,
1037                                          /*FlattenArgs=*/false);
1038
1039        Sema::OwningExprResult E = InstantiateExpr(NTTP->getDefaultArgument(),
1040                                                   TemplateArgs);
1041        if (E.isInvalid())
1042          return true;
1043
1044        Arg = TemplateArgument(E.takeAs<Expr>());
1045      } else {
1046        TemplateTemplateParmDecl *TempParm
1047          = cast<TemplateTemplateParmDecl>(*Param);
1048
1049        if (!TempParm->hasDefaultArgument())
1050          break;
1051
1052        // FIXME: Instantiate default argument
1053        Arg = TemplateArgument(TempParm->getDefaultArgument());
1054      }
1055    } else {
1056      // Retrieve the template argument produced by the user.
1057      Arg = TemplateArgs[ArgIdx];
1058    }
1059
1060
1061    if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
1062      // Check template type parameters.
1063      if (Arg.getKind() == TemplateArgument::Type) {
1064        if (CheckTemplateArgument(TTP, Arg.getAsType(), Arg.getLocation()))
1065          Invalid = true;
1066
1067        // Add the converted template type argument.
1068        Converted.push_back(
1069                 TemplateArgument(Arg.getLocation(),
1070                                  Context.getCanonicalType(Arg.getAsType())));
1071        continue;
1072      }
1073
1074      // C++ [temp.arg.type]p1:
1075      //   A template-argument for a template-parameter which is a
1076      //   type shall be a type-id.
1077
1078      // We have a template type parameter but the template argument
1079      // is not a type.
1080      Diag(Arg.getLocation(), diag::err_template_arg_must_be_type);
1081      Diag((*Param)->getLocation(), diag::note_template_param_here);
1082      Invalid = true;
1083    } else if (NonTypeTemplateParmDecl *NTTP
1084                 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
1085      // Check non-type template parameters.
1086
1087      // Instantiate the type of the non-type template parameter with
1088      // the template arguments we've seen thus far.
1089      QualType NTTPType = NTTP->getType();
1090      if (NTTPType->isDependentType()) {
1091        // Instantiate the type of the non-type template parameter.
1092        InstantiatingTemplate Inst(*this, TemplateLoc,
1093                                   Template, Converted.getFlatArgumentList(),
1094                                   Converted.flatSize(),
1095                                   SourceRange(TemplateLoc, RAngleLoc));
1096
1097        TemplateArgumentList TemplateArgs(Context, Converted,
1098                                          /*CopyArgs=*/false,
1099                                          /*FlattenArgs=*/false);
1100        NTTPType = InstantiateType(NTTPType, TemplateArgs,
1101                                   NTTP->getLocation(),
1102                                   NTTP->getDeclName());
1103        // If that worked, check the non-type template parameter type
1104        // for validity.
1105        if (!NTTPType.isNull())
1106          NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
1107                                                       NTTP->getLocation());
1108
1109        if (NTTPType.isNull()) {
1110          Invalid = true;
1111          break;
1112        }
1113      }
1114
1115      switch (Arg.getKind()) {
1116      case TemplateArgument::Null:
1117        assert(false && "Should never see a NULL template argument here");
1118        break;
1119
1120      case TemplateArgument::Expression: {
1121        Expr *E = Arg.getAsExpr();
1122        TemplateArgument Result;
1123        if (CheckTemplateArgument(NTTP, NTTPType, E, Result))
1124          Invalid = true;
1125        else
1126          Converted.push_back(Result);
1127        break;
1128      }
1129
1130      case TemplateArgument::Declaration:
1131      case TemplateArgument::Integral:
1132        // We've already checked this template argument, so just copy
1133        // it to the list of converted arguments.
1134        Converted.push_back(Arg);
1135        break;
1136
1137      case TemplateArgument::Type:
1138        // We have a non-type template parameter but the template
1139        // argument is a type.
1140
1141        // C++ [temp.arg]p2:
1142        //   In a template-argument, an ambiguity between a type-id and
1143        //   an expression is resolved to a type-id, regardless of the
1144        //   form of the corresponding template-parameter.
1145        //
1146        // We warn specifically about this case, since it can be rather
1147        // confusing for users.
1148        if (Arg.getAsType()->isFunctionType())
1149          Diag(Arg.getLocation(), diag::err_template_arg_nontype_ambig)
1150            << Arg.getAsType();
1151        else
1152          Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr);
1153        Diag((*Param)->getLocation(), diag::note_template_param_here);
1154        Invalid = true;
1155      }
1156    } else {
1157      // Check template template parameters.
1158      TemplateTemplateParmDecl *TempParm
1159        = cast<TemplateTemplateParmDecl>(*Param);
1160
1161      switch (Arg.getKind()) {
1162      case TemplateArgument::Null:
1163        assert(false && "Should never see a NULL template argument here");
1164        break;
1165
1166      case TemplateArgument::Expression: {
1167        Expr *ArgExpr = Arg.getAsExpr();
1168        if (ArgExpr && isa<DeclRefExpr>(ArgExpr) &&
1169            isa<TemplateDecl>(cast<DeclRefExpr>(ArgExpr)->getDecl())) {
1170          if (CheckTemplateArgument(TempParm, cast<DeclRefExpr>(ArgExpr)))
1171            Invalid = true;
1172
1173          // Add the converted template argument.
1174          Decl *D
1175            = Context.getCanonicalDecl(cast<DeclRefExpr>(ArgExpr)->getDecl());
1176          Converted.push_back(TemplateArgument(Arg.getLocation(), D));
1177          continue;
1178        }
1179      }
1180        // fall through
1181
1182      case TemplateArgument::Type: {
1183        // We have a template template parameter but the template
1184        // argument does not refer to a template.
1185        Diag(Arg.getLocation(), diag::err_template_arg_must_be_template);
1186        Invalid = true;
1187        break;
1188      }
1189
1190      case TemplateArgument::Declaration:
1191        // We've already checked this template argument, so just copy
1192        // it to the list of converted arguments.
1193        Converted.push_back(Arg);
1194        break;
1195
1196      case TemplateArgument::Integral:
1197        assert(false && "Integral argument with template template parameter");
1198        break;
1199      }
1200    }
1201  }
1202
1203  return Invalid;
1204}
1205
1206/// \brief Check a template argument against its corresponding
1207/// template type parameter.
1208///
1209/// This routine implements the semantics of C++ [temp.arg.type]. It
1210/// returns true if an error occurred, and false otherwise.
1211bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
1212                                 QualType Arg, SourceLocation ArgLoc) {
1213  // C++ [temp.arg.type]p2:
1214  //   A local type, a type with no linkage, an unnamed type or a type
1215  //   compounded from any of these types shall not be used as a
1216  //   template-argument for a template type-parameter.
1217  //
1218  // FIXME: Perform the recursive and no-linkage type checks.
1219  const TagType *Tag = 0;
1220  if (const EnumType *EnumT = Arg->getAsEnumType())
1221    Tag = EnumT;
1222  else if (const RecordType *RecordT = Arg->getAsRecordType())
1223    Tag = RecordT;
1224  if (Tag && Tag->getDecl()->getDeclContext()->isFunctionOrMethod())
1225    return Diag(ArgLoc, diag::err_template_arg_local_type)
1226      << QualType(Tag, 0);
1227  else if (Tag && !Tag->getDecl()->getDeclName() &&
1228           !Tag->getDecl()->getTypedefForAnonDecl()) {
1229    Diag(ArgLoc, diag::err_template_arg_unnamed_type);
1230    Diag(Tag->getDecl()->getLocation(), diag::note_template_unnamed_type_here);
1231    return true;
1232  }
1233
1234  return false;
1235}
1236
1237/// \brief Checks whether the given template argument is the address
1238/// of an object or function according to C++ [temp.arg.nontype]p1.
1239bool Sema::CheckTemplateArgumentAddressOfObjectOrFunction(Expr *Arg,
1240                                                          NamedDecl *&Entity) {
1241  bool Invalid = false;
1242
1243  // See through any implicit casts we added to fix the type.
1244  if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
1245    Arg = Cast->getSubExpr();
1246
1247  // C++0x allows nullptr, and there's no further checking to be done for that.
1248  if (Arg->getType()->isNullPtrType())
1249    return false;
1250
1251  // C++ [temp.arg.nontype]p1:
1252  //
1253  //   A template-argument for a non-type, non-template
1254  //   template-parameter shall be one of: [...]
1255  //
1256  //     -- the address of an object or function with external
1257  //        linkage, including function templates and function
1258  //        template-ids but excluding non-static class members,
1259  //        expressed as & id-expression where the & is optional if
1260  //        the name refers to a function or array, or if the
1261  //        corresponding template-parameter is a reference; or
1262  DeclRefExpr *DRE = 0;
1263
1264  // Ignore (and complain about) any excess parentheses.
1265  while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
1266    if (!Invalid) {
1267      Diag(Arg->getSourceRange().getBegin(),
1268           diag::err_template_arg_extra_parens)
1269        << Arg->getSourceRange();
1270      Invalid = true;
1271    }
1272
1273    Arg = Parens->getSubExpr();
1274  }
1275
1276  if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
1277    if (UnOp->getOpcode() == UnaryOperator::AddrOf)
1278      DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
1279  } else
1280    DRE = dyn_cast<DeclRefExpr>(Arg);
1281
1282  if (!DRE || !isa<ValueDecl>(DRE->getDecl()))
1283    return Diag(Arg->getSourceRange().getBegin(),
1284                diag::err_template_arg_not_object_or_func_form)
1285      << Arg->getSourceRange();
1286
1287  // Cannot refer to non-static data members
1288  if (FieldDecl *Field = dyn_cast<FieldDecl>(DRE->getDecl()))
1289    return Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_field)
1290      << Field << Arg->getSourceRange();
1291
1292  // Cannot refer to non-static member functions
1293  if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(DRE->getDecl()))
1294    if (!Method->isStatic())
1295      return Diag(Arg->getSourceRange().getBegin(),
1296                  diag::err_template_arg_method)
1297        << Method << Arg->getSourceRange();
1298
1299  // Functions must have external linkage.
1300  if (FunctionDecl *Func = dyn_cast<FunctionDecl>(DRE->getDecl())) {
1301    if (Func->getStorageClass() == FunctionDecl::Static) {
1302      Diag(Arg->getSourceRange().getBegin(),
1303           diag::err_template_arg_function_not_extern)
1304        << Func << Arg->getSourceRange();
1305      Diag(Func->getLocation(), diag::note_template_arg_internal_object)
1306        << true;
1307      return true;
1308    }
1309
1310    // Okay: we've named a function with external linkage.
1311    Entity = Func;
1312    return Invalid;
1313  }
1314
1315  if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
1316    if (!Var->hasGlobalStorage()) {
1317      Diag(Arg->getSourceRange().getBegin(),
1318           diag::err_template_arg_object_not_extern)
1319        << Var << Arg->getSourceRange();
1320      Diag(Var->getLocation(), diag::note_template_arg_internal_object)
1321        << true;
1322      return true;
1323    }
1324
1325    // Okay: we've named an object with external linkage
1326    Entity = Var;
1327    return Invalid;
1328  }
1329
1330  // We found something else, but we don't know specifically what it is.
1331  Diag(Arg->getSourceRange().getBegin(),
1332       diag::err_template_arg_not_object_or_func)
1333      << Arg->getSourceRange();
1334  Diag(DRE->getDecl()->getLocation(),
1335       diag::note_template_arg_refers_here);
1336  return true;
1337}
1338
1339/// \brief Checks whether the given template argument is a pointer to
1340/// member constant according to C++ [temp.arg.nontype]p1.
1341bool
1342Sema::CheckTemplateArgumentPointerToMember(Expr *Arg, NamedDecl *&Member) {
1343  bool Invalid = false;
1344
1345  // See through any implicit casts we added to fix the type.
1346  if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
1347    Arg = Cast->getSubExpr();
1348
1349  // C++0x allows nullptr, and there's no further checking to be done for that.
1350  if (Arg->getType()->isNullPtrType())
1351    return false;
1352
1353  // C++ [temp.arg.nontype]p1:
1354  //
1355  //   A template-argument for a non-type, non-template
1356  //   template-parameter shall be one of: [...]
1357  //
1358  //     -- a pointer to member expressed as described in 5.3.1.
1359  QualifiedDeclRefExpr *DRE = 0;
1360
1361  // Ignore (and complain about) any excess parentheses.
1362  while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
1363    if (!Invalid) {
1364      Diag(Arg->getSourceRange().getBegin(),
1365           diag::err_template_arg_extra_parens)
1366        << Arg->getSourceRange();
1367      Invalid = true;
1368    }
1369
1370    Arg = Parens->getSubExpr();
1371  }
1372
1373  if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg))
1374    if (UnOp->getOpcode() == UnaryOperator::AddrOf)
1375      DRE = dyn_cast<QualifiedDeclRefExpr>(UnOp->getSubExpr());
1376
1377  if (!DRE)
1378    return Diag(Arg->getSourceRange().getBegin(),
1379                diag::err_template_arg_not_pointer_to_member_form)
1380      << Arg->getSourceRange();
1381
1382  if (isa<FieldDecl>(DRE->getDecl()) || isa<CXXMethodDecl>(DRE->getDecl())) {
1383    assert((isa<FieldDecl>(DRE->getDecl()) ||
1384            !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
1385           "Only non-static member pointers can make it here");
1386
1387    // Okay: this is the address of a non-static member, and therefore
1388    // a member pointer constant.
1389    Member = DRE->getDecl();
1390    return Invalid;
1391  }
1392
1393  // We found something else, but we don't know specifically what it is.
1394  Diag(Arg->getSourceRange().getBegin(),
1395       diag::err_template_arg_not_pointer_to_member_form)
1396      << Arg->getSourceRange();
1397  Diag(DRE->getDecl()->getLocation(),
1398       diag::note_template_arg_refers_here);
1399  return true;
1400}
1401
1402/// \brief Check a template argument against its corresponding
1403/// non-type template parameter.
1404///
1405/// This routine implements the semantics of C++ [temp.arg.nontype].
1406/// It returns true if an error occurred, and false otherwise. \p
1407/// InstantiatedParamType is the type of the non-type template
1408/// parameter after it has been instantiated.
1409///
1410/// If no error was detected, Converted receives the converted template argument.
1411bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
1412                                 QualType InstantiatedParamType, Expr *&Arg,
1413                                 TemplateArgument &Converted) {
1414  SourceLocation StartLoc = Arg->getSourceRange().getBegin();
1415
1416  // If either the parameter has a dependent type or the argument is
1417  // type-dependent, there's nothing we can check now.
1418  // FIXME: Add template argument to Converted!
1419  if (InstantiatedParamType->isDependentType() || Arg->isTypeDependent()) {
1420    // FIXME: Produce a cloned, canonical expression?
1421    Converted = TemplateArgument(Arg);
1422    return false;
1423  }
1424
1425  // C++ [temp.arg.nontype]p5:
1426  //   The following conversions are performed on each expression used
1427  //   as a non-type template-argument. If a non-type
1428  //   template-argument cannot be converted to the type of the
1429  //   corresponding template-parameter then the program is
1430  //   ill-formed.
1431  //
1432  //     -- for a non-type template-parameter of integral or
1433  //        enumeration type, integral promotions (4.5) and integral
1434  //        conversions (4.7) are applied.
1435  QualType ParamType = InstantiatedParamType;
1436  QualType ArgType = Arg->getType();
1437  if (ParamType->isIntegralType() || ParamType->isEnumeralType()) {
1438    // C++ [temp.arg.nontype]p1:
1439    //   A template-argument for a non-type, non-template
1440    //   template-parameter shall be one of:
1441    //
1442    //     -- an integral constant-expression of integral or enumeration
1443    //        type; or
1444    //     -- the name of a non-type template-parameter; or
1445    SourceLocation NonConstantLoc;
1446    llvm::APSInt Value;
1447    if (!ArgType->isIntegralType() && !ArgType->isEnumeralType()) {
1448      Diag(Arg->getSourceRange().getBegin(),
1449           diag::err_template_arg_not_integral_or_enumeral)
1450        << ArgType << Arg->getSourceRange();
1451      Diag(Param->getLocation(), diag::note_template_param_here);
1452      return true;
1453    } else if (!Arg->isValueDependent() &&
1454               !Arg->isIntegerConstantExpr(Value, Context, &NonConstantLoc)) {
1455      Diag(NonConstantLoc, diag::err_template_arg_not_ice)
1456        << ArgType << Arg->getSourceRange();
1457      return true;
1458    }
1459
1460    // FIXME: We need some way to more easily get the unqualified form
1461    // of the types without going all the way to the
1462    // canonical type.
1463    if (Context.getCanonicalType(ParamType).getCVRQualifiers())
1464      ParamType = Context.getCanonicalType(ParamType).getUnqualifiedType();
1465    if (Context.getCanonicalType(ArgType).getCVRQualifiers())
1466      ArgType = Context.getCanonicalType(ArgType).getUnqualifiedType();
1467
1468    // Try to convert the argument to the parameter's type.
1469    if (ParamType == ArgType) {
1470      // Okay: no conversion necessary
1471    } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
1472               !ParamType->isEnumeralType()) {
1473      // This is an integral promotion or conversion.
1474      ImpCastExprToType(Arg, ParamType);
1475    } else {
1476      // We can't perform this conversion.
1477      Diag(Arg->getSourceRange().getBegin(),
1478           diag::err_template_arg_not_convertible)
1479        << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
1480      Diag(Param->getLocation(), diag::note_template_param_here);
1481      return true;
1482    }
1483
1484    QualType IntegerType = Context.getCanonicalType(ParamType);
1485    if (const EnumType *Enum = IntegerType->getAsEnumType())
1486      IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
1487
1488    if (!Arg->isValueDependent()) {
1489      // Check that an unsigned parameter does not receive a negative
1490      // value.
1491      if (IntegerType->isUnsignedIntegerType()
1492          && (Value.isSigned() && Value.isNegative())) {
1493        Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_negative)
1494          << Value.toString(10) << Param->getType()
1495          << Arg->getSourceRange();
1496        Diag(Param->getLocation(), diag::note_template_param_here);
1497        return true;
1498      }
1499
1500      // Check that we don't overflow the template parameter type.
1501      unsigned AllowedBits = Context.getTypeSize(IntegerType);
1502      if (Value.getActiveBits() > AllowedBits) {
1503        Diag(Arg->getSourceRange().getBegin(),
1504             diag::err_template_arg_too_large)
1505          << Value.toString(10) << Param->getType()
1506          << Arg->getSourceRange();
1507        Diag(Param->getLocation(), diag::note_template_param_here);
1508        return true;
1509      }
1510
1511      if (Value.getBitWidth() != AllowedBits)
1512        Value.extOrTrunc(AllowedBits);
1513      Value.setIsSigned(IntegerType->isSignedIntegerType());
1514    }
1515
1516    // Add the value of this argument to the list of converted
1517    // arguments. We use the bitwidth and signedness of the template
1518    // parameter.
1519    if (Arg->isValueDependent()) {
1520      // The argument is value-dependent. Create a new
1521      // TemplateArgument with the converted expression.
1522      Converted = TemplateArgument(Arg);
1523      return false;
1524    }
1525
1526    Converted = TemplateArgument(StartLoc, Value,
1527                                 ParamType->isEnumeralType() ? ParamType
1528                                                             : IntegerType);
1529    return false;
1530  }
1531
1532  // Handle pointer-to-function, reference-to-function, and
1533  // pointer-to-member-function all in (roughly) the same way.
1534  if (// -- For a non-type template-parameter of type pointer to
1535      //    function, only the function-to-pointer conversion (4.3) is
1536      //    applied. If the template-argument represents a set of
1537      //    overloaded functions (or a pointer to such), the matching
1538      //    function is selected from the set (13.4).
1539      // In C++0x, any std::nullptr_t value can be converted.
1540      (ParamType->isPointerType() &&
1541       ParamType->getAsPointerType()->getPointeeType()->isFunctionType()) ||
1542      // -- For a non-type template-parameter of type reference to
1543      //    function, no conversions apply. If the template-argument
1544      //    represents a set of overloaded functions, the matching
1545      //    function is selected from the set (13.4).
1546      (ParamType->isReferenceType() &&
1547       ParamType->getAsReferenceType()->getPointeeType()->isFunctionType()) ||
1548      // -- For a non-type template-parameter of type pointer to
1549      //    member function, no conversions apply. If the
1550      //    template-argument represents a set of overloaded member
1551      //    functions, the matching member function is selected from
1552      //    the set (13.4).
1553      // Again, C++0x allows a std::nullptr_t value.
1554      (ParamType->isMemberPointerType() &&
1555       ParamType->getAsMemberPointerType()->getPointeeType()
1556         ->isFunctionType())) {
1557    if (Context.hasSameUnqualifiedType(ArgType,
1558                                       ParamType.getNonReferenceType())) {
1559      // We don't have to do anything: the types already match.
1560    } else if (ArgType->isNullPtrType() && (ParamType->isPointerType() ||
1561                 ParamType->isMemberPointerType())) {
1562      ArgType = ParamType;
1563      ImpCastExprToType(Arg, ParamType);
1564    } else if (ArgType->isFunctionType() && ParamType->isPointerType()) {
1565      ArgType = Context.getPointerType(ArgType);
1566      ImpCastExprToType(Arg, ArgType);
1567    } else if (FunctionDecl *Fn
1568                 = ResolveAddressOfOverloadedFunction(Arg, ParamType, true)) {
1569      if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
1570        return true;
1571
1572      FixOverloadedFunctionReference(Arg, Fn);
1573      ArgType = Arg->getType();
1574      if (ArgType->isFunctionType() && ParamType->isPointerType()) {
1575        ArgType = Context.getPointerType(Arg->getType());
1576        ImpCastExprToType(Arg, ArgType);
1577      }
1578    }
1579
1580    if (!Context.hasSameUnqualifiedType(ArgType,
1581                                        ParamType.getNonReferenceType())) {
1582      // We can't perform this conversion.
1583      Diag(Arg->getSourceRange().getBegin(),
1584           diag::err_template_arg_not_convertible)
1585        << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
1586      Diag(Param->getLocation(), diag::note_template_param_here);
1587      return true;
1588    }
1589
1590    if (ParamType->isMemberPointerType()) {
1591      NamedDecl *Member = 0;
1592      if (CheckTemplateArgumentPointerToMember(Arg, Member))
1593        return true;
1594
1595      Member = cast_or_null<NamedDecl>(Context.getCanonicalDecl(Member));
1596      Converted = TemplateArgument(StartLoc, Member);
1597      return false;
1598    }
1599
1600    NamedDecl *Entity = 0;
1601    if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
1602      return true;
1603
1604    Entity = cast_or_null<NamedDecl>(Context.getCanonicalDecl(Entity));
1605    Converted = TemplateArgument(StartLoc, Entity);
1606    return false;
1607  }
1608
1609  if (ParamType->isPointerType()) {
1610    //   -- for a non-type template-parameter of type pointer to
1611    //      object, qualification conversions (4.4) and the
1612    //      array-to-pointer conversion (4.2) are applied.
1613    // C++0x also allows a value of std::nullptr_t.
1614    assert(ParamType->getAsPointerType()->getPointeeType()->isObjectType() &&
1615           "Only object pointers allowed here");
1616
1617    if (ArgType->isNullPtrType()) {
1618      ArgType = ParamType;
1619      ImpCastExprToType(Arg, ParamType);
1620    } else if (ArgType->isArrayType()) {
1621      ArgType = Context.getArrayDecayedType(ArgType);
1622      ImpCastExprToType(Arg, ArgType);
1623    }
1624
1625    if (IsQualificationConversion(ArgType, ParamType)) {
1626      ArgType = ParamType;
1627      ImpCastExprToType(Arg, ParamType);
1628    }
1629
1630    if (!Context.hasSameUnqualifiedType(ArgType, ParamType)) {
1631      // We can't perform this conversion.
1632      Diag(Arg->getSourceRange().getBegin(),
1633           diag::err_template_arg_not_convertible)
1634        << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
1635      Diag(Param->getLocation(), diag::note_template_param_here);
1636      return true;
1637    }
1638
1639    NamedDecl *Entity = 0;
1640    if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
1641      return true;
1642
1643    Entity = cast_or_null<NamedDecl>(Context.getCanonicalDecl(Entity));
1644    Converted = TemplateArgument(StartLoc, Entity);
1645    return false;
1646  }
1647
1648  if (const ReferenceType *ParamRefType = ParamType->getAsReferenceType()) {
1649    //   -- For a non-type template-parameter of type reference to
1650    //      object, no conversions apply. The type referred to by the
1651    //      reference may be more cv-qualified than the (otherwise
1652    //      identical) type of the template-argument. The
1653    //      template-parameter is bound directly to the
1654    //      template-argument, which must be an lvalue.
1655    assert(ParamRefType->getPointeeType()->isObjectType() &&
1656           "Only object references allowed here");
1657
1658    if (!Context.hasSameUnqualifiedType(ParamRefType->getPointeeType(), ArgType)) {
1659      Diag(Arg->getSourceRange().getBegin(),
1660           diag::err_template_arg_no_ref_bind)
1661        << InstantiatedParamType << Arg->getType()
1662        << Arg->getSourceRange();
1663      Diag(Param->getLocation(), diag::note_template_param_here);
1664      return true;
1665    }
1666
1667    unsigned ParamQuals
1668      = Context.getCanonicalType(ParamType).getCVRQualifiers();
1669    unsigned ArgQuals = Context.getCanonicalType(ArgType).getCVRQualifiers();
1670
1671    if ((ParamQuals | ArgQuals) != ParamQuals) {
1672      Diag(Arg->getSourceRange().getBegin(),
1673           diag::err_template_arg_ref_bind_ignores_quals)
1674        << InstantiatedParamType << Arg->getType()
1675        << Arg->getSourceRange();
1676      Diag(Param->getLocation(), diag::note_template_param_here);
1677      return true;
1678    }
1679
1680    NamedDecl *Entity = 0;
1681    if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
1682      return true;
1683
1684    Entity = cast<NamedDecl>(Context.getCanonicalDecl(Entity));
1685    Converted = TemplateArgument(StartLoc, Entity);
1686    return false;
1687  }
1688
1689  //     -- For a non-type template-parameter of type pointer to data
1690  //        member, qualification conversions (4.4) are applied.
1691  // C++0x allows std::nullptr_t values.
1692  assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
1693
1694  if (Context.hasSameUnqualifiedType(ParamType, ArgType)) {
1695    // Types match exactly: nothing more to do here.
1696  } else if (ArgType->isNullPtrType()) {
1697    ImpCastExprToType(Arg, ParamType);
1698  } else if (IsQualificationConversion(ArgType, ParamType)) {
1699    ImpCastExprToType(Arg, ParamType);
1700  } else {
1701    // We can't perform this conversion.
1702    Diag(Arg->getSourceRange().getBegin(),
1703         diag::err_template_arg_not_convertible)
1704      << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
1705    Diag(Param->getLocation(), diag::note_template_param_here);
1706    return true;
1707  }
1708
1709  NamedDecl *Member = 0;
1710  if (CheckTemplateArgumentPointerToMember(Arg, Member))
1711    return true;
1712
1713  Member = cast_or_null<NamedDecl>(Context.getCanonicalDecl(Member));
1714  Converted = TemplateArgument(StartLoc, Member);
1715  return false;
1716}
1717
1718/// \brief Check a template argument against its corresponding
1719/// template template parameter.
1720///
1721/// This routine implements the semantics of C++ [temp.arg.template].
1722/// It returns true if an error occurred, and false otherwise.
1723bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
1724                                 DeclRefExpr *Arg) {
1725  assert(isa<TemplateDecl>(Arg->getDecl()) && "Only template decls allowed");
1726  TemplateDecl *Template = cast<TemplateDecl>(Arg->getDecl());
1727
1728  // C++ [temp.arg.template]p1:
1729  //   A template-argument for a template template-parameter shall be
1730  //   the name of a class template, expressed as id-expression. Only
1731  //   primary class templates are considered when matching the
1732  //   template template argument with the corresponding parameter;
1733  //   partial specializations are not considered even if their
1734  //   parameter lists match that of the template template parameter.
1735  //
1736  // Note that we also allow template template parameters here, which
1737  // will happen when we are dealing with, e.g., class template
1738  // partial specializations.
1739  if (!isa<ClassTemplateDecl>(Template) &&
1740      !isa<TemplateTemplateParmDecl>(Template)) {
1741    assert(isa<FunctionTemplateDecl>(Template) &&
1742           "Only function templates are possible here");
1743    Diag(Arg->getSourceRange().getBegin(),
1744         diag::note_template_arg_refers_here_func)
1745      << Template;
1746  }
1747
1748  return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
1749                                         Param->getTemplateParameters(),
1750                                         true, true,
1751                                         Arg->getSourceRange().getBegin());
1752}
1753
1754/// \brief Determine whether the given template parameter lists are
1755/// equivalent.
1756///
1757/// \param New  The new template parameter list, typically written in the
1758/// source code as part of a new template declaration.
1759///
1760/// \param Old  The old template parameter list, typically found via
1761/// name lookup of the template declared with this template parameter
1762/// list.
1763///
1764/// \param Complain  If true, this routine will produce a diagnostic if
1765/// the template parameter lists are not equivalent.
1766///
1767/// \param IsTemplateTemplateParm  If true, this routine is being
1768/// called to compare the template parameter lists of a template
1769/// template parameter.
1770///
1771/// \param TemplateArgLoc If this source location is valid, then we
1772/// are actually checking the template parameter list of a template
1773/// argument (New) against the template parameter list of its
1774/// corresponding template template parameter (Old). We produce
1775/// slightly different diagnostics in this scenario.
1776///
1777/// \returns True if the template parameter lists are equal, false
1778/// otherwise.
1779bool
1780Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
1781                                     TemplateParameterList *Old,
1782                                     bool Complain,
1783                                     bool IsTemplateTemplateParm,
1784                                     SourceLocation TemplateArgLoc) {
1785  if (Old->size() != New->size()) {
1786    if (Complain) {
1787      unsigned NextDiag = diag::err_template_param_list_different_arity;
1788      if (TemplateArgLoc.isValid()) {
1789        Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
1790        NextDiag = diag::note_template_param_list_different_arity;
1791      }
1792      Diag(New->getTemplateLoc(), NextDiag)
1793          << (New->size() > Old->size())
1794          << IsTemplateTemplateParm
1795          << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
1796      Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
1797        << IsTemplateTemplateParm
1798        << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
1799    }
1800
1801    return false;
1802  }
1803
1804  for (TemplateParameterList::iterator OldParm = Old->begin(),
1805         OldParmEnd = Old->end(), NewParm = New->begin();
1806       OldParm != OldParmEnd; ++OldParm, ++NewParm) {
1807    if ((*OldParm)->getKind() != (*NewParm)->getKind()) {
1808      unsigned NextDiag = diag::err_template_param_different_kind;
1809      if (TemplateArgLoc.isValid()) {
1810        Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
1811        NextDiag = diag::note_template_param_different_kind;
1812      }
1813      Diag((*NewParm)->getLocation(), NextDiag)
1814        << IsTemplateTemplateParm;
1815      Diag((*OldParm)->getLocation(), diag::note_template_prev_declaration)
1816        << IsTemplateTemplateParm;
1817      return false;
1818    }
1819
1820    if (isa<TemplateTypeParmDecl>(*OldParm)) {
1821      // Okay; all template type parameters are equivalent (since we
1822      // know we're at the same index).
1823#if 0
1824      // FIXME: Enable this code in debug mode *after* we properly go through
1825      // and "instantiate" the template parameter lists of template template
1826      // parameters. It's only after this instantiation that (1) any dependent
1827      // types within the template parameter list of the template template
1828      // parameter can be checked, and (2) the template type parameter depths
1829      // will match up.
1830      QualType OldParmType
1831        = Context.getTypeDeclType(cast<TemplateTypeParmDecl>(*OldParm));
1832      QualType NewParmType
1833        = Context.getTypeDeclType(cast<TemplateTypeParmDecl>(*NewParm));
1834      assert(Context.getCanonicalType(OldParmType) ==
1835             Context.getCanonicalType(NewParmType) &&
1836             "type parameter mismatch?");
1837#endif
1838    } else if (NonTypeTemplateParmDecl *OldNTTP
1839                 = dyn_cast<NonTypeTemplateParmDecl>(*OldParm)) {
1840      // The types of non-type template parameters must agree.
1841      NonTypeTemplateParmDecl *NewNTTP
1842        = cast<NonTypeTemplateParmDecl>(*NewParm);
1843      if (Context.getCanonicalType(OldNTTP->getType()) !=
1844            Context.getCanonicalType(NewNTTP->getType())) {
1845        if (Complain) {
1846          unsigned NextDiag = diag::err_template_nontype_parm_different_type;
1847          if (TemplateArgLoc.isValid()) {
1848            Diag(TemplateArgLoc,
1849                 diag::err_template_arg_template_params_mismatch);
1850            NextDiag = diag::note_template_nontype_parm_different_type;
1851          }
1852          Diag(NewNTTP->getLocation(), NextDiag)
1853            << NewNTTP->getType()
1854            << IsTemplateTemplateParm;
1855          Diag(OldNTTP->getLocation(),
1856               diag::note_template_nontype_parm_prev_declaration)
1857            << OldNTTP->getType();
1858        }
1859        return false;
1860      }
1861    } else {
1862      // The template parameter lists of template template
1863      // parameters must agree.
1864      // FIXME: Could we perform a faster "type" comparison here?
1865      assert(isa<TemplateTemplateParmDecl>(*OldParm) &&
1866             "Only template template parameters handled here");
1867      TemplateTemplateParmDecl *OldTTP
1868        = cast<TemplateTemplateParmDecl>(*OldParm);
1869      TemplateTemplateParmDecl *NewTTP
1870        = cast<TemplateTemplateParmDecl>(*NewParm);
1871      if (!TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
1872                                          OldTTP->getTemplateParameters(),
1873                                          Complain,
1874                                          /*IsTemplateTemplateParm=*/true,
1875                                          TemplateArgLoc))
1876        return false;
1877    }
1878  }
1879
1880  return true;
1881}
1882
1883/// \brief Check whether a template can be declared within this scope.
1884///
1885/// If the template declaration is valid in this scope, returns
1886/// false. Otherwise, issues a diagnostic and returns true.
1887bool
1888Sema::CheckTemplateDeclScope(Scope *S,
1889                             MultiTemplateParamsArg &TemplateParameterLists) {
1890  assert(TemplateParameterLists.size() > 0 && "Not a template");
1891
1892  // Find the nearest enclosing declaration scope.
1893  while ((S->getFlags() & Scope::DeclScope) == 0 ||
1894         (S->getFlags() & Scope::TemplateParamScope) != 0)
1895    S = S->getParent();
1896
1897  TemplateParameterList *TemplateParams =
1898    static_cast<TemplateParameterList*>(*TemplateParameterLists.get());
1899  SourceLocation TemplateLoc = TemplateParams->getTemplateLoc();
1900  SourceRange TemplateRange
1901    = SourceRange(TemplateLoc, TemplateParams->getRAngleLoc());
1902
1903  // C++ [temp]p2:
1904  //   A template-declaration can appear only as a namespace scope or
1905  //   class scope declaration.
1906  DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
1907  while (Ctx && isa<LinkageSpecDecl>(Ctx)) {
1908    if (cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx)
1909      return Diag(TemplateLoc, diag::err_template_linkage)
1910        << TemplateRange;
1911
1912    Ctx = Ctx->getParent();
1913  }
1914
1915  if (Ctx && (Ctx->isFileContext() || Ctx->isRecord()))
1916    return false;
1917
1918  return Diag(TemplateLoc, diag::err_template_outside_namespace_or_class_scope)
1919    << TemplateRange;
1920}
1921
1922/// \brief Check whether a class template specialization or explicit
1923/// instantiation in the current context is well-formed.
1924///
1925/// This routine determines whether a class template specialization or
1926/// explicit instantiation can be declared in the current context
1927/// (C++ [temp.expl.spec]p2, C++0x [temp.explicit]p2) and emits
1928/// appropriate diagnostics if there was an error. It returns true if
1929// there was an error that we cannot recover from, and false otherwise.
1930bool
1931Sema::CheckClassTemplateSpecializationScope(ClassTemplateDecl *ClassTemplate,
1932                                   ClassTemplateSpecializationDecl *PrevDecl,
1933                                            SourceLocation TemplateNameLoc,
1934                                            SourceRange ScopeSpecifierRange,
1935                                            bool PartialSpecialization,
1936                                            bool ExplicitInstantiation) {
1937  // C++ [temp.expl.spec]p2:
1938  //   An explicit specialization shall be declared in the namespace
1939  //   of which the template is a member, or, for member templates, in
1940  //   the namespace of which the enclosing class or enclosing class
1941  //   template is a member. An explicit specialization of a member
1942  //   function, member class or static data member of a class
1943  //   template shall be declared in the namespace of which the class
1944  //   template is a member. Such a declaration may also be a
1945  //   definition. If the declaration is not a definition, the
1946  //   specialization may be defined later in the name- space in which
1947  //   the explicit specialization was declared, or in a namespace
1948  //   that encloses the one in which the explicit specialization was
1949  //   declared.
1950  if (CurContext->getLookupContext()->isFunctionOrMethod()) {
1951    int Kind = ExplicitInstantiation? 2 : PartialSpecialization? 1 : 0;
1952    Diag(TemplateNameLoc, diag::err_template_spec_decl_function_scope)
1953      << Kind << ClassTemplate;
1954    return true;
1955  }
1956
1957  DeclContext *DC = CurContext->getEnclosingNamespaceContext();
1958  DeclContext *TemplateContext
1959    = ClassTemplate->getDeclContext()->getEnclosingNamespaceContext();
1960  if ((!PrevDecl || PrevDecl->getSpecializationKind() == TSK_Undeclared) &&
1961      !ExplicitInstantiation) {
1962    // There is no prior declaration of this entity, so this
1963    // specialization must be in the same context as the template
1964    // itself.
1965    if (DC != TemplateContext) {
1966      if (isa<TranslationUnitDecl>(TemplateContext))
1967        Diag(TemplateNameLoc, diag::err_template_spec_decl_out_of_scope_global)
1968          << PartialSpecialization
1969          << ClassTemplate << ScopeSpecifierRange;
1970      else if (isa<NamespaceDecl>(TemplateContext))
1971        Diag(TemplateNameLoc, diag::err_template_spec_decl_out_of_scope)
1972          << PartialSpecialization << ClassTemplate
1973          << cast<NamedDecl>(TemplateContext) << ScopeSpecifierRange;
1974
1975      Diag(ClassTemplate->getLocation(), diag::note_template_decl_here);
1976    }
1977
1978    return false;
1979  }
1980
1981  // We have a previous declaration of this entity. Make sure that
1982  // this redeclaration (or definition) occurs in an enclosing namespace.
1983  if (!CurContext->Encloses(TemplateContext)) {
1984    // FIXME:  In C++98,  we  would like  to  turn these  errors into  warnings,
1985    // dependent on a -Wc++0x flag.
1986    bool SuppressedDiag = false;
1987    int Kind = ExplicitInstantiation? 2 : PartialSpecialization? 1 : 0;
1988    if (isa<TranslationUnitDecl>(TemplateContext)) {
1989      if (!ExplicitInstantiation || getLangOptions().CPlusPlus0x)
1990        Diag(TemplateNameLoc, diag::err_template_spec_redecl_global_scope)
1991          << Kind << ClassTemplate << ScopeSpecifierRange;
1992      else
1993        SuppressedDiag = true;
1994    } else if (isa<NamespaceDecl>(TemplateContext)) {
1995      if (!ExplicitInstantiation || getLangOptions().CPlusPlus0x)
1996        Diag(TemplateNameLoc, diag::err_template_spec_redecl_out_of_scope)
1997          << Kind << ClassTemplate
1998          << cast<NamedDecl>(TemplateContext) << ScopeSpecifierRange;
1999      else
2000        SuppressedDiag = true;
2001    }
2002
2003    if (!SuppressedDiag)
2004      Diag(ClassTemplate->getLocation(), diag::note_template_decl_here);
2005  }
2006
2007  return false;
2008}
2009
2010/// \brief Check the non-type template arguments of a class template
2011/// partial specialization according to C++ [temp.class.spec]p9.
2012///
2013/// \param TemplateParams the template parameters of the primary class
2014/// template.
2015///
2016/// \param TemplateArg the template arguments of the class template
2017/// partial specialization.
2018///
2019/// \param MirrorsPrimaryTemplate will be set true if the class
2020/// template partial specialization arguments are identical to the
2021/// implicit template arguments of the primary template. This is not
2022/// necessarily an error (C++0x), and it is left to the caller to diagnose
2023/// this condition when it is an error.
2024///
2025/// \returns true if there was an error, false otherwise.
2026bool Sema::CheckClassTemplatePartialSpecializationArgs(
2027                                        TemplateParameterList *TemplateParams,
2028                                        const TemplateArgument *TemplateArgs,
2029                                        bool &MirrorsPrimaryTemplate) {
2030  // FIXME: the interface to this function will have to change to
2031  // accommodate variadic templates.
2032  MirrorsPrimaryTemplate = true;
2033  for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
2034    // Determine whether the template argument list of the partial
2035    // specialization is identical to the implicit argument list of
2036    // the primary template. The caller may need to diagnostic this as
2037    // an error per C++ [temp.class.spec]p9b3.
2038    if (MirrorsPrimaryTemplate) {
2039      if (TemplateTypeParmDecl *TTP
2040            = dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(I))) {
2041        if (Context.getCanonicalType(Context.getTypeDeclType(TTP)) !=
2042              Context.getCanonicalType(TemplateArgs[I].getAsType()))
2043          MirrorsPrimaryTemplate = false;
2044      } else if (TemplateTemplateParmDecl *TTP
2045                   = dyn_cast<TemplateTemplateParmDecl>(
2046                                                 TemplateParams->getParam(I))) {
2047        // FIXME: We should settle on either Declaration storage or
2048        // Expression storage for template template parameters.
2049        TemplateTemplateParmDecl *ArgDecl
2050          = dyn_cast_or_null<TemplateTemplateParmDecl>(
2051                                                  TemplateArgs[I].getAsDecl());
2052        if (!ArgDecl)
2053          if (DeclRefExpr *DRE
2054                = dyn_cast_or_null<DeclRefExpr>(TemplateArgs[I].getAsExpr()))
2055            ArgDecl = dyn_cast<TemplateTemplateParmDecl>(DRE->getDecl());
2056
2057        if (!ArgDecl ||
2058            ArgDecl->getIndex() != TTP->getIndex() ||
2059            ArgDecl->getDepth() != TTP->getDepth())
2060          MirrorsPrimaryTemplate = false;
2061      }
2062    }
2063
2064    NonTypeTemplateParmDecl *Param
2065      = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
2066    if (!Param) {
2067      continue;
2068    }
2069
2070    Expr *ArgExpr = TemplateArgs[I].getAsExpr();
2071    if (!ArgExpr) {
2072      MirrorsPrimaryTemplate = false;
2073      continue;
2074    }
2075
2076    // C++ [temp.class.spec]p8:
2077    //   A non-type argument is non-specialized if it is the name of a
2078    //   non-type parameter. All other non-type arguments are
2079    //   specialized.
2080    //
2081    // Below, we check the two conditions that only apply to
2082    // specialized non-type arguments, so skip any non-specialized
2083    // arguments.
2084    if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
2085      if (NonTypeTemplateParmDecl *NTTP
2086            = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl())) {
2087        if (MirrorsPrimaryTemplate &&
2088            (Param->getIndex() != NTTP->getIndex() ||
2089             Param->getDepth() != NTTP->getDepth()))
2090          MirrorsPrimaryTemplate = false;
2091
2092        continue;
2093      }
2094
2095    // C++ [temp.class.spec]p9:
2096    //   Within the argument list of a class template partial
2097    //   specialization, the following restrictions apply:
2098    //     -- A partially specialized non-type argument expression
2099    //        shall not involve a template parameter of the partial
2100    //        specialization except when the argument expression is a
2101    //        simple identifier.
2102    if (ArgExpr->isTypeDependent() || ArgExpr->isValueDependent()) {
2103      Diag(ArgExpr->getLocStart(),
2104           diag::err_dependent_non_type_arg_in_partial_spec)
2105        << ArgExpr->getSourceRange();
2106      return true;
2107    }
2108
2109    //     -- The type of a template parameter corresponding to a
2110    //        specialized non-type argument shall not be dependent on a
2111    //        parameter of the specialization.
2112    if (Param->getType()->isDependentType()) {
2113      Diag(ArgExpr->getLocStart(),
2114           diag::err_dependent_typed_non_type_arg_in_partial_spec)
2115        << Param->getType()
2116        << ArgExpr->getSourceRange();
2117      Diag(Param->getLocation(), diag::note_template_param_here);
2118      return true;
2119    }
2120
2121    MirrorsPrimaryTemplate = false;
2122  }
2123
2124  return false;
2125}
2126
2127Sema::DeclResult
2128Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec, TagKind TK,
2129                                       SourceLocation KWLoc,
2130                                       const CXXScopeSpec &SS,
2131                                       TemplateTy TemplateD,
2132                                       SourceLocation TemplateNameLoc,
2133                                       SourceLocation LAngleLoc,
2134                                       ASTTemplateArgsPtr TemplateArgsIn,
2135                                       SourceLocation *TemplateArgLocs,
2136                                       SourceLocation RAngleLoc,
2137                                       AttributeList *Attr,
2138                               MultiTemplateParamsArg TemplateParameterLists) {
2139  // Find the class template we're specializing
2140  TemplateName Name = TemplateD.getAsVal<TemplateName>();
2141  ClassTemplateDecl *ClassTemplate
2142    = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
2143
2144  bool isPartialSpecialization = false;
2145
2146  // Check the validity of the template headers that introduce this
2147  // template.
2148  // FIXME: Once we have member templates, we'll need to check
2149  // C++ [temp.expl.spec]p17-18, where we could have multiple levels of
2150  // template<> headers.
2151  if (TemplateParameterLists.size() == 0)
2152    Diag(KWLoc, diag::err_template_spec_needs_header)
2153      << CodeModificationHint::CreateInsertion(KWLoc, "template<> ");
2154  else {
2155    TemplateParameterList *TemplateParams
2156      = static_cast<TemplateParameterList*>(*TemplateParameterLists.get());
2157    if (TemplateParameterLists.size() > 1) {
2158      Diag(TemplateParams->getTemplateLoc(),
2159           diag::err_template_spec_extra_headers);
2160      return true;
2161    }
2162
2163    if (TemplateParams->size() > 0) {
2164      isPartialSpecialization = true;
2165
2166      // C++ [temp.class.spec]p10:
2167      //   The template parameter list of a specialization shall not
2168      //   contain default template argument values.
2169      for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
2170        Decl *Param = TemplateParams->getParam(I);
2171        if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
2172          if (TTP->hasDefaultArgument()) {
2173            Diag(TTP->getDefaultArgumentLoc(),
2174                 diag::err_default_arg_in_partial_spec);
2175            TTP->setDefaultArgument(QualType(), SourceLocation(), false);
2176          }
2177        } else if (NonTypeTemplateParmDecl *NTTP
2178                     = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
2179          if (Expr *DefArg = NTTP->getDefaultArgument()) {
2180            Diag(NTTP->getDefaultArgumentLoc(),
2181                 diag::err_default_arg_in_partial_spec)
2182              << DefArg->getSourceRange();
2183            NTTP->setDefaultArgument(0);
2184            DefArg->Destroy(Context);
2185          }
2186        } else {
2187          TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
2188          if (Expr *DefArg = TTP->getDefaultArgument()) {
2189            Diag(TTP->getDefaultArgumentLoc(),
2190                 diag::err_default_arg_in_partial_spec)
2191              << DefArg->getSourceRange();
2192            TTP->setDefaultArgument(0);
2193            DefArg->Destroy(Context);
2194          }
2195        }
2196      }
2197    }
2198  }
2199
2200  // Check that the specialization uses the same tag kind as the
2201  // original template.
2202  TagDecl::TagKind Kind;
2203  switch (TagSpec) {
2204  default: assert(0 && "Unknown tag type!");
2205  case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
2206  case DeclSpec::TST_union:  Kind = TagDecl::TK_union; break;
2207  case DeclSpec::TST_class:  Kind = TagDecl::TK_class; break;
2208  }
2209  if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
2210                                    Kind, KWLoc,
2211                                    *ClassTemplate->getIdentifier())) {
2212    Diag(KWLoc, diag::err_use_with_wrong_tag)
2213      << ClassTemplate
2214      << CodeModificationHint::CreateReplacement(KWLoc,
2215                            ClassTemplate->getTemplatedDecl()->getKindName());
2216    Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
2217         diag::note_previous_use);
2218    Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
2219  }
2220
2221  // Translate the parser's template argument list in our AST format.
2222  llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
2223  translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
2224
2225  // Check that the template argument list is well-formed for this
2226  // template.
2227  TemplateArgumentListBuilder ConvertedTemplateArgs(Context);
2228  if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, LAngleLoc,
2229                                &TemplateArgs[0], TemplateArgs.size(),
2230                                RAngleLoc, ConvertedTemplateArgs))
2231    return true;
2232
2233  assert((ConvertedTemplateArgs.size() ==
2234            ClassTemplate->getTemplateParameters()->size()) &&
2235         "Converted template argument list is too short!");
2236
2237  // Find the class template (partial) specialization declaration that
2238  // corresponds to these arguments.
2239  llvm::FoldingSetNodeID ID;
2240  if (isPartialSpecialization) {
2241    bool MirrorsPrimaryTemplate;
2242    if (CheckClassTemplatePartialSpecializationArgs(
2243                                         ClassTemplate->getTemplateParameters(),
2244                                    ConvertedTemplateArgs.getFlatArgumentList(),
2245                                         MirrorsPrimaryTemplate))
2246      return true;
2247
2248    if (MirrorsPrimaryTemplate) {
2249      // C++ [temp.class.spec]p9b3:
2250      //
2251      //   -- The argument list of the specialization shall not be identical
2252      //      to the implicit argument list of the primary template.
2253      Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
2254        << (TK == TK_Definition)
2255        << CodeModificationHint::CreateRemoval(SourceRange(LAngleLoc,
2256                                                           RAngleLoc));
2257      return ActOnClassTemplate(S, TagSpec, TK, KWLoc, SS,
2258                                ClassTemplate->getIdentifier(),
2259                                TemplateNameLoc,
2260                                Attr,
2261                                move(TemplateParameterLists),
2262                                AS_none);
2263    }
2264
2265    // FIXME: Template parameter list matters, too
2266    ClassTemplatePartialSpecializationDecl::Profile(ID,
2267                                    ConvertedTemplateArgs.getFlatArgumentList(),
2268                                              ConvertedTemplateArgs.flatSize());
2269  }
2270  else
2271    ClassTemplateSpecializationDecl::Profile(ID,
2272                                    ConvertedTemplateArgs.getFlatArgumentList(),
2273                                             ConvertedTemplateArgs.flatSize());
2274  void *InsertPos = 0;
2275  ClassTemplateSpecializationDecl *PrevDecl = 0;
2276
2277  if (isPartialSpecialization)
2278    PrevDecl
2279      = ClassTemplate->getPartialSpecializations().FindNodeOrInsertPos(ID,
2280                                                                    InsertPos);
2281  else
2282    PrevDecl
2283      = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
2284
2285  ClassTemplateSpecializationDecl *Specialization = 0;
2286
2287  // Check whether we can declare a class template specialization in
2288  // the current scope.
2289  if (CheckClassTemplateSpecializationScope(ClassTemplate, PrevDecl,
2290                                            TemplateNameLoc,
2291                                            SS.getRange(),
2292                                            isPartialSpecialization,
2293                                            /*ExplicitInstantiation=*/false))
2294    return true;
2295
2296  if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
2297    // Since the only prior class template specialization with these
2298    // arguments was referenced but not declared, reuse that
2299    // declaration node as our own, updating its source location to
2300    // reflect our new declaration.
2301    Specialization = PrevDecl;
2302    Specialization->setLocation(TemplateNameLoc);
2303    PrevDecl = 0;
2304  } else if (isPartialSpecialization) {
2305    // FIXME: extra checking for partial specializations
2306
2307    // Create a new class template partial specialization declaration node.
2308    TemplateParameterList *TemplateParams
2309      = static_cast<TemplateParameterList*>(*TemplateParameterLists.get());
2310    ClassTemplatePartialSpecializationDecl *PrevPartial
2311      = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
2312    ClassTemplatePartialSpecializationDecl *Partial
2313      = ClassTemplatePartialSpecializationDecl::Create(Context,
2314                                             ClassTemplate->getDeclContext(),
2315                                                       TemplateNameLoc,
2316                                                       TemplateParams,
2317                                                       ClassTemplate,
2318                                                       ConvertedTemplateArgs,
2319                                                       PrevPartial);
2320
2321    if (PrevPartial) {
2322      ClassTemplate->getPartialSpecializations().RemoveNode(PrevPartial);
2323      ClassTemplate->getPartialSpecializations().GetOrInsertNode(Partial);
2324    } else {
2325      ClassTemplate->getPartialSpecializations().InsertNode(Partial, InsertPos);
2326    }
2327    Specialization = Partial;
2328  } else {
2329    // Create a new class template specialization declaration node for
2330    // this explicit specialization.
2331    Specialization
2332      = ClassTemplateSpecializationDecl::Create(Context,
2333                                             ClassTemplate->getDeclContext(),
2334                                                TemplateNameLoc,
2335                                                ClassTemplate,
2336                                                ConvertedTemplateArgs,
2337                                                PrevDecl);
2338
2339    if (PrevDecl) {
2340      ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
2341      ClassTemplate->getSpecializations().GetOrInsertNode(Specialization);
2342    } else {
2343      ClassTemplate->getSpecializations().InsertNode(Specialization,
2344                                                     InsertPos);
2345    }
2346  }
2347
2348  // Note that this is an explicit specialization.
2349  Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
2350
2351  // Check that this isn't a redefinition of this specialization.
2352  if (TK == TK_Definition) {
2353    if (RecordDecl *Def = Specialization->getDefinition(Context)) {
2354      // FIXME: Should also handle explicit specialization after implicit
2355      // instantiation with a special diagnostic.
2356      SourceRange Range(TemplateNameLoc, RAngleLoc);
2357      Diag(TemplateNameLoc, diag::err_redefinition)
2358        << Context.getTypeDeclType(Specialization) << Range;
2359      Diag(Def->getLocation(), diag::note_previous_definition);
2360      Specialization->setInvalidDecl();
2361      return true;
2362    }
2363  }
2364
2365  // Build the fully-sugared type for this class template
2366  // specialization as the user wrote in the specialization
2367  // itself. This means that we'll pretty-print the type retrieved
2368  // from the specialization's declaration the way that the user
2369  // actually wrote the specialization, rather than formatting the
2370  // name based on the "canonical" representation used to store the
2371  // template arguments in the specialization.
2372  QualType WrittenTy
2373    = Context.getTemplateSpecializationType(Name,
2374                                            &TemplateArgs[0],
2375                                            TemplateArgs.size(),
2376                                  Context.getTypeDeclType(Specialization));
2377  Specialization->setTypeAsWritten(WrittenTy);
2378  TemplateArgsIn.release();
2379
2380  // C++ [temp.expl.spec]p9:
2381  //   A template explicit specialization is in the scope of the
2382  //   namespace in which the template was defined.
2383  //
2384  // We actually implement this paragraph where we set the semantic
2385  // context (in the creation of the ClassTemplateSpecializationDecl),
2386  // but we also maintain the lexical context where the actual
2387  // definition occurs.
2388  Specialization->setLexicalDeclContext(CurContext);
2389
2390  // We may be starting the definition of this specialization.
2391  if (TK == TK_Definition)
2392    Specialization->startDefinition();
2393
2394  // Add the specialization into its lexical context, so that it can
2395  // be seen when iterating through the list of declarations in that
2396  // context. However, specializations are not found by name lookup.
2397  CurContext->addDecl(Context, Specialization);
2398  return DeclPtrTy::make(Specialization);
2399}
2400
2401// Explicit instantiation of a class template specialization
2402Sema::DeclResult
2403Sema::ActOnExplicitInstantiation(Scope *S, SourceLocation TemplateLoc,
2404                                 unsigned TagSpec,
2405                                 SourceLocation KWLoc,
2406                                 const CXXScopeSpec &SS,
2407                                 TemplateTy TemplateD,
2408                                 SourceLocation TemplateNameLoc,
2409                                 SourceLocation LAngleLoc,
2410                                 ASTTemplateArgsPtr TemplateArgsIn,
2411                                 SourceLocation *TemplateArgLocs,
2412                                 SourceLocation RAngleLoc,
2413                                 AttributeList *Attr) {
2414  // Find the class template we're specializing
2415  TemplateName Name = TemplateD.getAsVal<TemplateName>();
2416  ClassTemplateDecl *ClassTemplate
2417    = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
2418
2419  // Check that the specialization uses the same tag kind as the
2420  // original template.
2421  TagDecl::TagKind Kind;
2422  switch (TagSpec) {
2423  default: assert(0 && "Unknown tag type!");
2424  case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
2425  case DeclSpec::TST_union:  Kind = TagDecl::TK_union; break;
2426  case DeclSpec::TST_class:  Kind = TagDecl::TK_class; break;
2427  }
2428  if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
2429                                    Kind, KWLoc,
2430                                    *ClassTemplate->getIdentifier())) {
2431    Diag(KWLoc, diag::err_use_with_wrong_tag)
2432      << ClassTemplate
2433      << CodeModificationHint::CreateReplacement(KWLoc,
2434                            ClassTemplate->getTemplatedDecl()->getKindName());
2435    Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
2436         diag::note_previous_use);
2437    Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
2438  }
2439
2440  // C++0x [temp.explicit]p2:
2441  //   [...] An explicit instantiation shall appear in an enclosing
2442  //   namespace of its template. [...]
2443  //
2444  // This is C++ DR 275.
2445  if (CheckClassTemplateSpecializationScope(ClassTemplate, 0,
2446                                            TemplateNameLoc,
2447                                            SS.getRange(),
2448                                            /*PartialSpecialization=*/false,
2449                                            /*ExplicitInstantiation=*/true))
2450    return true;
2451
2452  // Translate the parser's template argument list in our AST format.
2453  llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
2454  translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
2455
2456  // Check that the template argument list is well-formed for this
2457  // template.
2458  TemplateArgumentListBuilder ConvertedTemplateArgs(Context);
2459  if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, LAngleLoc,
2460                                TemplateArgs.data(), TemplateArgs.size(),
2461                                RAngleLoc, ConvertedTemplateArgs))
2462    return true;
2463
2464  assert((ConvertedTemplateArgs.size() ==
2465            ClassTemplate->getTemplateParameters()->size()) &&
2466         "Converted template argument list is too short!");
2467
2468  // Find the class template specialization declaration that
2469  // corresponds to these arguments.
2470  llvm::FoldingSetNodeID ID;
2471  ClassTemplateSpecializationDecl::Profile(ID,
2472                                    ConvertedTemplateArgs.getFlatArgumentList(),
2473                                           ConvertedTemplateArgs.flatSize());
2474  void *InsertPos = 0;
2475  ClassTemplateSpecializationDecl *PrevDecl
2476    = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
2477
2478  ClassTemplateSpecializationDecl *Specialization = 0;
2479
2480  bool SpecializationRequiresInstantiation = true;
2481  if (PrevDecl) {
2482    if (PrevDecl->getSpecializationKind() == TSK_ExplicitInstantiation) {
2483      // This particular specialization has already been declared or
2484      // instantiated. We cannot explicitly instantiate it.
2485      Diag(TemplateNameLoc, diag::err_explicit_instantiation_duplicate)
2486        << Context.getTypeDeclType(PrevDecl);
2487      Diag(PrevDecl->getLocation(),
2488           diag::note_previous_explicit_instantiation);
2489      return DeclPtrTy::make(PrevDecl);
2490    }
2491
2492    if (PrevDecl->getSpecializationKind() == TSK_ExplicitSpecialization) {
2493      // C++ DR 259, C++0x [temp.explicit]p4:
2494      //   For a given set of template parameters, if an explicit
2495      //   instantiation of a template appears after a declaration of
2496      //   an explicit specialization for that template, the explicit
2497      //   instantiation has no effect.
2498      if (!getLangOptions().CPlusPlus0x) {
2499        Diag(TemplateNameLoc,
2500             diag::ext_explicit_instantiation_after_specialization)
2501          << Context.getTypeDeclType(PrevDecl);
2502        Diag(PrevDecl->getLocation(),
2503             diag::note_previous_template_specialization);
2504      }
2505
2506      // Create a new class template specialization declaration node
2507      // for this explicit specialization. This node is only used to
2508      // record the existence of this explicit instantiation for
2509      // accurate reproduction of the source code; we don't actually
2510      // use it for anything, since it is semantically irrelevant.
2511      Specialization
2512        = ClassTemplateSpecializationDecl::Create(Context,
2513                                             ClassTemplate->getDeclContext(),
2514                                                  TemplateNameLoc,
2515                                                  ClassTemplate,
2516                                                  ConvertedTemplateArgs, 0);
2517      Specialization->setLexicalDeclContext(CurContext);
2518      CurContext->addDecl(Context, Specialization);
2519      return DeclPtrTy::make(Specialization);
2520    }
2521
2522    // If we have already (implicitly) instantiated this
2523    // specialization, there is less work to do.
2524    if (PrevDecl->getSpecializationKind() == TSK_ImplicitInstantiation)
2525      SpecializationRequiresInstantiation = false;
2526
2527    // Since the only prior class template specialization with these
2528    // arguments was referenced but not declared, reuse that
2529    // declaration node as our own, updating its source location to
2530    // reflect our new declaration.
2531    Specialization = PrevDecl;
2532    Specialization->setLocation(TemplateNameLoc);
2533    PrevDecl = 0;
2534  } else {
2535    // Create a new class template specialization declaration node for
2536    // this explicit specialization.
2537    Specialization
2538      = ClassTemplateSpecializationDecl::Create(Context,
2539                                             ClassTemplate->getDeclContext(),
2540                                                TemplateNameLoc,
2541                                                ClassTemplate,
2542                                                ConvertedTemplateArgs, 0);
2543
2544    ClassTemplate->getSpecializations().InsertNode(Specialization,
2545                                                   InsertPos);
2546  }
2547
2548  // Build the fully-sugared type for this explicit instantiation as
2549  // the user wrote in the explicit instantiation itself. This means
2550  // that we'll pretty-print the type retrieved from the
2551  // specialization's declaration the way that the user actually wrote
2552  // the explicit instantiation, rather than formatting the name based
2553  // on the "canonical" representation used to store the template
2554  // arguments in the specialization.
2555  QualType WrittenTy
2556    = Context.getTemplateSpecializationType(Name,
2557                                            TemplateArgs.data(),
2558                                            TemplateArgs.size(),
2559                                  Context.getTypeDeclType(Specialization));
2560  Specialization->setTypeAsWritten(WrittenTy);
2561  TemplateArgsIn.release();
2562
2563  // Add the explicit instantiation into its lexical context. However,
2564  // since explicit instantiations are never found by name lookup, we
2565  // just put it into the declaration context directly.
2566  Specialization->setLexicalDeclContext(CurContext);
2567  CurContext->addDecl(Context, Specialization);
2568
2569  // C++ [temp.explicit]p3:
2570  //   A definition of a class template or class member template
2571  //   shall be in scope at the point of the explicit instantiation of
2572  //   the class template or class member template.
2573  //
2574  // This check comes when we actually try to perform the
2575  // instantiation.
2576  if (SpecializationRequiresInstantiation)
2577    InstantiateClassTemplateSpecialization(Specialization, true);
2578  else // Instantiate the members of this class template specialization.
2579    InstantiateClassTemplateSpecializationMembers(TemplateLoc, Specialization);
2580
2581  return DeclPtrTy::make(Specialization);
2582}
2583
2584// Explicit instantiation of a member class of a class template.
2585Sema::DeclResult
2586Sema::ActOnExplicitInstantiation(Scope *S, SourceLocation TemplateLoc,
2587                                 unsigned TagSpec,
2588                                 SourceLocation KWLoc,
2589                                 const CXXScopeSpec &SS,
2590                                 IdentifierInfo *Name,
2591                                 SourceLocation NameLoc,
2592                                 AttributeList *Attr) {
2593
2594  bool Owned = false;
2595  DeclPtrTy TagD = ActOnTag(S, TagSpec, Action::TK_Reference,
2596                            KWLoc, SS, Name, NameLoc, Attr, AS_none, Owned);
2597  if (!TagD)
2598    return true;
2599
2600  TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>());
2601  if (Tag->isEnum()) {
2602    Diag(TemplateLoc, diag::err_explicit_instantiation_enum)
2603      << Context.getTypeDeclType(Tag);
2604    return true;
2605  }
2606
2607  if (Tag->isInvalidDecl())
2608    return true;
2609
2610  CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
2611  CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
2612  if (!Pattern) {
2613    Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
2614      << Context.getTypeDeclType(Record);
2615    Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
2616    return true;
2617  }
2618
2619  // C++0x [temp.explicit]p2:
2620  //   [...] An explicit instantiation shall appear in an enclosing
2621  //   namespace of its template. [...]
2622  //
2623  // This is C++ DR 275.
2624  if (getLangOptions().CPlusPlus0x) {
2625    // FIXME: In C++98, we would like to turn these errors into warnings,
2626    // dependent on a -Wc++0x flag.
2627    DeclContext *PatternContext
2628      = Pattern->getDeclContext()->getEnclosingNamespaceContext();
2629    if (!CurContext->Encloses(PatternContext)) {
2630      Diag(TemplateLoc, diag::err_explicit_instantiation_out_of_scope)
2631        << Record << cast<NamedDecl>(PatternContext) << SS.getRange();
2632      Diag(Pattern->getLocation(), diag::note_previous_declaration);
2633    }
2634  }
2635
2636  if (!Record->getDefinition(Context)) {
2637    // If the class has a definition, instantiate it (and all of its
2638    // members, recursively).
2639    Pattern = cast_or_null<CXXRecordDecl>(Pattern->getDefinition(Context));
2640    if (Pattern && InstantiateClass(TemplateLoc, Record, Pattern,
2641                                    getTemplateInstantiationArgs(Record),
2642                                    /*ExplicitInstantiation=*/true))
2643      return true;
2644  } else // Instantiate all of the members of class.
2645    InstantiateClassMembers(TemplateLoc, Record,
2646                            getTemplateInstantiationArgs(Record));
2647
2648  // FIXME: We don't have any representation for explicit instantiations of
2649  // member classes. Such a representation is not needed for compilation, but it
2650  // should be available for clients that want to see all of the declarations in
2651  // the source code.
2652  return TagD;
2653}
2654
2655Sema::TypeResult
2656Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
2657                        const IdentifierInfo &II, SourceLocation IdLoc) {
2658  NestedNameSpecifier *NNS
2659    = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
2660  if (!NNS)
2661    return true;
2662
2663  QualType T = CheckTypenameType(NNS, II, SourceRange(TypenameLoc, IdLoc));
2664  if (T.isNull())
2665    return true;
2666  return T.getAsOpaquePtr();
2667}
2668
2669Sema::TypeResult
2670Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
2671                        SourceLocation TemplateLoc, TypeTy *Ty) {
2672  QualType T = QualType::getFromOpaquePtr(Ty);
2673  NestedNameSpecifier *NNS
2674    = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
2675  const TemplateSpecializationType *TemplateId
2676    = T->getAsTemplateSpecializationType();
2677  assert(TemplateId && "Expected a template specialization type");
2678
2679  if (NNS->isDependent())
2680    return Context.getTypenameType(NNS, TemplateId).getAsOpaquePtr();
2681
2682  return Context.getQualifiedNameType(NNS, T).getAsOpaquePtr();
2683}
2684
2685/// \brief Build the type that describes a C++ typename specifier,
2686/// e.g., "typename T::type".
2687QualType
2688Sema::CheckTypenameType(NestedNameSpecifier *NNS, const IdentifierInfo &II,
2689                        SourceRange Range) {
2690  CXXRecordDecl *CurrentInstantiation = 0;
2691  if (NNS->isDependent()) {
2692    CurrentInstantiation = getCurrentInstantiationOf(NNS);
2693
2694    // If the nested-name-specifier does not refer to the current
2695    // instantiation, then build a typename type.
2696    if (!CurrentInstantiation)
2697      return Context.getTypenameType(NNS, &II);
2698  }
2699
2700  DeclContext *Ctx = 0;
2701
2702  if (CurrentInstantiation)
2703    Ctx = CurrentInstantiation;
2704  else {
2705    CXXScopeSpec SS;
2706    SS.setScopeRep(NNS);
2707    SS.setRange(Range);
2708    if (RequireCompleteDeclContext(SS))
2709      return QualType();
2710
2711    Ctx = computeDeclContext(SS);
2712  }
2713  assert(Ctx && "No declaration context?");
2714
2715  DeclarationName Name(&II);
2716  LookupResult Result = LookupQualifiedName(Ctx, Name, LookupOrdinaryName,
2717                                            false);
2718  unsigned DiagID = 0;
2719  Decl *Referenced = 0;
2720  switch (Result.getKind()) {
2721  case LookupResult::NotFound:
2722    if (Ctx->isTranslationUnit())
2723      DiagID = diag::err_typename_nested_not_found_global;
2724    else
2725      DiagID = diag::err_typename_nested_not_found;
2726    break;
2727
2728  case LookupResult::Found:
2729    if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getAsDecl())) {
2730      // We found a type. Build a QualifiedNameType, since the
2731      // typename-specifier was just sugar. FIXME: Tell
2732      // QualifiedNameType that it has a "typename" prefix.
2733      return Context.getQualifiedNameType(NNS, Context.getTypeDeclType(Type));
2734    }
2735
2736    DiagID = diag::err_typename_nested_not_type;
2737    Referenced = Result.getAsDecl();
2738    break;
2739
2740  case LookupResult::FoundOverloaded:
2741    DiagID = diag::err_typename_nested_not_type;
2742    Referenced = *Result.begin();
2743    break;
2744
2745  case LookupResult::AmbiguousBaseSubobjectTypes:
2746  case LookupResult::AmbiguousBaseSubobjects:
2747  case LookupResult::AmbiguousReference:
2748    DiagnoseAmbiguousLookup(Result, Name, Range.getEnd(), Range);
2749    return QualType();
2750  }
2751
2752  // If we get here, it's because name lookup did not find a
2753  // type. Emit an appropriate diagnostic and return an error.
2754  if (NamedDecl *NamedCtx = dyn_cast<NamedDecl>(Ctx))
2755    Diag(Range.getEnd(), DiagID) << Range << Name << NamedCtx;
2756  else
2757    Diag(Range.getEnd(), DiagID) << Range << Name;
2758  if (Referenced)
2759    Diag(Referenced->getLocation(), diag::note_typename_refers_here)
2760      << Name;
2761  return QualType();
2762}
2763