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