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