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