SemaTemplate.cpp revision 5aeccdbb4bdc94e48c04cacc59fa812af32109b2
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(IdentifierInfo &II, Scope *S,
30                                      DeclTy *&Template,
31                                      const CXXScopeSpec *SS) {
32  NamedDecl *IIDecl = LookupParsedName(S, SS, &II, LookupOrdinaryName);
33
34  if (IIDecl) {
35    if (isa<TemplateDecl>(IIDecl)) {
36      Template = IIDecl;
37      if (isa<FunctionTemplateDecl>(IIDecl))
38        return TNK_Function_template;
39      else if (isa<ClassTemplateDecl>(IIDecl))
40        return TNK_Class_template;
41      else if (isa<TemplateTemplateParmDecl>(IIDecl))
42        return TNK_Template_template_parm;
43      else
44        assert(false && "Unknown TemplateDecl");
45    } else if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(IIDecl)) {
46      // C++ [temp.local]p1:
47      //   Like normal (non-template) classes, class templates have an
48      //   injected-class-name (Clause 9). The injected-class-name
49      //   can be used with or without a template-argument-list. When
50      //   it is used without a template-argument-list, it is
51      //   equivalent to the injected-class-name followed by the
52      //   template-parameters of the class template enclosed in
53      //   <>. When it is used with a template-argument-list, it
54      //   refers to the specified class template specialization,
55      //   which could be the current specialization or another
56      //   specialization.
57      if (Record->isInjectedClassName()) {
58        Record = cast<CXXRecordDecl>(Context.getCanonicalDecl(Record));
59        if ((Template = Record->getDescribedClassTemplate()))
60          return TNK_Class_template;
61        else if (ClassTemplateSpecializationDecl *Spec
62                   = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
63          Template = Spec->getSpecializedTemplate();
64          return TNK_Class_template;
65        }
66      }
67    }
68
69    // FIXME: What follows is a gross hack.
70    if (FunctionDecl *FD = dyn_cast<FunctionDecl>(IIDecl)) {
71      if (FD->getType()->isDependentType()) {
72        Template = FD;
73        return TNK_Function_template;
74      }
75    } else if (OverloadedFunctionDecl *Ovl
76                 = dyn_cast<OverloadedFunctionDecl>(IIDecl)) {
77      for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(),
78                                                  FEnd = Ovl->function_end();
79           F != FEnd; ++F) {
80        if ((*F)->getType()->isDependentType()) {
81          Template = Ovl;
82          return TNK_Function_template;
83        }
84      }
85    }
86  }
87  return TNK_Non_template;
88}
89
90/// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
91/// that the template parameter 'PrevDecl' is being shadowed by a new
92/// declaration at location Loc. Returns true to indicate that this is
93/// an error, and false otherwise.
94bool Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
95  assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
96
97  // Microsoft Visual C++ permits template parameters to be shadowed.
98  if (getLangOptions().Microsoft)
99    return false;
100
101  // C++ [temp.local]p4:
102  //   A template-parameter shall not be redeclared within its
103  //   scope (including nested scopes).
104  Diag(Loc, diag::err_template_param_shadow)
105    << cast<NamedDecl>(PrevDecl)->getDeclName();
106  Diag(PrevDecl->getLocation(), diag::note_template_param_here);
107  return true;
108}
109
110/// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
111/// the parameter D to reference the templated declaration and return a pointer
112/// to the template declaration. Otherwise, do nothing to D and return null.
113TemplateDecl *Sema::AdjustDeclIfTemplate(DeclTy *&D)
114{
115  if(TemplateDecl *Temp = dyn_cast<TemplateDecl>(static_cast<Decl*>(D))) {
116    D = Temp->getTemplatedDecl();
117    return Temp;
118  }
119  return 0;
120}
121
122/// ActOnTypeParameter - Called when a C++ template type parameter
123/// (e.g., "typename T") has been parsed. Typename specifies whether
124/// the keyword "typename" was used to declare the type parameter
125/// (otherwise, "class" was used), and KeyLoc is the location of the
126/// "class" or "typename" keyword. ParamName is the name of the
127/// parameter (NULL indicates an unnamed template parameter) and
128/// ParamName is the location of the parameter name (if any).
129/// If the type parameter has a default argument, it will be added
130/// later via ActOnTypeParameterDefault.
131Sema::DeclTy *Sema::ActOnTypeParameter(Scope *S, bool Typename,
132				       SourceLocation KeyLoc,
133				       IdentifierInfo *ParamName,
134				       SourceLocation ParamNameLoc,
135                                       unsigned Depth, unsigned Position) {
136  assert(S->isTemplateParamScope() &&
137	 "Template type parameter not in template parameter scope!");
138  bool Invalid = false;
139
140  if (ParamName) {
141    NamedDecl *PrevDecl = LookupName(S, ParamName, LookupTagName);
142    if (PrevDecl && PrevDecl->isTemplateParameter())
143      Invalid = Invalid || DiagnoseTemplateParameterShadow(ParamNameLoc,
144							   PrevDecl);
145  }
146
147  SourceLocation Loc = ParamNameLoc;
148  if (!ParamName)
149    Loc = KeyLoc;
150
151  TemplateTypeParmDecl *Param
152    = TemplateTypeParmDecl::Create(Context, CurContext, Loc,
153                                   Depth, Position, ParamName, Typename);
154  if (Invalid)
155    Param->setInvalidDecl();
156
157  if (ParamName) {
158    // Add the template parameter into the current scope.
159    S->AddDecl(Param);
160    IdResolver.AddDecl(Param);
161  }
162
163  return Param;
164}
165
166/// ActOnTypeParameterDefault - Adds a default argument (the type
167/// Default) to the given template type parameter (TypeParam).
168void Sema::ActOnTypeParameterDefault(DeclTy *TypeParam,
169                                     SourceLocation EqualLoc,
170                                     SourceLocation DefaultLoc,
171                                     TypeTy *DefaultT) {
172  TemplateTypeParmDecl *Parm
173    = cast<TemplateTypeParmDecl>(static_cast<Decl *>(TypeParam));
174  QualType Default = QualType::getFromOpaquePtr(DefaultT);
175
176  // C++ [temp.param]p14:
177  //   A template-parameter shall not be used in its own default argument.
178  // FIXME: Implement this check! Needs a recursive walk over the types.
179
180  // Check the template argument itself.
181  if (CheckTemplateArgument(Parm, Default, DefaultLoc)) {
182    Parm->setInvalidDecl();
183    return;
184  }
185
186  Parm->setDefaultArgument(Default, DefaultLoc, false);
187}
188
189/// \brief Check that the type of a non-type template parameter is
190/// well-formed.
191///
192/// \returns the (possibly-promoted) parameter type if valid;
193/// otherwise, produces a diagnostic and returns a NULL type.
194QualType
195Sema::CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc) {
196  // C++ [temp.param]p4:
197  //
198  // A non-type template-parameter shall have one of the following
199  // (optionally cv-qualified) types:
200  //
201  //       -- integral or enumeration type,
202  if (T->isIntegralType() || T->isEnumeralType() ||
203      //   -- pointer to object or pointer to function,
204      (T->isPointerType() &&
205       (T->getAsPointerType()->getPointeeType()->isObjectType() ||
206        T->getAsPointerType()->getPointeeType()->isFunctionType())) ||
207      //   -- reference to object or reference to function,
208      T->isReferenceType() ||
209      //   -- pointer to member.
210      T->isMemberPointerType() ||
211      // If T is a dependent type, we can't do the check now, so we
212      // assume that it is well-formed.
213      T->isDependentType())
214    return T;
215  // C++ [temp.param]p8:
216  //
217  //   A non-type template-parameter of type "array of T" or
218  //   "function returning T" is adjusted to be of type "pointer to
219  //   T" or "pointer to function returning T", respectively.
220  else if (T->isArrayType())
221    // FIXME: Keep the type prior to promotion?
222    return Context.getArrayDecayedType(T);
223  else if (T->isFunctionType())
224    // FIXME: Keep the type prior to promotion?
225    return Context.getPointerType(T);
226
227  Diag(Loc, diag::err_template_nontype_parm_bad_type)
228    << T;
229
230  return QualType();
231}
232
233/// ActOnNonTypeTemplateParameter - Called when a C++ non-type
234/// template parameter (e.g., "int Size" in "template<int Size>
235/// class Array") has been parsed. S is the current scope and D is
236/// the parsed declarator.
237Sema::DeclTy *Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
238                                                  unsigned Depth,
239                                                  unsigned Position) {
240  QualType T = GetTypeForDeclarator(D, S);
241
242  assert(S->isTemplateParamScope() &&
243         "Non-type template parameter not in template parameter scope!");
244  bool Invalid = false;
245
246  IdentifierInfo *ParamName = D.getIdentifier();
247  if (ParamName) {
248    NamedDecl *PrevDecl = LookupName(S, ParamName, LookupTagName);
249    if (PrevDecl && PrevDecl->isTemplateParameter())
250      Invalid = Invalid || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
251                                                           PrevDecl);
252  }
253
254  T = CheckNonTypeTemplateParameterType(T, D.getIdentifierLoc());
255  if (T.isNull()) {
256    T = Context.IntTy; // Recover with an 'int' type.
257    Invalid = true;
258  }
259
260  NonTypeTemplateParmDecl *Param
261    = NonTypeTemplateParmDecl::Create(Context, CurContext, D.getIdentifierLoc(),
262                                      Depth, Position, ParamName, T);
263  if (Invalid)
264    Param->setInvalidDecl();
265
266  if (D.getIdentifier()) {
267    // Add the template parameter into the current scope.
268    S->AddDecl(Param);
269    IdResolver.AddDecl(Param);
270  }
271  return Param;
272}
273
274/// \brief Adds a default argument to the given non-type template
275/// parameter.
276void Sema::ActOnNonTypeTemplateParameterDefault(DeclTy *TemplateParamD,
277                                                SourceLocation EqualLoc,
278                                                ExprArg DefaultE) {
279  NonTypeTemplateParmDecl *TemplateParm
280    = cast<NonTypeTemplateParmDecl>(static_cast<Decl *>(TemplateParamD));
281  Expr *Default = static_cast<Expr *>(DefaultE.get());
282
283  // C++ [temp.param]p14:
284  //   A template-parameter shall not be used in its own default argument.
285  // FIXME: Implement this check! Needs a recursive walk over the types.
286
287  // Check the well-formedness of the default template argument.
288  if (CheckTemplateArgument(TemplateParm, TemplateParm->getType(), Default)) {
289    TemplateParm->setInvalidDecl();
290    return;
291  }
292
293  TemplateParm->setDefaultArgument(static_cast<Expr *>(DefaultE.release()));
294}
295
296
297/// ActOnTemplateTemplateParameter - Called when a C++ template template
298/// parameter (e.g. T in template <template <typename> class T> class array)
299/// has been parsed. S is the current scope.
300Sema::DeclTy *Sema::ActOnTemplateTemplateParameter(Scope* S,
301                                                   SourceLocation TmpLoc,
302                                                   TemplateParamsTy *Params,
303                                                   IdentifierInfo *Name,
304                                                   SourceLocation NameLoc,
305                                                   unsigned Depth,
306                                                   unsigned Position)
307{
308  assert(S->isTemplateParamScope() &&
309         "Template template parameter not in template parameter scope!");
310
311  // Construct the parameter object.
312  TemplateTemplateParmDecl *Param =
313    TemplateTemplateParmDecl::Create(Context, CurContext, TmpLoc, Depth,
314                                     Position, Name,
315                                     (TemplateParameterList*)Params);
316
317  // Make sure the parameter is valid.
318  // FIXME: Decl object is not currently invalidated anywhere so this doesn't
319  // do anything yet. However, if the template parameter list or (eventual)
320  // default value is ever invalidated, that will propagate here.
321  bool Invalid = false;
322  if (Invalid) {
323    Param->setInvalidDecl();
324  }
325
326  // If the tt-param has a name, then link the identifier into the scope
327  // and lookup mechanisms.
328  if (Name) {
329    S->AddDecl(Param);
330    IdResolver.AddDecl(Param);
331  }
332
333  return Param;
334}
335
336/// \brief Adds a default argument to the given template template
337/// parameter.
338void Sema::ActOnTemplateTemplateParameterDefault(DeclTy *TemplateParamD,
339                                                 SourceLocation EqualLoc,
340                                                 ExprArg DefaultE) {
341  TemplateTemplateParmDecl *TemplateParm
342    = cast<TemplateTemplateParmDecl>(static_cast<Decl *>(TemplateParamD));
343
344  // Since a template-template parameter's default argument is an
345  // id-expression, it must be a DeclRefExpr.
346  DeclRefExpr *Default
347    = cast<DeclRefExpr>(static_cast<Expr *>(DefaultE.get()));
348
349  // C++ [temp.param]p14:
350  //   A template-parameter shall not be used in its own default argument.
351  // FIXME: Implement this check! Needs a recursive walk over the types.
352
353  // Check the well-formedness of the template argument.
354  if (!isa<TemplateDecl>(Default->getDecl())) {
355    Diag(Default->getSourceRange().getBegin(),
356         diag::err_template_arg_must_be_template)
357      << Default->getSourceRange();
358    TemplateParm->setInvalidDecl();
359    return;
360  }
361  if (CheckTemplateArgument(TemplateParm, Default)) {
362    TemplateParm->setInvalidDecl();
363    return;
364  }
365
366  DefaultE.release();
367  TemplateParm->setDefaultArgument(Default);
368}
369
370/// ActOnTemplateParameterList - Builds a TemplateParameterList that
371/// contains the template parameters in Params/NumParams.
372Sema::TemplateParamsTy *
373Sema::ActOnTemplateParameterList(unsigned Depth,
374                                 SourceLocation ExportLoc,
375                                 SourceLocation TemplateLoc,
376                                 SourceLocation LAngleLoc,
377                                 DeclTy **Params, unsigned NumParams,
378                                 SourceLocation RAngleLoc) {
379  if (ExportLoc.isValid())
380    Diag(ExportLoc, diag::note_template_export_unsupported);
381
382  return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
383                                       (Decl**)Params, NumParams, RAngleLoc);
384}
385
386Sema::DeclResult
387Sema::ActOnClassTemplate(Scope *S, unsigned TagSpec, TagKind TK,
388                         SourceLocation KWLoc, const CXXScopeSpec &SS,
389                         IdentifierInfo *Name, SourceLocation NameLoc,
390                         AttributeList *Attr,
391                         MultiTemplateParamsArg TemplateParameterLists,
392                         AccessSpecifier AS) {
393  assert(TemplateParameterLists.size() > 0 && "No template parameter lists?");
394  assert(TK != TK_Reference && "Can only declare or define class templates");
395  bool Invalid = false;
396
397  // Check that we can declare a template here.
398  if (CheckTemplateDeclScope(S, TemplateParameterLists))
399    return true;
400
401  TagDecl::TagKind Kind;
402  switch (TagSpec) {
403  default: assert(0 && "Unknown tag type!");
404  case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
405  case DeclSpec::TST_union:  Kind = TagDecl::TK_union; break;
406  case DeclSpec::TST_class:  Kind = TagDecl::TK_class; break;
407  }
408
409  // There is no such thing as an unnamed class template.
410  if (!Name) {
411    Diag(KWLoc, diag::err_template_unnamed_class);
412    return true;
413  }
414
415  // Find any previous declaration with this name.
416  LookupResult Previous = LookupParsedName(S, &SS, Name, LookupOrdinaryName,
417                                           true);
418  assert(!Previous.isAmbiguous() && "Ambiguity in class template redecl?");
419  NamedDecl *PrevDecl = 0;
420  if (Previous.begin() != Previous.end())
421    PrevDecl = *Previous.begin();
422
423  DeclContext *SemanticContext = CurContext;
424  if (SS.isNotEmpty() && !SS.isInvalid()) {
425    SemanticContext = computeDeclContext(SS);
426
427    // FIXME: need to match up several levels of template parameter
428    // lists here.
429  }
430
431  // FIXME: member templates!
432  TemplateParameterList *TemplateParams
433    = static_cast<TemplateParameterList *>(*TemplateParameterLists.release());
434
435  // If there is a previous declaration with the same name, check
436  // whether this is a valid redeclaration.
437  ClassTemplateDecl *PrevClassTemplate
438    = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
439  if (PrevClassTemplate) {
440    // Ensure that the template parameter lists are compatible.
441    if (!TemplateParameterListsAreEqual(TemplateParams,
442                                   PrevClassTemplate->getTemplateParameters(),
443                                        /*Complain=*/true))
444      return true;
445
446    // C++ [temp.class]p4:
447    //   In a redeclaration, partial specialization, explicit
448    //   specialization or explicit instantiation of a class template,
449    //   the class-key shall agree in kind with the original class
450    //   template declaration (7.1.5.3).
451    RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
452    if (PrevRecordDecl->getTagKind() != Kind) {
453      Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
454      Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
455      return true;
456    }
457
458
459    // Check for redefinition of this class template.
460    if (TK == TK_Definition) {
461      if (TagDecl *Def = PrevRecordDecl->getDefinition(Context)) {
462        Diag(NameLoc, diag::err_redefinition) << Name;
463        Diag(Def->getLocation(), diag::note_previous_definition);
464        // FIXME: Would it make sense to try to "forget" the previous
465        // definition, as part of error recovery?
466        return true;
467      }
468    }
469  } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
470    // Maybe we will complain about the shadowed template parameter.
471    DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
472    // Just pretend that we didn't see the previous declaration.
473    PrevDecl = 0;
474  } else if (PrevDecl) {
475    // C++ [temp]p5:
476    //   A class template shall not have the same name as any other
477    //   template, class, function, object, enumeration, enumerator,
478    //   namespace, or type in the same scope (3.3), except as specified
479    //   in (14.5.4).
480    Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
481    Diag(PrevDecl->getLocation(), diag::note_previous_definition);
482    return true;
483  }
484
485  // Check the template parameter list of this declaration, possibly
486  // merging in the template parameter list from the previous class
487  // template declaration.
488  if (CheckTemplateParameterList(TemplateParams,
489            PrevClassTemplate? PrevClassTemplate->getTemplateParameters() : 0))
490    Invalid = true;
491
492  // If we had a scope specifier, we better have a previous template
493  // declaration!
494
495  CXXRecordDecl *NewClass =
496    CXXRecordDecl::Create(Context, Kind, SemanticContext, NameLoc, Name,
497                          PrevClassTemplate?
498                            PrevClassTemplate->getTemplatedDecl() : 0);
499
500  ClassTemplateDecl *NewTemplate
501    = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
502                                DeclarationName(Name), TemplateParams,
503                                NewClass, PrevClassTemplate);
504  NewClass->setDescribedClassTemplate(NewTemplate);
505
506  // Set the lexical context of these templates
507  NewClass->setLexicalDeclContext(CurContext);
508  NewTemplate->setLexicalDeclContext(CurContext);
509
510  if (TK == TK_Definition)
511    NewClass->startDefinition();
512
513  if (Attr)
514    ProcessDeclAttributeList(NewClass, Attr);
515
516  PushOnScopeChains(NewTemplate, S);
517
518  if (Invalid) {
519    NewTemplate->setInvalidDecl();
520    NewClass->setInvalidDecl();
521  }
522  return NewTemplate;
523}
524
525/// \brief Checks the validity of a template parameter list, possibly
526/// considering the template parameter list from a previous
527/// declaration.
528///
529/// If an "old" template parameter list is provided, it must be
530/// equivalent (per TemplateParameterListsAreEqual) to the "new"
531/// template parameter list.
532///
533/// \param NewParams Template parameter list for a new template
534/// declaration. This template parameter list will be updated with any
535/// default arguments that are carried through from the previous
536/// template parameter list.
537///
538/// \param OldParams If provided, template parameter list from a
539/// previous declaration of the same template. Default template
540/// arguments will be merged from the old template parameter list to
541/// the new template parameter list.
542///
543/// \returns true if an error occurred, false otherwise.
544bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
545                                      TemplateParameterList *OldParams) {
546  bool Invalid = false;
547
548  // C++ [temp.param]p10:
549  //   The set of default template-arguments available for use with a
550  //   template declaration or definition is obtained by merging the
551  //   default arguments from the definition (if in scope) and all
552  //   declarations in scope in the same way default function
553  //   arguments are (8.3.6).
554  bool SawDefaultArgument = false;
555  SourceLocation PreviousDefaultArgLoc;
556
557  // Dummy initialization to avoid warnings.
558  TemplateParameterList::iterator OldParam = NewParams->end();
559  if (OldParams)
560    OldParam = OldParams->begin();
561
562  for (TemplateParameterList::iterator NewParam = NewParams->begin(),
563                                    NewParamEnd = NewParams->end();
564       NewParam != NewParamEnd; ++NewParam) {
565    // Variables used to diagnose redundant default arguments
566    bool RedundantDefaultArg = false;
567    SourceLocation OldDefaultLoc;
568    SourceLocation NewDefaultLoc;
569
570    // Variables used to diagnose missing default arguments
571    bool MissingDefaultArg = false;
572
573    // Merge default arguments for template type parameters.
574    if (TemplateTypeParmDecl *NewTypeParm
575          = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
576      TemplateTypeParmDecl *OldTypeParm
577          = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : 0;
578
579      if (OldTypeParm && OldTypeParm->hasDefaultArgument() &&
580          NewTypeParm->hasDefaultArgument()) {
581        OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
582        NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
583        SawDefaultArgument = true;
584        RedundantDefaultArg = true;
585        PreviousDefaultArgLoc = NewDefaultLoc;
586      } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
587        // Merge the default argument from the old declaration to the
588        // new declaration.
589        SawDefaultArgument = true;
590        NewTypeParm->setDefaultArgument(OldTypeParm->getDefaultArgument(),
591                                        OldTypeParm->getDefaultArgumentLoc(),
592                                        true);
593        PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
594      } else if (NewTypeParm->hasDefaultArgument()) {
595        SawDefaultArgument = true;
596        PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
597      } else if (SawDefaultArgument)
598        MissingDefaultArg = true;
599    }
600    // Merge default arguments for non-type template parameters
601    else if (NonTypeTemplateParmDecl *NewNonTypeParm
602               = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
603      NonTypeTemplateParmDecl *OldNonTypeParm
604        = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : 0;
605      if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument() &&
606          NewNonTypeParm->hasDefaultArgument()) {
607        OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
608        NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
609        SawDefaultArgument = true;
610        RedundantDefaultArg = true;
611        PreviousDefaultArgLoc = NewDefaultLoc;
612      } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
613        // Merge the default argument from the old declaration to the
614        // new declaration.
615        SawDefaultArgument = true;
616        // FIXME: We need to create a new kind of "default argument"
617        // expression that points to a previous template template
618        // parameter.
619        NewNonTypeParm->setDefaultArgument(
620                                        OldNonTypeParm->getDefaultArgument());
621        PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
622      } else if (NewNonTypeParm->hasDefaultArgument()) {
623        SawDefaultArgument = true;
624        PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
625      } else if (SawDefaultArgument)
626        MissingDefaultArg = true;
627    }
628    // Merge default arguments for template template parameters
629    else {
630      TemplateTemplateParmDecl *NewTemplateParm
631        = cast<TemplateTemplateParmDecl>(*NewParam);
632      TemplateTemplateParmDecl *OldTemplateParm
633        = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : 0;
634      if (OldTemplateParm && OldTemplateParm->hasDefaultArgument() &&
635          NewTemplateParm->hasDefaultArgument()) {
636        OldDefaultLoc = OldTemplateParm->getDefaultArgumentLoc();
637        NewDefaultLoc = NewTemplateParm->getDefaultArgumentLoc();
638        SawDefaultArgument = true;
639        RedundantDefaultArg = true;
640        PreviousDefaultArgLoc = NewDefaultLoc;
641      } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
642        // Merge the default argument from the old declaration to the
643        // new declaration.
644        SawDefaultArgument = true;
645        // FIXME: We need to create a new kind of "default argument"
646        // expression that points to a previous template template
647        // parameter.
648        NewTemplateParm->setDefaultArgument(
649                                        OldTemplateParm->getDefaultArgument());
650        PreviousDefaultArgLoc = OldTemplateParm->getDefaultArgumentLoc();
651      } else if (NewTemplateParm->hasDefaultArgument()) {
652        SawDefaultArgument = true;
653        PreviousDefaultArgLoc = NewTemplateParm->getDefaultArgumentLoc();
654      } else if (SawDefaultArgument)
655        MissingDefaultArg = true;
656    }
657
658    if (RedundantDefaultArg) {
659      // C++ [temp.param]p12:
660      //   A template-parameter shall not be given default arguments
661      //   by two different declarations in the same scope.
662      Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
663      Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
664      Invalid = true;
665    } else if (MissingDefaultArg) {
666      // C++ [temp.param]p11:
667      //   If a template-parameter has a default template-argument,
668      //   all subsequent template-parameters shall have a default
669      //   template-argument supplied.
670      Diag((*NewParam)->getLocation(),
671           diag::err_template_param_default_arg_missing);
672      Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
673      Invalid = true;
674    }
675
676    // If we have an old template parameter list that we're merging
677    // in, move on to the next parameter.
678    if (OldParams)
679      ++OldParam;
680  }
681
682  return Invalid;
683}
684
685/// \brief Translates template arguments as provided by the parser
686/// into template arguments used by semantic analysis.
687static void
688translateTemplateArguments(ASTTemplateArgsPtr &TemplateArgsIn,
689                           SourceLocation *TemplateArgLocs,
690                     llvm::SmallVector<TemplateArgument, 16> &TemplateArgs) {
691  TemplateArgs.reserve(TemplateArgsIn.size());
692
693  void **Args = TemplateArgsIn.getArgs();
694  bool *ArgIsType = TemplateArgsIn.getArgIsType();
695  for (unsigned Arg = 0, Last = TemplateArgsIn.size(); Arg != Last; ++Arg) {
696    TemplateArgs.push_back(
697      ArgIsType[Arg]? TemplateArgument(TemplateArgLocs[Arg],
698                                       QualType::getFromOpaquePtr(Args[Arg]))
699                    : TemplateArgument(reinterpret_cast<Expr *>(Args[Arg])));
700  }
701}
702
703QualType Sema::CheckClassTemplateId(ClassTemplateDecl *ClassTemplate,
704                                    SourceLocation TemplateLoc,
705                                    SourceLocation LAngleLoc,
706                                    const TemplateArgument *TemplateArgs,
707                                    unsigned NumTemplateArgs,
708                                    SourceLocation RAngleLoc) {
709  // Check that the template argument list is well-formed for this
710  // template.
711  llvm::SmallVector<TemplateArgument, 16> ConvertedTemplateArgs;
712  if (CheckTemplateArgumentList(ClassTemplate, TemplateLoc, LAngleLoc,
713                                TemplateArgs, NumTemplateArgs, RAngleLoc,
714                                ConvertedTemplateArgs))
715    return QualType();
716
717  assert((ConvertedTemplateArgs.size() ==
718            ClassTemplate->getTemplateParameters()->size()) &&
719         "Converted template argument list is too short!");
720
721  QualType CanonType;
722
723  if (ClassTemplateSpecializationType::anyDependentTemplateArguments(
724                                                      TemplateArgs,
725                                                      NumTemplateArgs)) {
726    // This class template specialization is a dependent
727    // type. Therefore, its canonical type is another class template
728    // specialization type that contains all of the converted
729    // arguments in canonical form. This ensures that, e.g., A<T> and
730    // A<T, T> have identical types when A is declared as:
731    //
732    //   template<typename T, typename U = T> struct A;
733
734    CanonType = Context.getClassTemplateSpecializationType(ClassTemplate,
735                                                    &ConvertedTemplateArgs[0],
736                                                ConvertedTemplateArgs.size());
737  } else {
738    // Find the class template specialization declaration that
739    // corresponds to these arguments.
740    llvm::FoldingSetNodeID ID;
741    ClassTemplateSpecializationDecl::Profile(ID, &ConvertedTemplateArgs[0],
742                                             ConvertedTemplateArgs.size());
743    void *InsertPos = 0;
744    ClassTemplateSpecializationDecl *Decl
745      = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
746    if (!Decl) {
747      // This is the first time we have referenced this class template
748      // specialization. Create the canonical declaration and add it to
749      // the set of specializations.
750      Decl = ClassTemplateSpecializationDecl::Create(Context,
751                                           ClassTemplate->getDeclContext(),
752                                                     TemplateLoc,
753                                                     ClassTemplate,
754                                                     &ConvertedTemplateArgs[0],
755                                                  ConvertedTemplateArgs.size(),
756                                                     0);
757      ClassTemplate->getSpecializations().InsertNode(Decl, InsertPos);
758      Decl->setLexicalDeclContext(CurContext);
759    }
760
761    CanonType = Context.getTypeDeclType(Decl);
762  }
763
764  // Build the fully-sugared type for this class template
765  // specialization, which refers back to the class template
766  // specialization we created or found.
767  return Context.getClassTemplateSpecializationType(ClassTemplate,
768                                                    TemplateArgs,
769                                                    NumTemplateArgs,
770                                                    CanonType);
771}
772
773Action::TypeResult
774Sema::ActOnClassTemplateId(DeclTy *TemplateD, SourceLocation TemplateLoc,
775                           SourceLocation LAngleLoc,
776                           ASTTemplateArgsPtr TemplateArgsIn,
777                           SourceLocation *TemplateArgLocs,
778                           SourceLocation RAngleLoc,
779                           const CXXScopeSpec *SS) {
780  TemplateDecl *Template = cast<TemplateDecl>(static_cast<Decl *>(TemplateD));
781  ClassTemplateDecl *ClassTemplate = cast<ClassTemplateDecl>(Template);
782
783  // Translate the parser's template argument list in our AST format.
784  llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
785  translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
786
787  QualType Result = CheckClassTemplateId(ClassTemplate, TemplateLoc,
788                                         LAngleLoc,
789                                         &TemplateArgs[0],
790                                         TemplateArgs.size(),
791                                         RAngleLoc);
792
793  if (SS)
794    Result = getQualifiedNameType(*SS, Result);
795
796  TemplateArgsIn.release();
797  return Result.getAsOpaquePtr();
798}
799
800/// \brief Check that the given template argument list is well-formed
801/// for specializing the given template.
802bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
803                                     SourceLocation TemplateLoc,
804                                     SourceLocation LAngleLoc,
805                                     const TemplateArgument *TemplateArgs,
806                                     unsigned NumTemplateArgs,
807                                     SourceLocation RAngleLoc,
808                          llvm::SmallVectorImpl<TemplateArgument> &Converted) {
809  TemplateParameterList *Params = Template->getTemplateParameters();
810  unsigned NumParams = Params->size();
811  unsigned NumArgs = NumTemplateArgs;
812  bool Invalid = false;
813
814  if (NumArgs > NumParams ||
815      NumArgs < Params->getMinRequiredArguments()) {
816    // FIXME: point at either the first arg beyond what we can handle,
817    // or the '>', depending on whether we have too many or too few
818    // arguments.
819    SourceRange Range;
820    if (NumArgs > NumParams)
821      Range = SourceRange(TemplateArgs[NumParams].getLocation(), RAngleLoc);
822    Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
823      << (NumArgs > NumParams)
824      << (isa<ClassTemplateDecl>(Template)? 0 :
825          isa<FunctionTemplateDecl>(Template)? 1 :
826          isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
827      << Template << Range;
828    Diag(Template->getLocation(), diag::note_template_decl_here)
829      << Params->getSourceRange();
830    Invalid = true;
831  }
832
833  // C++ [temp.arg]p1:
834  //   [...] The type and form of each template-argument specified in
835  //   a template-id shall match the type and form specified for the
836  //   corresponding parameter declared by the template in its
837  //   template-parameter-list.
838  unsigned ArgIdx = 0;
839  for (TemplateParameterList::iterator Param = Params->begin(),
840                                       ParamEnd = Params->end();
841       Param != ParamEnd; ++Param, ++ArgIdx) {
842    // Decode the template argument
843    TemplateArgument Arg;
844    if (ArgIdx >= NumArgs) {
845      // Retrieve the default template argument from the template
846      // parameter.
847      if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
848        if (!TTP->hasDefaultArgument())
849          break;
850
851        QualType ArgType = TTP->getDefaultArgument();
852
853        // If the argument type is dependent, instantiate it now based
854        // on the previously-computed template arguments.
855        if (ArgType->isDependentType()) {
856          InstantiatingTemplate Inst(*this, TemplateLoc,
857                                     Template, &Converted[0],
858                                     Converted.size(),
859                                     SourceRange(TemplateLoc, RAngleLoc));
860          ArgType = InstantiateType(ArgType, &Converted[0], Converted.size(),
861                                    TTP->getDefaultArgumentLoc(),
862                                    TTP->getDeclName());
863        }
864
865        if (ArgType.isNull())
866          return true;
867
868        Arg = TemplateArgument(TTP->getLocation(), ArgType);
869      } else if (NonTypeTemplateParmDecl *NTTP
870                   = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
871        if (!NTTP->hasDefaultArgument())
872          break;
873
874        // FIXME: Instantiate default argument
875        Arg = TemplateArgument(NTTP->getDefaultArgument());
876      } else {
877        TemplateTemplateParmDecl *TempParm
878          = cast<TemplateTemplateParmDecl>(*Param);
879
880        if (!TempParm->hasDefaultArgument())
881          break;
882
883        // FIXME: Instantiate default argument
884        Arg = TemplateArgument(TempParm->getDefaultArgument());
885      }
886    } else {
887      // Retrieve the template argument produced by the user.
888      Arg = TemplateArgs[ArgIdx];
889    }
890
891
892    if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
893      // Check template type parameters.
894      if (Arg.getKind() == TemplateArgument::Type) {
895        if (CheckTemplateArgument(TTP, Arg.getAsType(), Arg.getLocation()))
896          Invalid = true;
897
898        // Add the converted template type argument.
899        Converted.push_back(
900                 TemplateArgument(Arg.getLocation(),
901                                  Context.getCanonicalType(Arg.getAsType())));
902        continue;
903      }
904
905      // C++ [temp.arg.type]p1:
906      //   A template-argument for a template-parameter which is a
907      //   type shall be a type-id.
908
909      // We have a template type parameter but the template argument
910      // is not a type.
911      Diag(Arg.getLocation(), diag::err_template_arg_must_be_type);
912      Diag((*Param)->getLocation(), diag::note_template_param_here);
913      Invalid = true;
914    } else if (NonTypeTemplateParmDecl *NTTP
915                 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
916      // Check non-type template parameters.
917
918      // Instantiate the type of the non-type template parameter with
919      // the template arguments we've seen thus far.
920      QualType NTTPType = NTTP->getType();
921      if (NTTPType->isDependentType()) {
922        // Instantiate the type of the non-type template parameter.
923        InstantiatingTemplate Inst(*this, TemplateLoc,
924                                   Template, &Converted[0],
925                                   Converted.size(),
926                                   SourceRange(TemplateLoc, RAngleLoc));
927
928        NTTPType = InstantiateType(NTTPType,
929                                   &Converted[0], Converted.size(),
930                                   NTTP->getLocation(),
931                                   NTTP->getDeclName());
932        // If that worked, check the non-type template parameter type
933        // for validity.
934        if (!NTTPType.isNull())
935          NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
936                                                       NTTP->getLocation());
937
938        if (NTTPType.isNull()) {
939          Invalid = true;
940          break;
941        }
942      }
943
944      switch (Arg.getKind()) {
945      case TemplateArgument::Expression: {
946        Expr *E = Arg.getAsExpr();
947        if (CheckTemplateArgument(NTTP, NTTPType, E, &Converted))
948          Invalid = true;
949        break;
950      }
951
952      case TemplateArgument::Declaration:
953      case TemplateArgument::Integral:
954        // We've already checked this template argument, so just copy
955        // it to the list of converted arguments.
956        Converted.push_back(Arg);
957        break;
958
959      case TemplateArgument::Type:
960        // We have a non-type template parameter but the template
961        // argument is a type.
962
963        // C++ [temp.arg]p2:
964        //   In a template-argument, an ambiguity between a type-id and
965        //   an expression is resolved to a type-id, regardless of the
966        //   form of the corresponding template-parameter.
967        //
968        // We warn specifically about this case, since it can be rather
969        // confusing for users.
970        if (Arg.getAsType()->isFunctionType())
971          Diag(Arg.getLocation(), diag::err_template_arg_nontype_ambig)
972            << Arg.getAsType();
973        else
974          Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr);
975        Diag((*Param)->getLocation(), diag::note_template_param_here);
976        Invalid = true;
977      }
978    } else {
979      // Check template template parameters.
980      TemplateTemplateParmDecl *TempParm
981        = cast<TemplateTemplateParmDecl>(*Param);
982
983      switch (Arg.getKind()) {
984      case TemplateArgument::Expression: {
985        Expr *ArgExpr = Arg.getAsExpr();
986        if (ArgExpr && isa<DeclRefExpr>(ArgExpr) &&
987            isa<TemplateDecl>(cast<DeclRefExpr>(ArgExpr)->getDecl())) {
988          if (CheckTemplateArgument(TempParm, cast<DeclRefExpr>(ArgExpr)))
989            Invalid = true;
990
991          // Add the converted template argument.
992          // FIXME: Need the "canonical" template declaration!
993          Converted.push_back(
994                    TemplateArgument(Arg.getLocation(),
995                                     cast<DeclRefExpr>(ArgExpr)->getDecl()));
996          continue;
997        }
998      }
999        // fall through
1000
1001      case TemplateArgument::Type: {
1002        // We have a template template parameter but the template
1003        // argument does not refer to a template.
1004        Diag(Arg.getLocation(), diag::err_template_arg_must_be_template);
1005        Invalid = true;
1006        break;
1007      }
1008
1009      case TemplateArgument::Declaration:
1010        // We've already checked this template argument, so just copy
1011        // it to the list of converted arguments.
1012        Converted.push_back(Arg);
1013        break;
1014
1015      case TemplateArgument::Integral:
1016        assert(false && "Integral argument with template template parameter");
1017        break;
1018      }
1019    }
1020  }
1021
1022  return Invalid;
1023}
1024
1025/// \brief Check a template argument against its corresponding
1026/// template type parameter.
1027///
1028/// This routine implements the semantics of C++ [temp.arg.type]. It
1029/// returns true if an error occurred, and false otherwise.
1030bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
1031                                 QualType Arg, SourceLocation ArgLoc) {
1032  // C++ [temp.arg.type]p2:
1033  //   A local type, a type with no linkage, an unnamed type or a type
1034  //   compounded from any of these types shall not be used as a
1035  //   template-argument for a template type-parameter.
1036  //
1037  // FIXME: Perform the recursive and no-linkage type checks.
1038  const TagType *Tag = 0;
1039  if (const EnumType *EnumT = Arg->getAsEnumType())
1040    Tag = EnumT;
1041  else if (const RecordType *RecordT = Arg->getAsRecordType())
1042    Tag = RecordT;
1043  if (Tag && Tag->getDecl()->getDeclContext()->isFunctionOrMethod())
1044    return Diag(ArgLoc, diag::err_template_arg_local_type)
1045      << QualType(Tag, 0);
1046  else if (Tag && !Tag->getDecl()->getDeclName() &&
1047           !Tag->getDecl()->getTypedefForAnonDecl()) {
1048    Diag(ArgLoc, diag::err_template_arg_unnamed_type);
1049    Diag(Tag->getDecl()->getLocation(), diag::note_template_unnamed_type_here);
1050    return true;
1051  }
1052
1053  return false;
1054}
1055
1056/// \brief Checks whether the given template argument is the address
1057/// of an object or function according to C++ [temp.arg.nontype]p1.
1058bool Sema::CheckTemplateArgumentAddressOfObjectOrFunction(Expr *Arg,
1059                                                          NamedDecl *&Entity) {
1060  bool Invalid = false;
1061
1062  // See through any implicit casts we added to fix the type.
1063  if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
1064    Arg = Cast->getSubExpr();
1065
1066  // C++ [temp.arg.nontype]p1:
1067  //
1068  //   A template-argument for a non-type, non-template
1069  //   template-parameter shall be one of: [...]
1070  //
1071  //     -- the address of an object or function with external
1072  //        linkage, including function templates and function
1073  //        template-ids but excluding non-static class members,
1074  //        expressed as & id-expression where the & is optional if
1075  //        the name refers to a function or array, or if the
1076  //        corresponding template-parameter is a reference; or
1077  DeclRefExpr *DRE = 0;
1078
1079  // Ignore (and complain about) any excess parentheses.
1080  while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
1081    if (!Invalid) {
1082      Diag(Arg->getSourceRange().getBegin(),
1083           diag::err_template_arg_extra_parens)
1084        << Arg->getSourceRange();
1085      Invalid = true;
1086    }
1087
1088    Arg = Parens->getSubExpr();
1089  }
1090
1091  if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
1092    if (UnOp->getOpcode() == UnaryOperator::AddrOf)
1093      DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
1094  } else
1095    DRE = dyn_cast<DeclRefExpr>(Arg);
1096
1097  if (!DRE || !isa<ValueDecl>(DRE->getDecl()))
1098    return Diag(Arg->getSourceRange().getBegin(),
1099                diag::err_template_arg_not_object_or_func_form)
1100      << Arg->getSourceRange();
1101
1102  // Cannot refer to non-static data members
1103  if (FieldDecl *Field = dyn_cast<FieldDecl>(DRE->getDecl()))
1104    return Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_field)
1105      << Field << Arg->getSourceRange();
1106
1107  // Cannot refer to non-static member functions
1108  if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(DRE->getDecl()))
1109    if (!Method->isStatic())
1110      return Diag(Arg->getSourceRange().getBegin(),
1111                  diag::err_template_arg_method)
1112        << Method << Arg->getSourceRange();
1113
1114  // Functions must have external linkage.
1115  if (FunctionDecl *Func = dyn_cast<FunctionDecl>(DRE->getDecl())) {
1116    if (Func->getStorageClass() == FunctionDecl::Static) {
1117      Diag(Arg->getSourceRange().getBegin(),
1118           diag::err_template_arg_function_not_extern)
1119        << Func << Arg->getSourceRange();
1120      Diag(Func->getLocation(), diag::note_template_arg_internal_object)
1121        << true;
1122      return true;
1123    }
1124
1125    // Okay: we've named a function with external linkage.
1126    Entity = Func;
1127    return Invalid;
1128  }
1129
1130  if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
1131    if (!Var->hasGlobalStorage()) {
1132      Diag(Arg->getSourceRange().getBegin(),
1133           diag::err_template_arg_object_not_extern)
1134        << Var << Arg->getSourceRange();
1135      Diag(Var->getLocation(), diag::note_template_arg_internal_object)
1136        << true;
1137      return true;
1138    }
1139
1140    // Okay: we've named an object with external linkage
1141    Entity = Var;
1142    return Invalid;
1143  }
1144
1145  // We found something else, but we don't know specifically what it is.
1146  Diag(Arg->getSourceRange().getBegin(),
1147       diag::err_template_arg_not_object_or_func)
1148      << Arg->getSourceRange();
1149  Diag(DRE->getDecl()->getLocation(),
1150       diag::note_template_arg_refers_here);
1151  return true;
1152}
1153
1154/// \brief Checks whether the given template argument is a pointer to
1155/// member constant according to C++ [temp.arg.nontype]p1.
1156bool
1157Sema::CheckTemplateArgumentPointerToMember(Expr *Arg, NamedDecl *&Member) {
1158  bool Invalid = false;
1159
1160  // See through any implicit casts we added to fix the type.
1161  if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
1162    Arg = Cast->getSubExpr();
1163
1164  // C++ [temp.arg.nontype]p1:
1165  //
1166  //   A template-argument for a non-type, non-template
1167  //   template-parameter shall be one of: [...]
1168  //
1169  //     -- a pointer to member expressed as described in 5.3.1.
1170  QualifiedDeclRefExpr *DRE = 0;
1171
1172  // Ignore (and complain about) any excess parentheses.
1173  while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
1174    if (!Invalid) {
1175      Diag(Arg->getSourceRange().getBegin(),
1176           diag::err_template_arg_extra_parens)
1177        << Arg->getSourceRange();
1178      Invalid = true;
1179    }
1180
1181    Arg = Parens->getSubExpr();
1182  }
1183
1184  if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg))
1185    if (UnOp->getOpcode() == UnaryOperator::AddrOf)
1186      DRE = dyn_cast<QualifiedDeclRefExpr>(UnOp->getSubExpr());
1187
1188  if (!DRE)
1189    return Diag(Arg->getSourceRange().getBegin(),
1190                diag::err_template_arg_not_pointer_to_member_form)
1191      << Arg->getSourceRange();
1192
1193  if (isa<FieldDecl>(DRE->getDecl()) || isa<CXXMethodDecl>(DRE->getDecl())) {
1194    assert((isa<FieldDecl>(DRE->getDecl()) ||
1195            !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
1196           "Only non-static member pointers can make it here");
1197
1198    // Okay: this is the address of a non-static member, and therefore
1199    // a member pointer constant.
1200    Member = DRE->getDecl();
1201    return Invalid;
1202  }
1203
1204  // We found something else, but we don't know specifically what it is.
1205  Diag(Arg->getSourceRange().getBegin(),
1206       diag::err_template_arg_not_pointer_to_member_form)
1207      << Arg->getSourceRange();
1208  Diag(DRE->getDecl()->getLocation(),
1209       diag::note_template_arg_refers_here);
1210  return true;
1211}
1212
1213/// \brief Check a template argument against its corresponding
1214/// non-type template parameter.
1215///
1216/// This routine implements the semantics of C++ [temp.arg.nontype].
1217/// It returns true if an error occurred, and false otherwise. \p
1218/// InstantiatedParamType is the type of the non-type template
1219/// parameter after it has been instantiated.
1220///
1221/// If Converted is non-NULL and no errors occur, the value
1222/// of this argument will be added to the end of the Converted vector.
1223bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
1224                                 QualType InstantiatedParamType, Expr *&Arg,
1225                         llvm::SmallVectorImpl<TemplateArgument> *Converted) {
1226  SourceLocation StartLoc = Arg->getSourceRange().getBegin();
1227
1228  // If either the parameter has a dependent type or the argument is
1229  // type-dependent, there's nothing we can check now.
1230  // FIXME: Add template argument to Converted!
1231  if (InstantiatedParamType->isDependentType() || Arg->isTypeDependent()) {
1232    // FIXME: Produce a cloned, canonical expression?
1233    Converted->push_back(TemplateArgument(Arg));
1234    return false;
1235  }
1236
1237  // C++ [temp.arg.nontype]p5:
1238  //   The following conversions are performed on each expression used
1239  //   as a non-type template-argument. If a non-type
1240  //   template-argument cannot be converted to the type of the
1241  //   corresponding template-parameter then the program is
1242  //   ill-formed.
1243  //
1244  //     -- for a non-type template-parameter of integral or
1245  //        enumeration type, integral promotions (4.5) and integral
1246  //        conversions (4.7) are applied.
1247  QualType ParamType = InstantiatedParamType;
1248  QualType ArgType = Arg->getType();
1249  if (ParamType->isIntegralType() || ParamType->isEnumeralType()) {
1250    // C++ [temp.arg.nontype]p1:
1251    //   A template-argument for a non-type, non-template
1252    //   template-parameter shall be one of:
1253    //
1254    //     -- an integral constant-expression of integral or enumeration
1255    //        type; or
1256    //     -- the name of a non-type template-parameter; or
1257    SourceLocation NonConstantLoc;
1258    llvm::APSInt Value;
1259    if (!ArgType->isIntegralType() && !ArgType->isEnumeralType()) {
1260      Diag(Arg->getSourceRange().getBegin(),
1261           diag::err_template_arg_not_integral_or_enumeral)
1262        << ArgType << Arg->getSourceRange();
1263      Diag(Param->getLocation(), diag::note_template_param_here);
1264      return true;
1265    } else if (!Arg->isValueDependent() &&
1266               !Arg->isIntegerConstantExpr(Value, Context, &NonConstantLoc)) {
1267      Diag(NonConstantLoc, diag::err_template_arg_not_ice)
1268        << ArgType << Arg->getSourceRange();
1269      return true;
1270    }
1271
1272    // FIXME: We need some way to more easily get the unqualified form
1273    // of the types without going all the way to the
1274    // canonical type.
1275    if (Context.getCanonicalType(ParamType).getCVRQualifiers())
1276      ParamType = Context.getCanonicalType(ParamType).getUnqualifiedType();
1277    if (Context.getCanonicalType(ArgType).getCVRQualifiers())
1278      ArgType = Context.getCanonicalType(ArgType).getUnqualifiedType();
1279
1280    // Try to convert the argument to the parameter's type.
1281    if (ParamType == ArgType) {
1282      // Okay: no conversion necessary
1283    } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
1284               !ParamType->isEnumeralType()) {
1285      // This is an integral promotion or conversion.
1286      ImpCastExprToType(Arg, ParamType);
1287    } else {
1288      // We can't perform this conversion.
1289      Diag(Arg->getSourceRange().getBegin(),
1290           diag::err_template_arg_not_convertible)
1291        << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
1292      Diag(Param->getLocation(), diag::note_template_param_here);
1293      return true;
1294    }
1295
1296    QualType IntegerType = Context.getCanonicalType(ParamType);
1297    if (const EnumType *Enum = IntegerType->getAsEnumType())
1298      IntegerType = Enum->getDecl()->getIntegerType();
1299
1300    if (!Arg->isValueDependent()) {
1301      // Check that an unsigned parameter does not receive a negative
1302      // value.
1303      if (IntegerType->isUnsignedIntegerType()
1304          && (Value.isSigned() && Value.isNegative())) {
1305        Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_negative)
1306          << Value.toString(10) << Param->getType()
1307          << Arg->getSourceRange();
1308        Diag(Param->getLocation(), diag::note_template_param_here);
1309        return true;
1310      }
1311
1312      // Check that we don't overflow the template parameter type.
1313      unsigned AllowedBits = Context.getTypeSize(IntegerType);
1314      if (Value.getActiveBits() > AllowedBits) {
1315        Diag(Arg->getSourceRange().getBegin(),
1316             diag::err_template_arg_too_large)
1317          << Value.toString(10) << Param->getType()
1318          << Arg->getSourceRange();
1319        Diag(Param->getLocation(), diag::note_template_param_here);
1320        return true;
1321      }
1322
1323      if (Value.getBitWidth() != AllowedBits)
1324        Value.extOrTrunc(AllowedBits);
1325      Value.setIsSigned(IntegerType->isSignedIntegerType());
1326    }
1327
1328    if (Converted) {
1329      // Add the value of this argument to the list of converted
1330      // arguments. We use the bitwidth and signedness of the template
1331      // parameter.
1332      if (Arg->isValueDependent()) {
1333        // The argument is value-dependent. Create a new
1334        // TemplateArgument with the converted expression.
1335        Converted->push_back(TemplateArgument(Arg));
1336        return false;
1337      }
1338
1339      Converted->push_back(TemplateArgument(StartLoc, Value,
1340                                   Context.getCanonicalType(IntegerType)));
1341    }
1342
1343    return false;
1344  }
1345
1346  // Handle pointer-to-function, reference-to-function, and
1347  // pointer-to-member-function all in (roughly) the same way.
1348  if (// -- For a non-type template-parameter of type pointer to
1349      //    function, only the function-to-pointer conversion (4.3) is
1350      //    applied. If the template-argument represents a set of
1351      //    overloaded functions (or a pointer to such), the matching
1352      //    function is selected from the set (13.4).
1353      (ParamType->isPointerType() &&
1354       ParamType->getAsPointerType()->getPointeeType()->isFunctionType()) ||
1355      // -- For a non-type template-parameter of type reference to
1356      //    function, no conversions apply. If the template-argument
1357      //    represents a set of overloaded functions, the matching
1358      //    function is selected from the set (13.4).
1359      (ParamType->isReferenceType() &&
1360       ParamType->getAsReferenceType()->getPointeeType()->isFunctionType()) ||
1361      // -- For a non-type template-parameter of type pointer to
1362      //    member function, no conversions apply. If the
1363      //    template-argument represents a set of overloaded member
1364      //    functions, the matching member function is selected from
1365      //    the set (13.4).
1366      (ParamType->isMemberPointerType() &&
1367       ParamType->getAsMemberPointerType()->getPointeeType()
1368         ->isFunctionType())) {
1369    if (Context.hasSameUnqualifiedType(ArgType,
1370                                       ParamType.getNonReferenceType())) {
1371      // We don't have to do anything: the types already match.
1372    } else if (ArgType->isFunctionType() && ParamType->isPointerType()) {
1373      ArgType = Context.getPointerType(ArgType);
1374      ImpCastExprToType(Arg, ArgType);
1375    } else if (FunctionDecl *Fn
1376                 = ResolveAddressOfOverloadedFunction(Arg, ParamType, true)) {
1377      if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
1378        return true;
1379
1380      FixOverloadedFunctionReference(Arg, Fn);
1381      ArgType = Arg->getType();
1382      if (ArgType->isFunctionType() && ParamType->isPointerType()) {
1383        ArgType = Context.getPointerType(Arg->getType());
1384        ImpCastExprToType(Arg, ArgType);
1385      }
1386    }
1387
1388    if (!Context.hasSameUnqualifiedType(ArgType,
1389                                        ParamType.getNonReferenceType())) {
1390      // We can't perform this conversion.
1391      Diag(Arg->getSourceRange().getBegin(),
1392           diag::err_template_arg_not_convertible)
1393        << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
1394      Diag(Param->getLocation(), diag::note_template_param_here);
1395      return true;
1396    }
1397
1398    if (ParamType->isMemberPointerType()) {
1399      NamedDecl *Member = 0;
1400      if (CheckTemplateArgumentPointerToMember(Arg, Member))
1401        return true;
1402
1403      if (Converted)
1404        Converted->push_back(TemplateArgument(StartLoc, Member));
1405
1406      return false;
1407    }
1408
1409    NamedDecl *Entity = 0;
1410    if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
1411      return true;
1412
1413    if (Converted)
1414      Converted->push_back(TemplateArgument(StartLoc, Entity));
1415    return false;
1416  }
1417
1418  if (ParamType->isPointerType()) {
1419    //   -- for a non-type template-parameter of type pointer to
1420    //      object, qualification conversions (4.4) and the
1421    //      array-to-pointer conversion (4.2) are applied.
1422    assert(ParamType->getAsPointerType()->getPointeeType()->isObjectType() &&
1423           "Only object pointers allowed here");
1424
1425    if (ArgType->isArrayType()) {
1426      ArgType = Context.getArrayDecayedType(ArgType);
1427      ImpCastExprToType(Arg, ArgType);
1428    }
1429
1430    if (IsQualificationConversion(ArgType, ParamType)) {
1431      ArgType = ParamType;
1432      ImpCastExprToType(Arg, ParamType);
1433    }
1434
1435    if (!Context.hasSameUnqualifiedType(ArgType, ParamType)) {
1436      // We can't perform this conversion.
1437      Diag(Arg->getSourceRange().getBegin(),
1438           diag::err_template_arg_not_convertible)
1439        << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
1440      Diag(Param->getLocation(), diag::note_template_param_here);
1441      return true;
1442    }
1443
1444    NamedDecl *Entity = 0;
1445    if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
1446      return true;
1447
1448    if (Converted)
1449      Converted->push_back(TemplateArgument(StartLoc, Entity));
1450
1451    return false;
1452  }
1453
1454  if (const ReferenceType *ParamRefType = ParamType->getAsReferenceType()) {
1455    //   -- For a non-type template-parameter of type reference to
1456    //      object, no conversions apply. The type referred to by the
1457    //      reference may be more cv-qualified than the (otherwise
1458    //      identical) type of the template-argument. The
1459    //      template-parameter is bound directly to the
1460    //      template-argument, which must be an lvalue.
1461    assert(ParamRefType->getPointeeType()->isObjectType() &&
1462           "Only object references allowed here");
1463
1464    if (!Context.hasSameUnqualifiedType(ParamRefType->getPointeeType(), ArgType)) {
1465      Diag(Arg->getSourceRange().getBegin(),
1466           diag::err_template_arg_no_ref_bind)
1467        << InstantiatedParamType << Arg->getType()
1468        << Arg->getSourceRange();
1469      Diag(Param->getLocation(), diag::note_template_param_here);
1470      return true;
1471    }
1472
1473    unsigned ParamQuals
1474      = Context.getCanonicalType(ParamType).getCVRQualifiers();
1475    unsigned ArgQuals = Context.getCanonicalType(ArgType).getCVRQualifiers();
1476
1477    if ((ParamQuals | ArgQuals) != ParamQuals) {
1478      Diag(Arg->getSourceRange().getBegin(),
1479           diag::err_template_arg_ref_bind_ignores_quals)
1480        << InstantiatedParamType << Arg->getType()
1481        << Arg->getSourceRange();
1482      Diag(Param->getLocation(), diag::note_template_param_here);
1483      return true;
1484    }
1485
1486    NamedDecl *Entity = 0;
1487    if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
1488      return true;
1489
1490    if (Converted)
1491      Converted->push_back(TemplateArgument(StartLoc, Entity));
1492
1493    return false;
1494  }
1495
1496  //     -- For a non-type template-parameter of type pointer to data
1497  //        member, qualification conversions (4.4) are applied.
1498  assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
1499
1500  if (Context.hasSameUnqualifiedType(ParamType, ArgType)) {
1501    // Types match exactly: nothing more to do here.
1502  } else if (IsQualificationConversion(ArgType, ParamType)) {
1503    ImpCastExprToType(Arg, ParamType);
1504  } else {
1505    // We can't perform this conversion.
1506    Diag(Arg->getSourceRange().getBegin(),
1507         diag::err_template_arg_not_convertible)
1508      << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
1509    Diag(Param->getLocation(), diag::note_template_param_here);
1510    return true;
1511  }
1512
1513  NamedDecl *Member = 0;
1514  if (CheckTemplateArgumentPointerToMember(Arg, Member))
1515    return true;
1516
1517  if (Converted)
1518    Converted->push_back(TemplateArgument(StartLoc, Member));
1519
1520  return false;
1521}
1522
1523/// \brief Check a template argument against its corresponding
1524/// template template parameter.
1525///
1526/// This routine implements the semantics of C++ [temp.arg.template].
1527/// It returns true if an error occurred, and false otherwise.
1528bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
1529                                 DeclRefExpr *Arg) {
1530  assert(isa<TemplateDecl>(Arg->getDecl()) && "Only template decls allowed");
1531  TemplateDecl *Template = cast<TemplateDecl>(Arg->getDecl());
1532
1533  // C++ [temp.arg.template]p1:
1534  //   A template-argument for a template template-parameter shall be
1535  //   the name of a class template, expressed as id-expression. Only
1536  //   primary class templates are considered when matching the
1537  //   template template argument with the corresponding parameter;
1538  //   partial specializations are not considered even if their
1539  //   parameter lists match that of the template template parameter.
1540  if (!isa<ClassTemplateDecl>(Template)) {
1541    assert(isa<FunctionTemplateDecl>(Template) &&
1542           "Only function templates are possible here");
1543    Diag(Arg->getSourceRange().getBegin(),
1544         diag::note_template_arg_refers_here_func)
1545      << Template;
1546  }
1547
1548  return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
1549                                         Param->getTemplateParameters(),
1550                                         true, true,
1551                                         Arg->getSourceRange().getBegin());
1552}
1553
1554/// \brief Determine whether the given template parameter lists are
1555/// equivalent.
1556///
1557/// \param New  The new template parameter list, typically written in the
1558/// source code as part of a new template declaration.
1559///
1560/// \param Old  The old template parameter list, typically found via
1561/// name lookup of the template declared with this template parameter
1562/// list.
1563///
1564/// \param Complain  If true, this routine will produce a diagnostic if
1565/// the template parameter lists are not equivalent.
1566///
1567/// \param IsTemplateTemplateParm  If true, this routine is being
1568/// called to compare the template parameter lists of a template
1569/// template parameter.
1570///
1571/// \param TemplateArgLoc If this source location is valid, then we
1572/// are actually checking the template parameter list of a template
1573/// argument (New) against the template parameter list of its
1574/// corresponding template template parameter (Old). We produce
1575/// slightly different diagnostics in this scenario.
1576///
1577/// \returns True if the template parameter lists are equal, false
1578/// otherwise.
1579bool
1580Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
1581                                     TemplateParameterList *Old,
1582                                     bool Complain,
1583                                     bool IsTemplateTemplateParm,
1584                                     SourceLocation TemplateArgLoc) {
1585  if (Old->size() != New->size()) {
1586    if (Complain) {
1587      unsigned NextDiag = diag::err_template_param_list_different_arity;
1588      if (TemplateArgLoc.isValid()) {
1589        Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
1590        NextDiag = diag::note_template_param_list_different_arity;
1591      }
1592      Diag(New->getTemplateLoc(), NextDiag)
1593          << (New->size() > Old->size())
1594          << IsTemplateTemplateParm
1595          << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
1596      Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
1597        << IsTemplateTemplateParm
1598        << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
1599    }
1600
1601    return false;
1602  }
1603
1604  for (TemplateParameterList::iterator OldParm = Old->begin(),
1605         OldParmEnd = Old->end(), NewParm = New->begin();
1606       OldParm != OldParmEnd; ++OldParm, ++NewParm) {
1607    if ((*OldParm)->getKind() != (*NewParm)->getKind()) {
1608      unsigned NextDiag = diag::err_template_param_different_kind;
1609      if (TemplateArgLoc.isValid()) {
1610        Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
1611        NextDiag = diag::note_template_param_different_kind;
1612      }
1613      Diag((*NewParm)->getLocation(), NextDiag)
1614        << IsTemplateTemplateParm;
1615      Diag((*OldParm)->getLocation(), diag::note_template_prev_declaration)
1616        << IsTemplateTemplateParm;
1617      return false;
1618    }
1619
1620    if (isa<TemplateTypeParmDecl>(*OldParm)) {
1621      // Okay; all template type parameters are equivalent (since we
1622      // know we're at the same index).
1623#if 0
1624      // FIXME: Enable this code in debug mode *after* we properly go
1625      // through and "instantiate" the template parameter lists of
1626      // template template parameters. It's only after this
1627      // instantiation that (1) any dependent types within the
1628      // template parameter list of the template template parameter
1629      // can be checked, and (2) the template type parameter depths
1630      // will match up.
1631      QualType OldParmType
1632        = Context.getTypeDeclType(cast<TemplateTypeParmDecl>(*OldParm));
1633      QualType NewParmType
1634        = Context.getTypeDeclType(cast<TemplateTypeParmDecl>(*NewParm));
1635      assert(Context.getCanonicalType(OldParmType) ==
1636             Context.getCanonicalType(NewParmType) &&
1637             "type parameter mismatch?");
1638#endif
1639    } else if (NonTypeTemplateParmDecl *OldNTTP
1640                 = dyn_cast<NonTypeTemplateParmDecl>(*OldParm)) {
1641      // The types of non-type template parameters must agree.
1642      NonTypeTemplateParmDecl *NewNTTP
1643        = cast<NonTypeTemplateParmDecl>(*NewParm);
1644      if (Context.getCanonicalType(OldNTTP->getType()) !=
1645            Context.getCanonicalType(NewNTTP->getType())) {
1646        if (Complain) {
1647          unsigned NextDiag = diag::err_template_nontype_parm_different_type;
1648          if (TemplateArgLoc.isValid()) {
1649            Diag(TemplateArgLoc,
1650                 diag::err_template_arg_template_params_mismatch);
1651            NextDiag = diag::note_template_nontype_parm_different_type;
1652          }
1653          Diag(NewNTTP->getLocation(), NextDiag)
1654            << NewNTTP->getType()
1655            << IsTemplateTemplateParm;
1656          Diag(OldNTTP->getLocation(),
1657               diag::note_template_nontype_parm_prev_declaration)
1658            << OldNTTP->getType();
1659        }
1660        return false;
1661      }
1662    } else {
1663      // The template parameter lists of template template
1664      // parameters must agree.
1665      // FIXME: Could we perform a faster "type" comparison here?
1666      assert(isa<TemplateTemplateParmDecl>(*OldParm) &&
1667             "Only template template parameters handled here");
1668      TemplateTemplateParmDecl *OldTTP
1669        = cast<TemplateTemplateParmDecl>(*OldParm);
1670      TemplateTemplateParmDecl *NewTTP
1671        = cast<TemplateTemplateParmDecl>(*NewParm);
1672      if (!TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
1673                                          OldTTP->getTemplateParameters(),
1674                                          Complain,
1675                                          /*IsTemplateTemplateParm=*/true,
1676                                          TemplateArgLoc))
1677        return false;
1678    }
1679  }
1680
1681  return true;
1682}
1683
1684/// \brief Check whether a template can be declared within this scope.
1685///
1686/// If the template declaration is valid in this scope, returns
1687/// false. Otherwise, issues a diagnostic and returns true.
1688bool
1689Sema::CheckTemplateDeclScope(Scope *S,
1690                             MultiTemplateParamsArg &TemplateParameterLists) {
1691  assert(TemplateParameterLists.size() > 0 && "Not a template");
1692
1693  // Find the nearest enclosing declaration scope.
1694  while ((S->getFlags() & Scope::DeclScope) == 0 ||
1695         (S->getFlags() & Scope::TemplateParamScope) != 0)
1696    S = S->getParent();
1697
1698  TemplateParameterList *TemplateParams =
1699    static_cast<TemplateParameterList*>(*TemplateParameterLists.get());
1700  SourceLocation TemplateLoc = TemplateParams->getTemplateLoc();
1701  SourceRange TemplateRange
1702    = SourceRange(TemplateLoc, TemplateParams->getRAngleLoc());
1703
1704  // C++ [temp]p2:
1705  //   A template-declaration can appear only as a namespace scope or
1706  //   class scope declaration.
1707  DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
1708  while (Ctx && isa<LinkageSpecDecl>(Ctx)) {
1709    if (cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx)
1710      return Diag(TemplateLoc, diag::err_template_linkage)
1711        << TemplateRange;
1712
1713    Ctx = Ctx->getParent();
1714  }
1715
1716  if (Ctx && (Ctx->isFileContext() || Ctx->isRecord()))
1717    return false;
1718
1719  return Diag(TemplateLoc, diag::err_template_outside_namespace_or_class_scope)
1720    << TemplateRange;
1721}
1722
1723/// \brief Check whether a class template specialization in the
1724/// current context is well-formed.
1725///
1726/// This routine determines whether a class template specialization
1727/// can be declared in the current context (C++ [temp.expl.spec]p2)
1728/// and emits appropriate diagnostics if there was an error. It
1729/// returns true if there was an error that we cannot recover from,
1730/// and false otherwise.
1731bool
1732Sema::CheckClassTemplateSpecializationScope(ClassTemplateDecl *ClassTemplate,
1733                                   ClassTemplateSpecializationDecl *PrevDecl,
1734                                            SourceLocation TemplateNameLoc,
1735                                            SourceRange ScopeSpecifierRange) {
1736  // C++ [temp.expl.spec]p2:
1737  //   An explicit specialization shall be declared in the namespace
1738  //   of which the template is a member, or, for member templates, in
1739  //   the namespace of which the enclosing class or enclosing class
1740  //   template is a member. An explicit specialization of a member
1741  //   function, member class or static data member of a class
1742  //   template shall be declared in the namespace of which the class
1743  //   template is a member. Such a declaration may also be a
1744  //   definition. If the declaration is not a definition, the
1745  //   specialization may be defined later in the name- space in which
1746  //   the explicit specialization was declared, or in a namespace
1747  //   that encloses the one in which the explicit specialization was
1748  //   declared.
1749  if (CurContext->getLookupContext()->isFunctionOrMethod()) {
1750    Diag(TemplateNameLoc, diag::err_template_spec_decl_function_scope)
1751      << ClassTemplate;
1752    return true;
1753  }
1754
1755  DeclContext *DC = CurContext->getEnclosingNamespaceContext();
1756  DeclContext *TemplateContext
1757    = ClassTemplate->getDeclContext()->getEnclosingNamespaceContext();
1758  if (!PrevDecl || PrevDecl->getSpecializationKind() == TSK_Undeclared) {
1759    // There is no prior declaration of this entity, so this
1760    // specialization must be in the same context as the template
1761    // itself.
1762    if (DC != TemplateContext) {
1763      if (isa<TranslationUnitDecl>(TemplateContext))
1764        Diag(TemplateNameLoc, diag::err_template_spec_decl_out_of_scope_global)
1765          << ClassTemplate << ScopeSpecifierRange;
1766      else if (isa<NamespaceDecl>(TemplateContext))
1767        Diag(TemplateNameLoc, diag::err_template_spec_decl_out_of_scope)
1768          << ClassTemplate << cast<NamedDecl>(TemplateContext)
1769          << ScopeSpecifierRange;
1770
1771      Diag(ClassTemplate->getLocation(), diag::note_template_decl_here);
1772    }
1773
1774    return false;
1775  }
1776
1777  // We have a previous declaration of this entity. Make sure that
1778  // this redeclaration (or definition) occurs in an enclosing namespace.
1779  if (!CurContext->Encloses(TemplateContext)) {
1780    if (isa<TranslationUnitDecl>(TemplateContext))
1781      Diag(TemplateNameLoc, diag::err_template_spec_redecl_global_scope)
1782        << ClassTemplate << ScopeSpecifierRange;
1783    else if (isa<NamespaceDecl>(TemplateContext))
1784      Diag(TemplateNameLoc, diag::err_template_spec_redecl_out_of_scope)
1785        << ClassTemplate << cast<NamedDecl>(TemplateContext)
1786        << ScopeSpecifierRange;
1787
1788    Diag(ClassTemplate->getLocation(), diag::note_template_decl_here);
1789  }
1790
1791  return false;
1792}
1793
1794Sema::DeclResult
1795Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec, TagKind TK,
1796                                       SourceLocation KWLoc,
1797                                       const CXXScopeSpec &SS,
1798                                       DeclTy *TemplateD,
1799                                       SourceLocation TemplateNameLoc,
1800                                       SourceLocation LAngleLoc,
1801                                       ASTTemplateArgsPtr TemplateArgsIn,
1802                                       SourceLocation *TemplateArgLocs,
1803                                       SourceLocation RAngleLoc,
1804                                       AttributeList *Attr,
1805                               MultiTemplateParamsArg TemplateParameterLists) {
1806  // Find the class template we're specializing
1807  ClassTemplateDecl *ClassTemplate
1808    = dyn_cast_or_null<ClassTemplateDecl>(static_cast<Decl *>(TemplateD));
1809  if (!ClassTemplate)
1810    return true;
1811
1812  // Check the validity of the template headers that introduce this
1813  // template.
1814  // FIXME: Once we have member templates, we'll need to check
1815  // C++ [temp.expl.spec]p17-18, where we could have multiple levels of
1816  // template<> headers.
1817  if (TemplateParameterLists.size() == 0)
1818    Diag(KWLoc, diag::err_template_spec_needs_header)
1819      << CodeModificationHint::CreateInsertion(KWLoc, "template<> ");
1820  else {
1821    TemplateParameterList *TemplateParams
1822      = static_cast<TemplateParameterList*>(*TemplateParameterLists.get());
1823    if (TemplateParameterLists.size() > 1)
1824      return Diag(TemplateParams->getTemplateLoc(),
1825                  diag::err_template_spec_extra_headers);
1826
1827    if (TemplateParams->size() > 0)
1828      // FIXME: No support for class template partial specialization.
1829      return Diag(TemplateParams->getTemplateLoc(),
1830                  diag::unsup_template_partial_spec);
1831  }
1832
1833  // Check that the specialization uses the same tag kind as the
1834  // original template.
1835  TagDecl::TagKind Kind;
1836  switch (TagSpec) {
1837  default: assert(0 && "Unknown tag type!");
1838  case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
1839  case DeclSpec::TST_union:  Kind = TagDecl::TK_union; break;
1840  case DeclSpec::TST_class:  Kind = TagDecl::TK_class; break;
1841  }
1842  if (ClassTemplate->getTemplatedDecl()->getTagKind() != Kind) {
1843    Diag(KWLoc, diag::err_use_with_wrong_tag) << ClassTemplate;
1844    Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
1845         diag::note_previous_use);
1846    Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
1847  }
1848
1849  // Translate the parser's template argument list in our AST format.
1850  llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
1851  translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
1852
1853  // Check that the template argument list is well-formed for this
1854  // template.
1855  llvm::SmallVector<TemplateArgument, 16> ConvertedTemplateArgs;
1856  if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, LAngleLoc,
1857                                &TemplateArgs[0], TemplateArgs.size(),
1858                                RAngleLoc, ConvertedTemplateArgs))
1859    return true;
1860
1861  assert((ConvertedTemplateArgs.size() ==
1862            ClassTemplate->getTemplateParameters()->size()) &&
1863         "Converted template argument list is too short!");
1864
1865  // Find the class template specialization declaration that
1866  // corresponds to these arguments.
1867  llvm::FoldingSetNodeID ID;
1868  ClassTemplateSpecializationDecl::Profile(ID, &ConvertedTemplateArgs[0],
1869                                           ConvertedTemplateArgs.size());
1870  void *InsertPos = 0;
1871  ClassTemplateSpecializationDecl *PrevDecl
1872    = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
1873
1874  ClassTemplateSpecializationDecl *Specialization = 0;
1875
1876  // Check whether we can declare a class template specialization in
1877  // the current scope.
1878  if (CheckClassTemplateSpecializationScope(ClassTemplate, PrevDecl,
1879                                            TemplateNameLoc,
1880                                            SS.getRange()))
1881    return true;
1882
1883  if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
1884    // Since the only prior class template specialization with these
1885    // arguments was referenced but not declared, reuse that
1886    // declaration node as our own, updating its source location to
1887    // reflect our new declaration.
1888    Specialization = PrevDecl;
1889    Specialization->setLocation(TemplateNameLoc);
1890    PrevDecl = 0;
1891  } else {
1892    // Create a new class template specialization declaration node for
1893    // this explicit specialization.
1894    Specialization
1895      = ClassTemplateSpecializationDecl::Create(Context,
1896                                             ClassTemplate->getDeclContext(),
1897                                                TemplateNameLoc,
1898                                                ClassTemplate,
1899                                                &ConvertedTemplateArgs[0],
1900                                                ConvertedTemplateArgs.size(),
1901                                                PrevDecl);
1902
1903    if (PrevDecl) {
1904      ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
1905      ClassTemplate->getSpecializations().GetOrInsertNode(Specialization);
1906    } else {
1907      ClassTemplate->getSpecializations().InsertNode(Specialization,
1908                                                     InsertPos);
1909    }
1910  }
1911
1912  // Note that this is an explicit specialization.
1913  Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
1914
1915  // Check that this isn't a redefinition of this specialization.
1916  if (TK == TK_Definition) {
1917    if (RecordDecl *Def = Specialization->getDefinition(Context)) {
1918      // FIXME: Should also handle explicit specialization after
1919      // implicit instantiation with a special diagnostic.
1920      SourceRange Range(TemplateNameLoc, RAngleLoc);
1921      Diag(TemplateNameLoc, diag::err_redefinition)
1922        << Specialization << Range;
1923      Diag(Def->getLocation(), diag::note_previous_definition);
1924      Specialization->setInvalidDecl();
1925      return true;
1926    }
1927  }
1928
1929  // Build the fully-sugared type for this class template
1930  // specialization as the user wrote in the specialization
1931  // itself. This means that we'll pretty-print the type retrieved
1932  // from the specialization's declaration the way that the user
1933  // actually wrote the specialization, rather than formatting the
1934  // name based on the "canonical" representation used to store the
1935  // template arguments in the specialization.
1936  QualType WrittenTy
1937    = Context.getClassTemplateSpecializationType(ClassTemplate,
1938                                                 &TemplateArgs[0],
1939                                                 TemplateArgs.size(),
1940                                  Context.getTypeDeclType(Specialization));
1941  Specialization->setTypeAsWritten(getQualifiedNameType(SS, WrittenTy));
1942  TemplateArgsIn.release();
1943
1944  // C++ [temp.expl.spec]p9:
1945  //   A template explicit specialization is in the scope of the
1946  //   namespace in which the template was defined.
1947  //
1948  // We actually implement this paragraph where we set the semantic
1949  // context (in the creation of the ClassTemplateSpecializationDecl),
1950  // but we also maintain the lexical context where the actual
1951  // definition occurs.
1952  Specialization->setLexicalDeclContext(CurContext);
1953
1954  // We may be starting the definition of this specialization.
1955  if (TK == TK_Definition)
1956    Specialization->startDefinition();
1957
1958  // Add the specialization into its lexical context, so that it can
1959  // be seen when iterating through the list of declarations in that
1960  // context. However, specializations are not found by name lookup.
1961  CurContext->addDecl(Specialization);
1962  return Specialization;
1963}
1964