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