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