SemaTemplate.cpp revision 1afa611e36e0ab23dd3cde4bbe5aa74ceb7d77c5
1//===------- SemaTemplate.cpp - Semantic Analysis for C++ Templates -------===/
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//===----------------------------------------------------------------------===/
8//
9//  This file implements semantic analysis for C++ templates.
10//===----------------------------------------------------------------------===/
11
12#include "TreeTransform.h"
13#include "clang/AST/ASTContext.h"
14#include "clang/AST/DeclFriend.h"
15#include "clang/AST/DeclTemplate.h"
16#include "clang/AST/Expr.h"
17#include "clang/AST/ExprCXX.h"
18#include "clang/AST/RecursiveASTVisitor.h"
19#include "clang/AST/TypeVisitor.h"
20#include "clang/Basic/LangOptions.h"
21#include "clang/Basic/PartialDiagnostic.h"
22#include "clang/Sema/DeclSpec.h"
23#include "clang/Sema/Lookup.h"
24#include "clang/Sema/ParsedTemplate.h"
25#include "clang/Sema/Scope.h"
26#include "clang/Sema/SemaInternal.h"
27#include "clang/Sema/Template.h"
28#include "clang/Sema/TemplateDeduction.h"
29#include "llvm/ADT/SmallBitVector.h"
30#include "llvm/ADT/SmallString.h"
31#include "llvm/ADT/StringExtras.h"
32using namespace clang;
33using namespace sema;
34
35// Exported for use by Parser.
36SourceRange
37clang::getTemplateParamsRange(TemplateParameterList const * const *Ps,
38                              unsigned N) {
39  if (!N) return SourceRange();
40  return SourceRange(Ps[0]->getTemplateLoc(), Ps[N-1]->getRAngleLoc());
41}
42
43/// \brief Determine whether the declaration found is acceptable as the name
44/// of a template and, if so, return that template declaration. Otherwise,
45/// returns NULL.
46static NamedDecl *isAcceptableTemplateName(ASTContext &Context,
47                                           NamedDecl *Orig,
48                                           bool AllowFunctionTemplates) {
49  NamedDecl *D = Orig->getUnderlyingDecl();
50
51  if (isa<TemplateDecl>(D)) {
52    if (!AllowFunctionTemplates && isa<FunctionTemplateDecl>(D))
53      return 0;
54
55    return Orig;
56  }
57
58  if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
59    // C++ [temp.local]p1:
60    //   Like normal (non-template) classes, class templates have an
61    //   injected-class-name (Clause 9). The injected-class-name
62    //   can be used with or without a template-argument-list. When
63    //   it is used without a template-argument-list, it is
64    //   equivalent to the injected-class-name followed by the
65    //   template-parameters of the class template enclosed in
66    //   <>. When it is used with a template-argument-list, it
67    //   refers to the specified class template specialization,
68    //   which could be the current specialization or another
69    //   specialization.
70    if (Record->isInjectedClassName()) {
71      Record = cast<CXXRecordDecl>(Record->getDeclContext());
72      if (Record->getDescribedClassTemplate())
73        return Record->getDescribedClassTemplate();
74
75      if (ClassTemplateSpecializationDecl *Spec
76            = dyn_cast<ClassTemplateSpecializationDecl>(Record))
77        return Spec->getSpecializedTemplate();
78    }
79
80    return 0;
81  }
82
83  return 0;
84}
85
86void Sema::FilterAcceptableTemplateNames(LookupResult &R,
87                                         bool AllowFunctionTemplates) {
88  // The set of class templates we've already seen.
89  llvm::SmallPtrSet<ClassTemplateDecl *, 8> ClassTemplates;
90  LookupResult::Filter filter = R.makeFilter();
91  while (filter.hasNext()) {
92    NamedDecl *Orig = filter.next();
93    NamedDecl *Repl = isAcceptableTemplateName(Context, Orig,
94                                               AllowFunctionTemplates);
95    if (!Repl)
96      filter.erase();
97    else if (Repl != Orig) {
98
99      // C++ [temp.local]p3:
100      //   A lookup that finds an injected-class-name (10.2) can result in an
101      //   ambiguity in certain cases (for example, if it is found in more than
102      //   one base class). If all of the injected-class-names that are found
103      //   refer to specializations of the same class template, and if the name
104      //   is used as a template-name, the reference refers to the class
105      //   template itself and not a specialization thereof, and is not
106      //   ambiguous.
107      if (ClassTemplateDecl *ClassTmpl = dyn_cast<ClassTemplateDecl>(Repl))
108        if (!ClassTemplates.insert(ClassTmpl)) {
109          filter.erase();
110          continue;
111        }
112
113      // FIXME: we promote access to public here as a workaround to
114      // the fact that LookupResult doesn't let us remember that we
115      // found this template through a particular injected class name,
116      // which means we end up doing nasty things to the invariants.
117      // Pretending that access is public is *much* safer.
118      filter.replace(Repl, AS_public);
119    }
120  }
121  filter.done();
122}
123
124bool Sema::hasAnyAcceptableTemplateNames(LookupResult &R,
125                                         bool AllowFunctionTemplates) {
126  for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I)
127    if (isAcceptableTemplateName(Context, *I, AllowFunctionTemplates))
128      return true;
129
130  return false;
131}
132
133TemplateNameKind Sema::isTemplateName(Scope *S,
134                                      CXXScopeSpec &SS,
135                                      bool hasTemplateKeyword,
136                                      UnqualifiedId &Name,
137                                      ParsedType ObjectTypePtr,
138                                      bool EnteringContext,
139                                      TemplateTy &TemplateResult,
140                                      bool &MemberOfUnknownSpecialization) {
141  assert(getLangOpts().CPlusPlus && "No template names in C!");
142
143  DeclarationName TName;
144  MemberOfUnknownSpecialization = false;
145
146  switch (Name.getKind()) {
147  case UnqualifiedId::IK_Identifier:
148    TName = DeclarationName(Name.Identifier);
149    break;
150
151  case UnqualifiedId::IK_OperatorFunctionId:
152    TName = Context.DeclarationNames.getCXXOperatorName(
153                                              Name.OperatorFunctionId.Operator);
154    break;
155
156  case UnqualifiedId::IK_LiteralOperatorId:
157    TName = Context.DeclarationNames.getCXXLiteralOperatorName(Name.Identifier);
158    break;
159
160  default:
161    return TNK_Non_template;
162  }
163
164  QualType ObjectType = ObjectTypePtr.get();
165
166  LookupResult R(*this, TName, Name.getLocStart(), LookupOrdinaryName);
167  LookupTemplateName(R, S, SS, ObjectType, EnteringContext,
168                     MemberOfUnknownSpecialization);
169  if (R.empty()) return TNK_Non_template;
170  if (R.isAmbiguous()) {
171    // Suppress diagnostics;  we'll redo this lookup later.
172    R.suppressDiagnostics();
173
174    // FIXME: we might have ambiguous templates, in which case we
175    // should at least parse them properly!
176    return TNK_Non_template;
177  }
178
179  TemplateName Template;
180  TemplateNameKind TemplateKind;
181
182  unsigned ResultCount = R.end() - R.begin();
183  if (ResultCount > 1) {
184    // We assume that we'll preserve the qualifier from a function
185    // template name in other ways.
186    Template = Context.getOverloadedTemplateName(R.begin(), R.end());
187    TemplateKind = TNK_Function_template;
188
189    // We'll do this lookup again later.
190    R.suppressDiagnostics();
191  } else {
192    TemplateDecl *TD = cast<TemplateDecl>((*R.begin())->getUnderlyingDecl());
193
194    if (SS.isSet() && !SS.isInvalid()) {
195      NestedNameSpecifier *Qualifier
196        = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
197      Template = Context.getQualifiedTemplateName(Qualifier,
198                                                  hasTemplateKeyword, TD);
199    } else {
200      Template = TemplateName(TD);
201    }
202
203    if (isa<FunctionTemplateDecl>(TD)) {
204      TemplateKind = TNK_Function_template;
205
206      // We'll do this lookup again later.
207      R.suppressDiagnostics();
208    } else {
209      assert(isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD) ||
210             isa<TypeAliasTemplateDecl>(TD));
211      TemplateKind = TNK_Type_template;
212    }
213  }
214
215  TemplateResult = TemplateTy::make(Template);
216  return TemplateKind;
217}
218
219bool Sema::DiagnoseUnknownTemplateName(const IdentifierInfo &II,
220                                       SourceLocation IILoc,
221                                       Scope *S,
222                                       const CXXScopeSpec *SS,
223                                       TemplateTy &SuggestedTemplate,
224                                       TemplateNameKind &SuggestedKind) {
225  // We can't recover unless there's a dependent scope specifier preceding the
226  // template name.
227  // FIXME: Typo correction?
228  if (!SS || !SS->isSet() || !isDependentScopeSpecifier(*SS) ||
229      computeDeclContext(*SS))
230    return false;
231
232  // The code is missing a 'template' keyword prior to the dependent template
233  // name.
234  NestedNameSpecifier *Qualifier = (NestedNameSpecifier*)SS->getScopeRep();
235  Diag(IILoc, diag::err_template_kw_missing)
236    << Qualifier << II.getName()
237    << FixItHint::CreateInsertion(IILoc, "template ");
238  SuggestedTemplate
239    = TemplateTy::make(Context.getDependentTemplateName(Qualifier, &II));
240  SuggestedKind = TNK_Dependent_template_name;
241  return true;
242}
243
244void Sema::LookupTemplateName(LookupResult &Found,
245                              Scope *S, CXXScopeSpec &SS,
246                              QualType ObjectType,
247                              bool EnteringContext,
248                              bool &MemberOfUnknownSpecialization) {
249  // Determine where to perform name lookup
250  MemberOfUnknownSpecialization = false;
251  DeclContext *LookupCtx = 0;
252  bool isDependent = false;
253  if (!ObjectType.isNull()) {
254    // This nested-name-specifier occurs in a member access expression, e.g.,
255    // x->B::f, and we are looking into the type of the object.
256    assert(!SS.isSet() && "ObjectType and scope specifier cannot coexist");
257    LookupCtx = computeDeclContext(ObjectType);
258    isDependent = ObjectType->isDependentType();
259    assert((isDependent || !ObjectType->isIncompleteType() ||
260            ObjectType->castAs<TagType>()->isBeingDefined()) &&
261           "Caller should have completed object type");
262
263    // Template names cannot appear inside an Objective-C class or object type.
264    if (ObjectType->isObjCObjectOrInterfaceType()) {
265      Found.clear();
266      return;
267    }
268  } else if (SS.isSet()) {
269    // This nested-name-specifier occurs after another nested-name-specifier,
270    // so long into the context associated with the prior nested-name-specifier.
271    LookupCtx = computeDeclContext(SS, EnteringContext);
272    isDependent = isDependentScopeSpecifier(SS);
273
274    // The declaration context must be complete.
275    if (LookupCtx && RequireCompleteDeclContext(SS, LookupCtx))
276      return;
277  }
278
279  bool ObjectTypeSearchedInScope = false;
280  bool AllowFunctionTemplatesInLookup = true;
281  if (LookupCtx) {
282    // Perform "qualified" name lookup into the declaration context we
283    // computed, which is either the type of the base of a member access
284    // expression or the declaration context associated with a prior
285    // nested-name-specifier.
286    LookupQualifiedName(Found, LookupCtx);
287    if (!ObjectType.isNull() && Found.empty()) {
288      // C++ [basic.lookup.classref]p1:
289      //   In a class member access expression (5.2.5), if the . or -> token is
290      //   immediately followed by an identifier followed by a <, the
291      //   identifier must be looked up to determine whether the < is the
292      //   beginning of a template argument list (14.2) or a less-than operator.
293      //   The identifier is first looked up in the class of the object
294      //   expression. If the identifier is not found, it is then looked up in
295      //   the context of the entire postfix-expression and shall name a class
296      //   or function template.
297      if (S) LookupName(Found, S);
298      ObjectTypeSearchedInScope = true;
299      AllowFunctionTemplatesInLookup = false;
300    }
301  } else if (isDependent && (!S || ObjectType.isNull())) {
302    // We cannot look into a dependent object type or nested nme
303    // specifier.
304    MemberOfUnknownSpecialization = true;
305    return;
306  } else {
307    // Perform unqualified name lookup in the current scope.
308    LookupName(Found, S);
309
310    if (!ObjectType.isNull())
311      AllowFunctionTemplatesInLookup = false;
312  }
313
314  if (Found.empty() && !isDependent) {
315    // If we did not find any names, attempt to correct any typos.
316    DeclarationName Name = Found.getLookupName();
317    Found.clear();
318    // Simple filter callback that, for keywords, only accepts the C++ *_cast
319    CorrectionCandidateCallback FilterCCC;
320    FilterCCC.WantTypeSpecifiers = false;
321    FilterCCC.WantExpressionKeywords = false;
322    FilterCCC.WantRemainingKeywords = false;
323    FilterCCC.WantCXXNamedCasts = true;
324    if (TypoCorrection Corrected = CorrectTypo(Found.getLookupNameInfo(),
325                                               Found.getLookupKind(), S, &SS,
326                                               FilterCCC, LookupCtx)) {
327      Found.setLookupName(Corrected.getCorrection());
328      if (Corrected.getCorrectionDecl())
329        Found.addDecl(Corrected.getCorrectionDecl());
330      FilterAcceptableTemplateNames(Found);
331      if (!Found.empty()) {
332        std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
333        std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOpts()));
334        if (LookupCtx) {
335          bool droppedSpecifier = Corrected.WillReplaceSpecifier() &&
336                                  Name.getAsString() == CorrectedStr;
337          Diag(Found.getNameLoc(), diag::err_no_member_template_suggest)
338            << Name << LookupCtx << droppedSpecifier << CorrectedQuotedStr
339            << SS.getRange()
340            << FixItHint::CreateReplacement(Corrected.getCorrectionRange(),
341                                            CorrectedStr);
342        } else {
343          Diag(Found.getNameLoc(), diag::err_no_template_suggest)
344            << Name << CorrectedQuotedStr
345            << FixItHint::CreateReplacement(Found.getNameLoc(), CorrectedStr);
346        }
347        if (TemplateDecl *Template = Found.getAsSingle<TemplateDecl>())
348          Diag(Template->getLocation(), diag::note_previous_decl)
349            << CorrectedQuotedStr;
350      }
351    } else {
352      Found.setLookupName(Name);
353    }
354  }
355
356  FilterAcceptableTemplateNames(Found, AllowFunctionTemplatesInLookup);
357  if (Found.empty()) {
358    if (isDependent)
359      MemberOfUnknownSpecialization = true;
360    return;
361  }
362
363  if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope &&
364      !(getLangOpts().CPlusPlus11 && !Found.empty())) {
365    // C++03 [basic.lookup.classref]p1:
366    //   [...] If the lookup in the class of the object expression finds a
367    //   template, the name is also looked up in the context of the entire
368    //   postfix-expression and [...]
369    //
370    // Note: C++11 does not perform this second lookup.
371    LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(),
372                            LookupOrdinaryName);
373    LookupName(FoundOuter, S);
374    FilterAcceptableTemplateNames(FoundOuter, /*AllowFunctionTemplates=*/false);
375
376    if (FoundOuter.empty()) {
377      //   - if the name is not found, the name found in the class of the
378      //     object expression is used, otherwise
379    } else if (!FoundOuter.getAsSingle<ClassTemplateDecl>() ||
380               FoundOuter.isAmbiguous()) {
381      //   - if the name is found in the context of the entire
382      //     postfix-expression and does not name a class template, the name
383      //     found in the class of the object expression is used, otherwise
384      FoundOuter.clear();
385    } else if (!Found.isSuppressingDiagnostics()) {
386      //   - if the name found is a class template, it must refer to the same
387      //     entity as the one found in the class of the object expression,
388      //     otherwise the program is ill-formed.
389      if (!Found.isSingleResult() ||
390          Found.getFoundDecl()->getCanonicalDecl()
391            != FoundOuter.getFoundDecl()->getCanonicalDecl()) {
392        Diag(Found.getNameLoc(),
393             diag::ext_nested_name_member_ref_lookup_ambiguous)
394          << Found.getLookupName()
395          << ObjectType;
396        Diag(Found.getRepresentativeDecl()->getLocation(),
397             diag::note_ambig_member_ref_object_type)
398          << ObjectType;
399        Diag(FoundOuter.getFoundDecl()->getLocation(),
400             diag::note_ambig_member_ref_scope);
401
402        // Recover by taking the template that we found in the object
403        // expression's type.
404      }
405    }
406  }
407}
408
409/// ActOnDependentIdExpression - Handle a dependent id-expression that
410/// was just parsed.  This is only possible with an explicit scope
411/// specifier naming a dependent type.
412ExprResult
413Sema::ActOnDependentIdExpression(const CXXScopeSpec &SS,
414                                 SourceLocation TemplateKWLoc,
415                                 const DeclarationNameInfo &NameInfo,
416                                 bool isAddressOfOperand,
417                           const TemplateArgumentListInfo *TemplateArgs) {
418  DeclContext *DC = getFunctionLevelDeclContext();
419
420  if (!isAddressOfOperand &&
421      isa<CXXMethodDecl>(DC) &&
422      cast<CXXMethodDecl>(DC)->isInstance()) {
423    QualType ThisType = cast<CXXMethodDecl>(DC)->getThisType(Context);
424
425    // Since the 'this' expression is synthesized, we don't need to
426    // perform the double-lookup check.
427    NamedDecl *FirstQualifierInScope = 0;
428
429    return Owned(CXXDependentScopeMemberExpr::Create(Context,
430                                                     /*This*/ 0, ThisType,
431                                                     /*IsArrow*/ true,
432                                                     /*Op*/ SourceLocation(),
433                                               SS.getWithLocInContext(Context),
434                                                     TemplateKWLoc,
435                                                     FirstQualifierInScope,
436                                                     NameInfo,
437                                                     TemplateArgs));
438  }
439
440  return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
441}
442
443ExprResult
444Sema::BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
445                                SourceLocation TemplateKWLoc,
446                                const DeclarationNameInfo &NameInfo,
447                                const TemplateArgumentListInfo *TemplateArgs) {
448  return Owned(DependentScopeDeclRefExpr::Create(Context,
449                                               SS.getWithLocInContext(Context),
450                                                 TemplateKWLoc,
451                                                 NameInfo,
452                                                 TemplateArgs));
453}
454
455/// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
456/// that the template parameter 'PrevDecl' is being shadowed by a new
457/// declaration at location Loc. Returns true to indicate that this is
458/// an error, and false otherwise.
459void Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
460  assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
461
462  // Microsoft Visual C++ permits template parameters to be shadowed.
463  if (getLangOpts().MicrosoftExt)
464    return;
465
466  // C++ [temp.local]p4:
467  //   A template-parameter shall not be redeclared within its
468  //   scope (including nested scopes).
469  Diag(Loc, diag::err_template_param_shadow)
470    << cast<NamedDecl>(PrevDecl)->getDeclName();
471  Diag(PrevDecl->getLocation(), diag::note_template_param_here);
472  return;
473}
474
475/// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
476/// the parameter D to reference the templated declaration and return a pointer
477/// to the template declaration. Otherwise, do nothing to D and return null.
478TemplateDecl *Sema::AdjustDeclIfTemplate(Decl *&D) {
479  if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D)) {
480    D = Temp->getTemplatedDecl();
481    return Temp;
482  }
483  return 0;
484}
485
486ParsedTemplateArgument ParsedTemplateArgument::getTemplatePackExpansion(
487                                             SourceLocation EllipsisLoc) const {
488  assert(Kind == Template &&
489         "Only template template arguments can be pack expansions here");
490  assert(getAsTemplate().get().containsUnexpandedParameterPack() &&
491         "Template template argument pack expansion without packs");
492  ParsedTemplateArgument Result(*this);
493  Result.EllipsisLoc = EllipsisLoc;
494  return Result;
495}
496
497static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef,
498                                            const ParsedTemplateArgument &Arg) {
499
500  switch (Arg.getKind()) {
501  case ParsedTemplateArgument::Type: {
502    TypeSourceInfo *DI;
503    QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI);
504    if (!DI)
505      DI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getLocation());
506    return TemplateArgumentLoc(TemplateArgument(T), DI);
507  }
508
509  case ParsedTemplateArgument::NonType: {
510    Expr *E = static_cast<Expr *>(Arg.getAsExpr());
511    return TemplateArgumentLoc(TemplateArgument(E), E);
512  }
513
514  case ParsedTemplateArgument::Template: {
515    TemplateName Template = Arg.getAsTemplate().get();
516    TemplateArgument TArg;
517    if (Arg.getEllipsisLoc().isValid())
518      TArg = TemplateArgument(Template, Optional<unsigned int>());
519    else
520      TArg = Template;
521    return TemplateArgumentLoc(TArg,
522                               Arg.getScopeSpec().getWithLocInContext(
523                                                              SemaRef.Context),
524                               Arg.getLocation(),
525                               Arg.getEllipsisLoc());
526  }
527  }
528
529  llvm_unreachable("Unhandled parsed template argument");
530}
531
532/// \brief Translates template arguments as provided by the parser
533/// into template arguments used by semantic analysis.
534void Sema::translateTemplateArguments(const ASTTemplateArgsPtr &TemplateArgsIn,
535                                      TemplateArgumentListInfo &TemplateArgs) {
536 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
537   TemplateArgs.addArgument(translateTemplateArgument(*this,
538                                                      TemplateArgsIn[I]));
539}
540
541static void maybeDiagnoseTemplateParameterShadow(Sema &SemaRef, Scope *S,
542                                                 SourceLocation Loc,
543                                                 IdentifierInfo *Name) {
544  NamedDecl *PrevDecl = SemaRef.LookupSingleName(
545      S, Name, Loc, Sema::LookupOrdinaryName, Sema::ForRedeclaration);
546  if (PrevDecl && PrevDecl->isTemplateParameter())
547    SemaRef.DiagnoseTemplateParameterShadow(Loc, PrevDecl);
548}
549
550/// ActOnTypeParameter - Called when a C++ template type parameter
551/// (e.g., "typename T") has been parsed. Typename specifies whether
552/// the keyword "typename" was used to declare the type parameter
553/// (otherwise, "class" was used), and KeyLoc is the location of the
554/// "class" or "typename" keyword. ParamName is the name of the
555/// parameter (NULL indicates an unnamed template parameter) and
556/// ParamNameLoc is the location of the parameter name (if any).
557/// If the type parameter has a default argument, it will be added
558/// later via ActOnTypeParameterDefault.
559Decl *Sema::ActOnTypeParameter(Scope *S, bool Typename, bool Ellipsis,
560                               SourceLocation EllipsisLoc,
561                               SourceLocation KeyLoc,
562                               IdentifierInfo *ParamName,
563                               SourceLocation ParamNameLoc,
564                               unsigned Depth, unsigned Position,
565                               SourceLocation EqualLoc,
566                               ParsedType DefaultArg) {
567  assert(S->isTemplateParamScope() &&
568         "Template type parameter not in template parameter scope!");
569  bool Invalid = false;
570
571  SourceLocation Loc = ParamNameLoc;
572  if (!ParamName)
573    Loc = KeyLoc;
574
575  TemplateTypeParmDecl *Param
576    = TemplateTypeParmDecl::Create(Context, Context.getTranslationUnitDecl(),
577                                   KeyLoc, Loc, Depth, Position, ParamName,
578                                   Typename, Ellipsis);
579  Param->setAccess(AS_public);
580  if (Invalid)
581    Param->setInvalidDecl();
582
583  if (ParamName) {
584    maybeDiagnoseTemplateParameterShadow(*this, S, ParamNameLoc, ParamName);
585
586    // Add the template parameter into the current scope.
587    S->AddDecl(Param);
588    IdResolver.AddDecl(Param);
589  }
590
591  // C++0x [temp.param]p9:
592  //   A default template-argument may be specified for any kind of
593  //   template-parameter that is not a template parameter pack.
594  if (DefaultArg && Ellipsis) {
595    Diag(EqualLoc, diag::err_template_param_pack_default_arg);
596    DefaultArg = ParsedType();
597  }
598
599  // Handle the default argument, if provided.
600  if (DefaultArg) {
601    TypeSourceInfo *DefaultTInfo;
602    GetTypeFromParser(DefaultArg, &DefaultTInfo);
603
604    assert(DefaultTInfo && "expected source information for type");
605
606    // Check for unexpanded parameter packs.
607    if (DiagnoseUnexpandedParameterPack(Loc, DefaultTInfo,
608                                        UPPC_DefaultArgument))
609      return Param;
610
611    // Check the template argument itself.
612    if (CheckTemplateArgument(Param, DefaultTInfo)) {
613      Param->setInvalidDecl();
614      return Param;
615    }
616
617    Param->setDefaultArgument(DefaultTInfo, false);
618  }
619
620  return Param;
621}
622
623/// \brief Check that the type of a non-type template parameter is
624/// well-formed.
625///
626/// \returns the (possibly-promoted) parameter type if valid;
627/// otherwise, produces a diagnostic and returns a NULL type.
628QualType
629Sema::CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc) {
630  // We don't allow variably-modified types as the type of non-type template
631  // parameters.
632  if (T->isVariablyModifiedType()) {
633    Diag(Loc, diag::err_variably_modified_nontype_template_param)
634      << T;
635    return QualType();
636  }
637
638  // C++ [temp.param]p4:
639  //
640  // A non-type template-parameter shall have one of the following
641  // (optionally cv-qualified) types:
642  //
643  //       -- integral or enumeration type,
644  if (T->isIntegralOrEnumerationType() ||
645      //   -- pointer to object or pointer to function,
646      T->isPointerType() ||
647      //   -- reference to object or reference to function,
648      T->isReferenceType() ||
649      //   -- pointer to member,
650      T->isMemberPointerType() ||
651      //   -- std::nullptr_t.
652      T->isNullPtrType() ||
653      // If T is a dependent type, we can't do the check now, so we
654      // assume that it is well-formed.
655      T->isDependentType()) {
656    // C++ [temp.param]p5: The top-level cv-qualifiers on the template-parameter
657    // are ignored when determining its type.
658    return T.getUnqualifiedType();
659  }
660
661  // C++ [temp.param]p8:
662  //
663  //   A non-type template-parameter of type "array of T" or
664  //   "function returning T" is adjusted to be of type "pointer to
665  //   T" or "pointer to function returning T", respectively.
666  else if (T->isArrayType())
667    // FIXME: Keep the type prior to promotion?
668    return Context.getArrayDecayedType(T);
669  else if (T->isFunctionType())
670    // FIXME: Keep the type prior to promotion?
671    return Context.getPointerType(T);
672
673  Diag(Loc, diag::err_template_nontype_parm_bad_type)
674    << T;
675
676  return QualType();
677}
678
679Decl *Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
680                                          unsigned Depth,
681                                          unsigned Position,
682                                          SourceLocation EqualLoc,
683                                          Expr *Default) {
684  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
685  QualType T = TInfo->getType();
686
687  assert(S->isTemplateParamScope() &&
688         "Non-type template parameter not in template parameter scope!");
689  bool Invalid = false;
690
691  T = CheckNonTypeTemplateParameterType(T, D.getIdentifierLoc());
692  if (T.isNull()) {
693    T = Context.IntTy; // Recover with an 'int' type.
694    Invalid = true;
695  }
696
697  IdentifierInfo *ParamName = D.getIdentifier();
698  bool IsParameterPack = D.hasEllipsis();
699  NonTypeTemplateParmDecl *Param
700    = NonTypeTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
701                                      D.getLocStart(),
702                                      D.getIdentifierLoc(),
703                                      Depth, Position, ParamName, T,
704                                      IsParameterPack, TInfo);
705  Param->setAccess(AS_public);
706
707  if (Invalid)
708    Param->setInvalidDecl();
709
710  if (ParamName) {
711    maybeDiagnoseTemplateParameterShadow(*this, S, D.getIdentifierLoc(),
712                                         ParamName);
713
714    // Add the template parameter into the current scope.
715    S->AddDecl(Param);
716    IdResolver.AddDecl(Param);
717  }
718
719  // C++0x [temp.param]p9:
720  //   A default template-argument may be specified for any kind of
721  //   template-parameter that is not a template parameter pack.
722  if (Default && IsParameterPack) {
723    Diag(EqualLoc, diag::err_template_param_pack_default_arg);
724    Default = 0;
725  }
726
727  // Check the well-formedness of the default template argument, if provided.
728  if (Default) {
729    // Check for unexpanded parameter packs.
730    if (DiagnoseUnexpandedParameterPack(Default, UPPC_DefaultArgument))
731      return Param;
732
733    TemplateArgument Converted;
734    ExprResult DefaultRes = CheckTemplateArgument(Param, Param->getType(), Default, Converted);
735    if (DefaultRes.isInvalid()) {
736      Param->setInvalidDecl();
737      return Param;
738    }
739    Default = DefaultRes.take();
740
741    Param->setDefaultArgument(Default, false);
742  }
743
744  return Param;
745}
746
747/// ActOnTemplateTemplateParameter - Called when a C++ template template
748/// parameter (e.g. T in template <template \<typename> class T> class array)
749/// has been parsed. S is the current scope.
750Decl *Sema::ActOnTemplateTemplateParameter(Scope* S,
751                                           SourceLocation TmpLoc,
752                                           TemplateParameterList *Params,
753                                           SourceLocation EllipsisLoc,
754                                           IdentifierInfo *Name,
755                                           SourceLocation NameLoc,
756                                           unsigned Depth,
757                                           unsigned Position,
758                                           SourceLocation EqualLoc,
759                                           ParsedTemplateArgument Default) {
760  assert(S->isTemplateParamScope() &&
761         "Template template parameter not in template parameter scope!");
762
763  // Construct the parameter object.
764  bool IsParameterPack = EllipsisLoc.isValid();
765  TemplateTemplateParmDecl *Param =
766    TemplateTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
767                                     NameLoc.isInvalid()? TmpLoc : NameLoc,
768                                     Depth, Position, IsParameterPack,
769                                     Name, Params);
770  Param->setAccess(AS_public);
771
772  // If the template template parameter has a name, then link the identifier
773  // into the scope and lookup mechanisms.
774  if (Name) {
775    maybeDiagnoseTemplateParameterShadow(*this, S, NameLoc, Name);
776
777    S->AddDecl(Param);
778    IdResolver.AddDecl(Param);
779  }
780
781  if (Params->size() == 0) {
782    Diag(Param->getLocation(), diag::err_template_template_parm_no_parms)
783    << SourceRange(Params->getLAngleLoc(), Params->getRAngleLoc());
784    Param->setInvalidDecl();
785  }
786
787  // C++0x [temp.param]p9:
788  //   A default template-argument may be specified for any kind of
789  //   template-parameter that is not a template parameter pack.
790  if (IsParameterPack && !Default.isInvalid()) {
791    Diag(EqualLoc, diag::err_template_param_pack_default_arg);
792    Default = ParsedTemplateArgument();
793  }
794
795  if (!Default.isInvalid()) {
796    // Check only that we have a template template argument. We don't want to
797    // try to check well-formedness now, because our template template parameter
798    // might have dependent types in its template parameters, which we wouldn't
799    // be able to match now.
800    //
801    // If none of the template template parameter's template arguments mention
802    // other template parameters, we could actually perform more checking here.
803    // However, it isn't worth doing.
804    TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default);
805    if (DefaultArg.getArgument().getAsTemplate().isNull()) {
806      Diag(DefaultArg.getLocation(), diag::err_template_arg_not_class_template)
807        << DefaultArg.getSourceRange();
808      return Param;
809    }
810
811    // Check for unexpanded parameter packs.
812    if (DiagnoseUnexpandedParameterPack(DefaultArg.getLocation(),
813                                        DefaultArg.getArgument().getAsTemplate(),
814                                        UPPC_DefaultArgument))
815      return Param;
816
817    Param->setDefaultArgument(DefaultArg, false);
818  }
819
820  return Param;
821}
822
823/// ActOnTemplateParameterList - Builds a TemplateParameterList that
824/// contains the template parameters in Params/NumParams.
825TemplateParameterList *
826Sema::ActOnTemplateParameterList(unsigned Depth,
827                                 SourceLocation ExportLoc,
828                                 SourceLocation TemplateLoc,
829                                 SourceLocation LAngleLoc,
830                                 Decl **Params, unsigned NumParams,
831                                 SourceLocation RAngleLoc) {
832  if (ExportLoc.isValid())
833    Diag(ExportLoc, diag::warn_template_export_unsupported);
834
835  return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
836                                       (NamedDecl**)Params, NumParams,
837                                       RAngleLoc);
838}
839
840static void SetNestedNameSpecifier(TagDecl *T, const CXXScopeSpec &SS) {
841  if (SS.isSet())
842    T->setQualifierInfo(SS.getWithLocInContext(T->getASTContext()));
843}
844
845DeclResult
846Sema::CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
847                         SourceLocation KWLoc, CXXScopeSpec &SS,
848                         IdentifierInfo *Name, SourceLocation NameLoc,
849                         AttributeList *Attr,
850                         TemplateParameterList *TemplateParams,
851                         AccessSpecifier AS, SourceLocation ModulePrivateLoc,
852                         unsigned NumOuterTemplateParamLists,
853                         TemplateParameterList** OuterTemplateParamLists) {
854  assert(TemplateParams && TemplateParams->size() > 0 &&
855         "No template parameters");
856  assert(TUK != TUK_Reference && "Can only declare or define class templates");
857  bool Invalid = false;
858
859  // Check that we can declare a template here.
860  if (CheckTemplateDeclScope(S, TemplateParams))
861    return true;
862
863  TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
864  assert(Kind != TTK_Enum && "can't build template of enumerated type");
865
866  // There is no such thing as an unnamed class template.
867  if (!Name) {
868    Diag(KWLoc, diag::err_template_unnamed_class);
869    return true;
870  }
871
872  // Find any previous declaration with this name. For a friend with no
873  // scope explicitly specified, we only look for tag declarations (per
874  // C++11 [basic.lookup.elab]p2).
875  DeclContext *SemanticContext;
876  LookupResult Previous(*this, Name, NameLoc,
877                        (SS.isEmpty() && TUK == TUK_Friend)
878                          ? LookupTagName : LookupOrdinaryName,
879                        ForRedeclaration);
880  if (SS.isNotEmpty() && !SS.isInvalid()) {
881    SemanticContext = computeDeclContext(SS, true);
882    if (!SemanticContext) {
883      // FIXME: Horrible, horrible hack! We can't currently represent this
884      // in the AST, and historically we have just ignored such friend
885      // class templates, so don't complain here.
886      if (TUK != TUK_Friend)
887        Diag(NameLoc, diag::err_template_qualified_declarator_no_match)
888          << SS.getScopeRep() << SS.getRange();
889      return true;
890    }
891
892    if (RequireCompleteDeclContext(SS, SemanticContext))
893      return true;
894
895    // If we're adding a template to a dependent context, we may need to
896    // rebuilding some of the types used within the template parameter list,
897    // now that we know what the current instantiation is.
898    if (SemanticContext->isDependentContext()) {
899      ContextRAII SavedContext(*this, SemanticContext);
900      if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
901        Invalid = true;
902    } else if (TUK != TUK_Friend && TUK != TUK_Reference)
903      diagnoseQualifiedDeclaration(SS, SemanticContext, Name, NameLoc);
904
905    LookupQualifiedName(Previous, SemanticContext);
906  } else {
907    SemanticContext = CurContext;
908    LookupName(Previous, S);
909  }
910
911  if (Previous.isAmbiguous())
912    return true;
913
914  NamedDecl *PrevDecl = 0;
915  if (Previous.begin() != Previous.end())
916    PrevDecl = (*Previous.begin())->getUnderlyingDecl();
917
918  // If there is a previous declaration with the same name, check
919  // whether this is a valid redeclaration.
920  ClassTemplateDecl *PrevClassTemplate
921    = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
922
923  // We may have found the injected-class-name of a class template,
924  // class template partial specialization, or class template specialization.
925  // In these cases, grab the template that is being defined or specialized.
926  if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) &&
927      cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
928    PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
929    PrevClassTemplate
930      = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
931    if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
932      PrevClassTemplate
933        = cast<ClassTemplateSpecializationDecl>(PrevDecl)
934            ->getSpecializedTemplate();
935    }
936  }
937
938  if (TUK == TUK_Friend) {
939    // C++ [namespace.memdef]p3:
940    //   [...] When looking for a prior declaration of a class or a function
941    //   declared as a friend, and when the name of the friend class or
942    //   function is neither a qualified name nor a template-id, scopes outside
943    //   the innermost enclosing namespace scope are not considered.
944    if (!SS.isSet()) {
945      DeclContext *OutermostContext = CurContext;
946      while (!OutermostContext->isFileContext())
947        OutermostContext = OutermostContext->getLookupParent();
948
949      if (PrevDecl &&
950          (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
951           OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
952        SemanticContext = PrevDecl->getDeclContext();
953      } else {
954        // Declarations in outer scopes don't matter. However, the outermost
955        // context we computed is the semantic context for our new
956        // declaration.
957        PrevDecl = PrevClassTemplate = 0;
958        SemanticContext = OutermostContext;
959
960        // Check that the chosen semantic context doesn't already contain a
961        // declaration of this name as a non-tag type.
962        LookupResult Previous(*this, Name, NameLoc, LookupOrdinaryName,
963                              ForRedeclaration);
964        DeclContext *LookupContext = SemanticContext;
965        while (LookupContext->isTransparentContext())
966          LookupContext = LookupContext->getLookupParent();
967        LookupQualifiedName(Previous, LookupContext);
968
969        if (Previous.isAmbiguous())
970          return true;
971
972        if (Previous.begin() != Previous.end())
973          PrevDecl = (*Previous.begin())->getUnderlyingDecl();
974      }
975    }
976  } else if (PrevDecl && !isDeclInScope(PrevDecl, SemanticContext, S))
977    PrevDecl = PrevClassTemplate = 0;
978
979  if (PrevClassTemplate) {
980    // Ensure that the template parameter lists are compatible. Skip this check
981    // for a friend in a dependent context: the template parameter list itself
982    // could be dependent.
983    if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
984        !TemplateParameterListsAreEqual(TemplateParams,
985                                   PrevClassTemplate->getTemplateParameters(),
986                                        /*Complain=*/true,
987                                        TPL_TemplateMatch))
988      return true;
989
990    // C++ [temp.class]p4:
991    //   In a redeclaration, partial specialization, explicit
992    //   specialization or explicit instantiation of a class template,
993    //   the class-key shall agree in kind with the original class
994    //   template declaration (7.1.5.3).
995    RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
996    if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind,
997                                      TUK == TUK_Definition,  KWLoc, *Name)) {
998      Diag(KWLoc, diag::err_use_with_wrong_tag)
999        << Name
1000        << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName());
1001      Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
1002      Kind = PrevRecordDecl->getTagKind();
1003    }
1004
1005    // Check for redefinition of this class template.
1006    if (TUK == TUK_Definition) {
1007      if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
1008        Diag(NameLoc, diag::err_redefinition) << Name;
1009        Diag(Def->getLocation(), diag::note_previous_definition);
1010        // FIXME: Would it make sense to try to "forget" the previous
1011        // definition, as part of error recovery?
1012        return true;
1013      }
1014    }
1015  } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
1016    // Maybe we will complain about the shadowed template parameter.
1017    DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
1018    // Just pretend that we didn't see the previous declaration.
1019    PrevDecl = 0;
1020  } else if (PrevDecl) {
1021    // C++ [temp]p5:
1022    //   A class template shall not have the same name as any other
1023    //   template, class, function, object, enumeration, enumerator,
1024    //   namespace, or type in the same scope (3.3), except as specified
1025    //   in (14.5.4).
1026    Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
1027    Diag(PrevDecl->getLocation(), diag::note_previous_definition);
1028    return true;
1029  }
1030
1031  // Check the template parameter list of this declaration, possibly
1032  // merging in the template parameter list from the previous class
1033  // template declaration. Skip this check for a friend in a dependent
1034  // context, because the template parameter list might be dependent.
1035  if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
1036      CheckTemplateParameterList(
1037          TemplateParams,
1038          PrevClassTemplate ? PrevClassTemplate->getTemplateParameters() : 0,
1039          (SS.isSet() && SemanticContext && SemanticContext->isRecord() &&
1040           SemanticContext->isDependentContext())
1041              ? TPC_ClassTemplateMember
1042              : TUK == TUK_Friend ? TPC_FriendClassTemplate
1043                                  : TPC_ClassTemplate))
1044    Invalid = true;
1045
1046  if (SS.isSet()) {
1047    // If the name of the template was qualified, we must be defining the
1048    // template out-of-line.
1049    if (!SS.isInvalid() && !Invalid && !PrevClassTemplate) {
1050      Diag(NameLoc, TUK == TUK_Friend ? diag::err_friend_decl_does_not_match
1051                                      : diag::err_member_def_does_not_match)
1052        << Name << SemanticContext << SS.getRange();
1053      Invalid = true;
1054    }
1055  }
1056
1057  CXXRecordDecl *NewClass =
1058    CXXRecordDecl::Create(Context, Kind, SemanticContext, KWLoc, NameLoc, Name,
1059                          PrevClassTemplate?
1060                            PrevClassTemplate->getTemplatedDecl() : 0,
1061                          /*DelayTypeCreation=*/true);
1062  SetNestedNameSpecifier(NewClass, SS);
1063  if (NumOuterTemplateParamLists > 0)
1064    NewClass->setTemplateParameterListsInfo(Context,
1065                                            NumOuterTemplateParamLists,
1066                                            OuterTemplateParamLists);
1067
1068  // Add alignment attributes if necessary; these attributes are checked when
1069  // the ASTContext lays out the structure.
1070  if (TUK == TUK_Definition) {
1071    AddAlignmentAttributesForRecord(NewClass);
1072    AddMsStructLayoutForRecord(NewClass);
1073  }
1074
1075  ClassTemplateDecl *NewTemplate
1076    = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
1077                                DeclarationName(Name), TemplateParams,
1078                                NewClass, PrevClassTemplate);
1079  NewClass->setDescribedClassTemplate(NewTemplate);
1080
1081  if (ModulePrivateLoc.isValid())
1082    NewTemplate->setModulePrivate();
1083
1084  // Build the type for the class template declaration now.
1085  QualType T = NewTemplate->getInjectedClassNameSpecialization();
1086  T = Context.getInjectedClassNameType(NewClass, T);
1087  assert(T->isDependentType() && "Class template type is not dependent?");
1088  (void)T;
1089
1090  // If we are providing an explicit specialization of a member that is a
1091  // class template, make a note of that.
1092  if (PrevClassTemplate &&
1093      PrevClassTemplate->getInstantiatedFromMemberTemplate())
1094    PrevClassTemplate->setMemberSpecialization();
1095
1096  // Set the access specifier.
1097  if (!Invalid && TUK != TUK_Friend && NewTemplate->getDeclContext()->isRecord())
1098    SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
1099
1100  // Set the lexical context of these templates
1101  NewClass->setLexicalDeclContext(CurContext);
1102  NewTemplate->setLexicalDeclContext(CurContext);
1103
1104  if (TUK == TUK_Definition)
1105    NewClass->startDefinition();
1106
1107  if (Attr)
1108    ProcessDeclAttributeList(S, NewClass, Attr);
1109
1110  if (PrevClassTemplate)
1111    mergeDeclAttributes(NewClass, PrevClassTemplate->getTemplatedDecl());
1112
1113  AddPushedVisibilityAttribute(NewClass);
1114
1115  if (TUK != TUK_Friend)
1116    PushOnScopeChains(NewTemplate, S);
1117  else {
1118    if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
1119      NewTemplate->setAccess(PrevClassTemplate->getAccess());
1120      NewClass->setAccess(PrevClassTemplate->getAccess());
1121    }
1122
1123    NewTemplate->setObjectOfFriendDecl(/* PreviouslyDeclared = */
1124                                       PrevClassTemplate != NULL);
1125
1126    // Friend templates are visible in fairly strange ways.
1127    if (!CurContext->isDependentContext()) {
1128      DeclContext *DC = SemanticContext->getRedeclContext();
1129      DC->makeDeclVisibleInContext(NewTemplate);
1130      if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
1131        PushOnScopeChains(NewTemplate, EnclosingScope,
1132                          /* AddToContext = */ false);
1133    }
1134
1135    FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
1136                                            NewClass->getLocation(),
1137                                            NewTemplate,
1138                                    /*FIXME:*/NewClass->getLocation());
1139    Friend->setAccess(AS_public);
1140    CurContext->addDecl(Friend);
1141  }
1142
1143  if (Invalid) {
1144    NewTemplate->setInvalidDecl();
1145    NewClass->setInvalidDecl();
1146  }
1147
1148  ActOnDocumentableDecl(NewTemplate);
1149
1150  return NewTemplate;
1151}
1152
1153/// \brief Diagnose the presence of a default template argument on a
1154/// template parameter, which is ill-formed in certain contexts.
1155///
1156/// \returns true if the default template argument should be dropped.
1157static bool DiagnoseDefaultTemplateArgument(Sema &S,
1158                                            Sema::TemplateParamListContext TPC,
1159                                            SourceLocation ParamLoc,
1160                                            SourceRange DefArgRange) {
1161  switch (TPC) {
1162  case Sema::TPC_ClassTemplate:
1163  case Sema::TPC_TypeAliasTemplate:
1164    return false;
1165
1166  case Sema::TPC_FunctionTemplate:
1167  case Sema::TPC_FriendFunctionTemplateDefinition:
1168    // C++ [temp.param]p9:
1169    //   A default template-argument shall not be specified in a
1170    //   function template declaration or a function template
1171    //   definition [...]
1172    //   If a friend function template declaration specifies a default
1173    //   template-argument, that declaration shall be a definition and shall be
1174    //   the only declaration of the function template in the translation unit.
1175    // (C++98/03 doesn't have this wording; see DR226).
1176    S.Diag(ParamLoc, S.getLangOpts().CPlusPlus11 ?
1177         diag::warn_cxx98_compat_template_parameter_default_in_function_template
1178           : diag::ext_template_parameter_default_in_function_template)
1179      << DefArgRange;
1180    return false;
1181
1182  case Sema::TPC_ClassTemplateMember:
1183    // C++0x [temp.param]p9:
1184    //   A default template-argument shall not be specified in the
1185    //   template-parameter-lists of the definition of a member of a
1186    //   class template that appears outside of the member's class.
1187    S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
1188      << DefArgRange;
1189    return true;
1190
1191  case Sema::TPC_FriendClassTemplate:
1192  case Sema::TPC_FriendFunctionTemplate:
1193    // C++ [temp.param]p9:
1194    //   A default template-argument shall not be specified in a
1195    //   friend template declaration.
1196    S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
1197      << DefArgRange;
1198    return true;
1199
1200    // FIXME: C++0x [temp.param]p9 allows default template-arguments
1201    // for friend function templates if there is only a single
1202    // declaration (and it is a definition). Strange!
1203  }
1204
1205  llvm_unreachable("Invalid TemplateParamListContext!");
1206}
1207
1208/// \brief Check for unexpanded parameter packs within the template parameters
1209/// of a template template parameter, recursively.
1210static bool DiagnoseUnexpandedParameterPacks(Sema &S,
1211                                             TemplateTemplateParmDecl *TTP) {
1212  // A template template parameter which is a parameter pack is also a pack
1213  // expansion.
1214  if (TTP->isParameterPack())
1215    return false;
1216
1217  TemplateParameterList *Params = TTP->getTemplateParameters();
1218  for (unsigned I = 0, N = Params->size(); I != N; ++I) {
1219    NamedDecl *P = Params->getParam(I);
1220    if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {
1221      if (!NTTP->isParameterPack() &&
1222          S.DiagnoseUnexpandedParameterPack(NTTP->getLocation(),
1223                                            NTTP->getTypeSourceInfo(),
1224                                      Sema::UPPC_NonTypeTemplateParameterType))
1225        return true;
1226
1227      continue;
1228    }
1229
1230    if (TemplateTemplateParmDecl *InnerTTP
1231                                        = dyn_cast<TemplateTemplateParmDecl>(P))
1232      if (DiagnoseUnexpandedParameterPacks(S, InnerTTP))
1233        return true;
1234  }
1235
1236  return false;
1237}
1238
1239/// \brief Checks the validity of a template parameter list, possibly
1240/// considering the template parameter list from a previous
1241/// declaration.
1242///
1243/// If an "old" template parameter list is provided, it must be
1244/// equivalent (per TemplateParameterListsAreEqual) to the "new"
1245/// template parameter list.
1246///
1247/// \param NewParams Template parameter list for a new template
1248/// declaration. This template parameter list will be updated with any
1249/// default arguments that are carried through from the previous
1250/// template parameter list.
1251///
1252/// \param OldParams If provided, template parameter list from a
1253/// previous declaration of the same template. Default template
1254/// arguments will be merged from the old template parameter list to
1255/// the new template parameter list.
1256///
1257/// \param TPC Describes the context in which we are checking the given
1258/// template parameter list.
1259///
1260/// \returns true if an error occurred, false otherwise.
1261bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
1262                                      TemplateParameterList *OldParams,
1263                                      TemplateParamListContext TPC) {
1264  bool Invalid = false;
1265
1266  // C++ [temp.param]p10:
1267  //   The set of default template-arguments available for use with a
1268  //   template declaration or definition is obtained by merging the
1269  //   default arguments from the definition (if in scope) and all
1270  //   declarations in scope in the same way default function
1271  //   arguments are (8.3.6).
1272  bool SawDefaultArgument = false;
1273  SourceLocation PreviousDefaultArgLoc;
1274
1275  // Dummy initialization to avoid warnings.
1276  TemplateParameterList::iterator OldParam = NewParams->end();
1277  if (OldParams)
1278    OldParam = OldParams->begin();
1279
1280  bool RemoveDefaultArguments = false;
1281  for (TemplateParameterList::iterator NewParam = NewParams->begin(),
1282                                    NewParamEnd = NewParams->end();
1283       NewParam != NewParamEnd; ++NewParam) {
1284    // Variables used to diagnose redundant default arguments
1285    bool RedundantDefaultArg = false;
1286    SourceLocation OldDefaultLoc;
1287    SourceLocation NewDefaultLoc;
1288
1289    // Variable used to diagnose missing default arguments
1290    bool MissingDefaultArg = false;
1291
1292    // Variable used to diagnose non-final parameter packs
1293    bool SawParameterPack = false;
1294
1295    if (TemplateTypeParmDecl *NewTypeParm
1296          = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
1297      // Check the presence of a default argument here.
1298      if (NewTypeParm->hasDefaultArgument() &&
1299          DiagnoseDefaultTemplateArgument(*this, TPC,
1300                                          NewTypeParm->getLocation(),
1301               NewTypeParm->getDefaultArgumentInfo()->getTypeLoc()
1302                                                       .getSourceRange()))
1303        NewTypeParm->removeDefaultArgument();
1304
1305      // Merge default arguments for template type parameters.
1306      TemplateTypeParmDecl *OldTypeParm
1307          = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : 0;
1308
1309      if (NewTypeParm->isParameterPack()) {
1310        assert(!NewTypeParm->hasDefaultArgument() &&
1311               "Parameter packs can't have a default argument!");
1312        SawParameterPack = true;
1313      } else if (OldTypeParm && OldTypeParm->hasDefaultArgument() &&
1314                 NewTypeParm->hasDefaultArgument()) {
1315        OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
1316        NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
1317        SawDefaultArgument = true;
1318        RedundantDefaultArg = true;
1319        PreviousDefaultArgLoc = NewDefaultLoc;
1320      } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
1321        // Merge the default argument from the old declaration to the
1322        // new declaration.
1323        SawDefaultArgument = true;
1324        NewTypeParm->setDefaultArgument(OldTypeParm->getDefaultArgumentInfo(),
1325                                        true);
1326        PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
1327      } else if (NewTypeParm->hasDefaultArgument()) {
1328        SawDefaultArgument = true;
1329        PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
1330      } else if (SawDefaultArgument)
1331        MissingDefaultArg = true;
1332    } else if (NonTypeTemplateParmDecl *NewNonTypeParm
1333               = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
1334      // Check for unexpanded parameter packs.
1335      if (!NewNonTypeParm->isParameterPack() &&
1336          DiagnoseUnexpandedParameterPack(NewNonTypeParm->getLocation(),
1337                                          NewNonTypeParm->getTypeSourceInfo(),
1338                                          UPPC_NonTypeTemplateParameterType)) {
1339        Invalid = true;
1340        continue;
1341      }
1342
1343      // Check the presence of a default argument here.
1344      if (NewNonTypeParm->hasDefaultArgument() &&
1345          DiagnoseDefaultTemplateArgument(*this, TPC,
1346                                          NewNonTypeParm->getLocation(),
1347                    NewNonTypeParm->getDefaultArgument()->getSourceRange())) {
1348        NewNonTypeParm->removeDefaultArgument();
1349      }
1350
1351      // Merge default arguments for non-type template parameters
1352      NonTypeTemplateParmDecl *OldNonTypeParm
1353        = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : 0;
1354      if (NewNonTypeParm->isParameterPack()) {
1355        assert(!NewNonTypeParm->hasDefaultArgument() &&
1356               "Parameter packs can't have a default argument!");
1357        if (!NewNonTypeParm->isPackExpansion())
1358          SawParameterPack = true;
1359      } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument() &&
1360          NewNonTypeParm->hasDefaultArgument()) {
1361        OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
1362        NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
1363        SawDefaultArgument = true;
1364        RedundantDefaultArg = true;
1365        PreviousDefaultArgLoc = NewDefaultLoc;
1366      } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
1367        // Merge the default argument from the old declaration to the
1368        // new declaration.
1369        SawDefaultArgument = true;
1370        // FIXME: We need to create a new kind of "default argument"
1371        // expression that points to a previous non-type template
1372        // parameter.
1373        NewNonTypeParm->setDefaultArgument(
1374                                         OldNonTypeParm->getDefaultArgument(),
1375                                         /*Inherited=*/ true);
1376        PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
1377      } else if (NewNonTypeParm->hasDefaultArgument()) {
1378        SawDefaultArgument = true;
1379        PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
1380      } else if (SawDefaultArgument)
1381        MissingDefaultArg = true;
1382    } else {
1383      TemplateTemplateParmDecl *NewTemplateParm
1384        = cast<TemplateTemplateParmDecl>(*NewParam);
1385
1386      // Check for unexpanded parameter packs, recursively.
1387      if (::DiagnoseUnexpandedParameterPacks(*this, NewTemplateParm)) {
1388        Invalid = true;
1389        continue;
1390      }
1391
1392      // Check the presence of a default argument here.
1393      if (NewTemplateParm->hasDefaultArgument() &&
1394          DiagnoseDefaultTemplateArgument(*this, TPC,
1395                                          NewTemplateParm->getLocation(),
1396                     NewTemplateParm->getDefaultArgument().getSourceRange()))
1397        NewTemplateParm->removeDefaultArgument();
1398
1399      // Merge default arguments for template template parameters
1400      TemplateTemplateParmDecl *OldTemplateParm
1401        = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : 0;
1402      if (NewTemplateParm->isParameterPack()) {
1403        assert(!NewTemplateParm->hasDefaultArgument() &&
1404               "Parameter packs can't have a default argument!");
1405        if (!NewTemplateParm->isPackExpansion())
1406          SawParameterPack = true;
1407      } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument() &&
1408          NewTemplateParm->hasDefaultArgument()) {
1409        OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
1410        NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
1411        SawDefaultArgument = true;
1412        RedundantDefaultArg = true;
1413        PreviousDefaultArgLoc = NewDefaultLoc;
1414      } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
1415        // Merge the default argument from the old declaration to the
1416        // new declaration.
1417        SawDefaultArgument = true;
1418        // FIXME: We need to create a new kind of "default argument" expression
1419        // that points to a previous template template parameter.
1420        NewTemplateParm->setDefaultArgument(
1421                                          OldTemplateParm->getDefaultArgument(),
1422                                          /*Inherited=*/ true);
1423        PreviousDefaultArgLoc
1424          = OldTemplateParm->getDefaultArgument().getLocation();
1425      } else if (NewTemplateParm->hasDefaultArgument()) {
1426        SawDefaultArgument = true;
1427        PreviousDefaultArgLoc
1428          = NewTemplateParm->getDefaultArgument().getLocation();
1429      } else if (SawDefaultArgument)
1430        MissingDefaultArg = true;
1431    }
1432
1433    // C++11 [temp.param]p11:
1434    //   If a template parameter of a primary class template or alias template
1435    //   is a template parameter pack, it shall be the last template parameter.
1436    if (SawParameterPack && (NewParam + 1) != NewParamEnd &&
1437        (TPC == TPC_ClassTemplate || TPC == TPC_TypeAliasTemplate)) {
1438      Diag((*NewParam)->getLocation(),
1439           diag::err_template_param_pack_must_be_last_template_parameter);
1440      Invalid = true;
1441    }
1442
1443    if (RedundantDefaultArg) {
1444      // C++ [temp.param]p12:
1445      //   A template-parameter shall not be given default arguments
1446      //   by two different declarations in the same scope.
1447      Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
1448      Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
1449      Invalid = true;
1450    } else if (MissingDefaultArg && TPC != TPC_FunctionTemplate) {
1451      // C++ [temp.param]p11:
1452      //   If a template-parameter of a class template has a default
1453      //   template-argument, each subsequent template-parameter shall either
1454      //   have a default template-argument supplied or be a template parameter
1455      //   pack.
1456      Diag((*NewParam)->getLocation(),
1457           diag::err_template_param_default_arg_missing);
1458      Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
1459      Invalid = true;
1460      RemoveDefaultArguments = true;
1461    }
1462
1463    // If we have an old template parameter list that we're merging
1464    // in, move on to the next parameter.
1465    if (OldParams)
1466      ++OldParam;
1467  }
1468
1469  // We were missing some default arguments at the end of the list, so remove
1470  // all of the default arguments.
1471  if (RemoveDefaultArguments) {
1472    for (TemplateParameterList::iterator NewParam = NewParams->begin(),
1473                                      NewParamEnd = NewParams->end();
1474         NewParam != NewParamEnd; ++NewParam) {
1475      if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*NewParam))
1476        TTP->removeDefaultArgument();
1477      else if (NonTypeTemplateParmDecl *NTTP
1478                                = dyn_cast<NonTypeTemplateParmDecl>(*NewParam))
1479        NTTP->removeDefaultArgument();
1480      else
1481        cast<TemplateTemplateParmDecl>(*NewParam)->removeDefaultArgument();
1482    }
1483  }
1484
1485  return Invalid;
1486}
1487
1488namespace {
1489
1490/// A class which looks for a use of a certain level of template
1491/// parameter.
1492struct DependencyChecker : RecursiveASTVisitor<DependencyChecker> {
1493  typedef RecursiveASTVisitor<DependencyChecker> super;
1494
1495  unsigned Depth;
1496  bool Match;
1497
1498  DependencyChecker(TemplateParameterList *Params) : Match(false) {
1499    NamedDecl *ND = Params->getParam(0);
1500    if (TemplateTypeParmDecl *PD = dyn_cast<TemplateTypeParmDecl>(ND)) {
1501      Depth = PD->getDepth();
1502    } else if (NonTypeTemplateParmDecl *PD =
1503                 dyn_cast<NonTypeTemplateParmDecl>(ND)) {
1504      Depth = PD->getDepth();
1505    } else {
1506      Depth = cast<TemplateTemplateParmDecl>(ND)->getDepth();
1507    }
1508  }
1509
1510  bool Matches(unsigned ParmDepth) {
1511    if (ParmDepth >= Depth) {
1512      Match = true;
1513      return true;
1514    }
1515    return false;
1516  }
1517
1518  bool VisitTemplateTypeParmType(const TemplateTypeParmType *T) {
1519    return !Matches(T->getDepth());
1520  }
1521
1522  bool TraverseTemplateName(TemplateName N) {
1523    if (TemplateTemplateParmDecl *PD =
1524          dyn_cast_or_null<TemplateTemplateParmDecl>(N.getAsTemplateDecl()))
1525      if (Matches(PD->getDepth())) return false;
1526    return super::TraverseTemplateName(N);
1527  }
1528
1529  bool VisitDeclRefExpr(DeclRefExpr *E) {
1530    if (NonTypeTemplateParmDecl *PD =
1531          dyn_cast<NonTypeTemplateParmDecl>(E->getDecl())) {
1532      if (PD->getDepth() == Depth) {
1533        Match = true;
1534        return false;
1535      }
1536    }
1537    return super::VisitDeclRefExpr(E);
1538  }
1539
1540  bool TraverseInjectedClassNameType(const InjectedClassNameType *T) {
1541    return TraverseType(T->getInjectedSpecializationType());
1542  }
1543};
1544}
1545
1546/// Determines whether a given type depends on the given parameter
1547/// list.
1548static bool
1549DependsOnTemplateParameters(QualType T, TemplateParameterList *Params) {
1550  DependencyChecker Checker(Params);
1551  Checker.TraverseType(T);
1552  return Checker.Match;
1553}
1554
1555// Find the source range corresponding to the named type in the given
1556// nested-name-specifier, if any.
1557static SourceRange getRangeOfTypeInNestedNameSpecifier(ASTContext &Context,
1558                                                       QualType T,
1559                                                       const CXXScopeSpec &SS) {
1560  NestedNameSpecifierLoc NNSLoc(SS.getScopeRep(), SS.location_data());
1561  while (NestedNameSpecifier *NNS = NNSLoc.getNestedNameSpecifier()) {
1562    if (const Type *CurType = NNS->getAsType()) {
1563      if (Context.hasSameUnqualifiedType(T, QualType(CurType, 0)))
1564        return NNSLoc.getTypeLoc().getSourceRange();
1565    } else
1566      break;
1567
1568    NNSLoc = NNSLoc.getPrefix();
1569  }
1570
1571  return SourceRange();
1572}
1573
1574/// \brief Match the given template parameter lists to the given scope
1575/// specifier, returning the template parameter list that applies to the
1576/// name.
1577///
1578/// \param DeclStartLoc the start of the declaration that has a scope
1579/// specifier or a template parameter list.
1580///
1581/// \param DeclLoc The location of the declaration itself.
1582///
1583/// \param SS the scope specifier that will be matched to the given template
1584/// parameter lists. This scope specifier precedes a qualified name that is
1585/// being declared.
1586///
1587/// \param ParamLists the template parameter lists, from the outermost to the
1588/// innermost template parameter lists.
1589///
1590/// \param NumParamLists the number of template parameter lists in ParamLists.
1591///
1592/// \param IsFriend Whether to apply the slightly different rules for
1593/// matching template parameters to scope specifiers in friend
1594/// declarations.
1595///
1596/// \param IsExplicitSpecialization will be set true if the entity being
1597/// declared is an explicit specialization, false otherwise.
1598///
1599/// \returns the template parameter list, if any, that corresponds to the
1600/// name that is preceded by the scope specifier @p SS. This template
1601/// parameter list may have template parameters (if we're declaring a
1602/// template) or may have no template parameters (if we're declaring a
1603/// template specialization), or may be NULL (if what we're declaring isn't
1604/// itself a template).
1605TemplateParameterList *
1606Sema::MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc,
1607                                              SourceLocation DeclLoc,
1608                                              const CXXScopeSpec &SS,
1609                                          TemplateParameterList **ParamLists,
1610                                              unsigned NumParamLists,
1611                                              bool IsFriend,
1612                                              bool &IsExplicitSpecialization,
1613                                              bool &Invalid) {
1614  IsExplicitSpecialization = false;
1615  Invalid = false;
1616
1617  // The sequence of nested types to which we will match up the template
1618  // parameter lists. We first build this list by starting with the type named
1619  // by the nested-name-specifier and walking out until we run out of types.
1620  SmallVector<QualType, 4> NestedTypes;
1621  QualType T;
1622  if (SS.getScopeRep()) {
1623    if (CXXRecordDecl *Record
1624              = dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, true)))
1625      T = Context.getTypeDeclType(Record);
1626    else
1627      T = QualType(SS.getScopeRep()->getAsType(), 0);
1628  }
1629
1630  // If we found an explicit specialization that prevents us from needing
1631  // 'template<>' headers, this will be set to the location of that
1632  // explicit specialization.
1633  SourceLocation ExplicitSpecLoc;
1634
1635  while (!T.isNull()) {
1636    NestedTypes.push_back(T);
1637
1638    // Retrieve the parent of a record type.
1639    if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
1640      // If this type is an explicit specialization, we're done.
1641      if (ClassTemplateSpecializationDecl *Spec
1642          = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
1643        if (!isa<ClassTemplatePartialSpecializationDecl>(Spec) &&
1644            Spec->getSpecializationKind() == TSK_ExplicitSpecialization) {
1645          ExplicitSpecLoc = Spec->getLocation();
1646          break;
1647        }
1648      } else if (Record->getTemplateSpecializationKind()
1649                                                == TSK_ExplicitSpecialization) {
1650        ExplicitSpecLoc = Record->getLocation();
1651        break;
1652      }
1653
1654      if (TypeDecl *Parent = dyn_cast<TypeDecl>(Record->getParent()))
1655        T = Context.getTypeDeclType(Parent);
1656      else
1657        T = QualType();
1658      continue;
1659    }
1660
1661    if (const TemplateSpecializationType *TST
1662                                     = T->getAs<TemplateSpecializationType>()) {
1663      if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
1664        if (TypeDecl *Parent = dyn_cast<TypeDecl>(Template->getDeclContext()))
1665          T = Context.getTypeDeclType(Parent);
1666        else
1667          T = QualType();
1668        continue;
1669      }
1670    }
1671
1672    // Look one step prior in a dependent template specialization type.
1673    if (const DependentTemplateSpecializationType *DependentTST
1674                          = T->getAs<DependentTemplateSpecializationType>()) {
1675      if (NestedNameSpecifier *NNS = DependentTST->getQualifier())
1676        T = QualType(NNS->getAsType(), 0);
1677      else
1678        T = QualType();
1679      continue;
1680    }
1681
1682    // Look one step prior in a dependent name type.
1683    if (const DependentNameType *DependentName = T->getAs<DependentNameType>()){
1684      if (NestedNameSpecifier *NNS = DependentName->getQualifier())
1685        T = QualType(NNS->getAsType(), 0);
1686      else
1687        T = QualType();
1688      continue;
1689    }
1690
1691    // Retrieve the parent of an enumeration type.
1692    if (const EnumType *EnumT = T->getAs<EnumType>()) {
1693      // FIXME: Forward-declared enums require a TSK_ExplicitSpecialization
1694      // check here.
1695      EnumDecl *Enum = EnumT->getDecl();
1696
1697      // Get to the parent type.
1698      if (TypeDecl *Parent = dyn_cast<TypeDecl>(Enum->getParent()))
1699        T = Context.getTypeDeclType(Parent);
1700      else
1701        T = QualType();
1702      continue;
1703    }
1704
1705    T = QualType();
1706  }
1707  // Reverse the nested types list, since we want to traverse from the outermost
1708  // to the innermost while checking template-parameter-lists.
1709  std::reverse(NestedTypes.begin(), NestedTypes.end());
1710
1711  // C++0x [temp.expl.spec]p17:
1712  //   A member or a member template may be nested within many
1713  //   enclosing class templates. In an explicit specialization for
1714  //   such a member, the member declaration shall be preceded by a
1715  //   template<> for each enclosing class template that is
1716  //   explicitly specialized.
1717  bool SawNonEmptyTemplateParameterList = false;
1718  unsigned ParamIdx = 0;
1719  for (unsigned TypeIdx = 0, NumTypes = NestedTypes.size(); TypeIdx != NumTypes;
1720       ++TypeIdx) {
1721    T = NestedTypes[TypeIdx];
1722
1723    // Whether we expect a 'template<>' header.
1724    bool NeedEmptyTemplateHeader = false;
1725
1726    // Whether we expect a template header with parameters.
1727    bool NeedNonemptyTemplateHeader = false;
1728
1729    // For a dependent type, the set of template parameters that we
1730    // expect to see.
1731    TemplateParameterList *ExpectedTemplateParams = 0;
1732
1733    // C++0x [temp.expl.spec]p15:
1734    //   A member or a member template may be nested within many enclosing
1735    //   class templates. In an explicit specialization for such a member, the
1736    //   member declaration shall be preceded by a template<> for each
1737    //   enclosing class template that is explicitly specialized.
1738    if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
1739      if (ClassTemplatePartialSpecializationDecl *Partial
1740            = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
1741        ExpectedTemplateParams = Partial->getTemplateParameters();
1742        NeedNonemptyTemplateHeader = true;
1743      } else if (Record->isDependentType()) {
1744        if (Record->getDescribedClassTemplate()) {
1745          ExpectedTemplateParams = Record->getDescribedClassTemplate()
1746                                                      ->getTemplateParameters();
1747          NeedNonemptyTemplateHeader = true;
1748        }
1749      } else if (ClassTemplateSpecializationDecl *Spec
1750                     = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
1751        // C++0x [temp.expl.spec]p4:
1752        //   Members of an explicitly specialized class template are defined
1753        //   in the same manner as members of normal classes, and not using
1754        //   the template<> syntax.
1755        if (Spec->getSpecializationKind() != TSK_ExplicitSpecialization)
1756          NeedEmptyTemplateHeader = true;
1757        else
1758          continue;
1759      } else if (Record->getTemplateSpecializationKind()) {
1760        if (Record->getTemplateSpecializationKind()
1761                                                != TSK_ExplicitSpecialization &&
1762            TypeIdx == NumTypes - 1)
1763          IsExplicitSpecialization = true;
1764
1765        continue;
1766      }
1767    } else if (const TemplateSpecializationType *TST
1768                                     = T->getAs<TemplateSpecializationType>()) {
1769      if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
1770        ExpectedTemplateParams = Template->getTemplateParameters();
1771        NeedNonemptyTemplateHeader = true;
1772      }
1773    } else if (T->getAs<DependentTemplateSpecializationType>()) {
1774      // FIXME:  We actually could/should check the template arguments here
1775      // against the corresponding template parameter list.
1776      NeedNonemptyTemplateHeader = false;
1777    }
1778
1779    // C++ [temp.expl.spec]p16:
1780    //   In an explicit specialization declaration for a member of a class
1781    //   template or a member template that ap- pears in namespace scope, the
1782    //   member template and some of its enclosing class templates may remain
1783    //   unspecialized, except that the declaration shall not explicitly
1784    //   specialize a class member template if its en- closing class templates
1785    //   are not explicitly specialized as well.
1786    if (ParamIdx < NumParamLists) {
1787      if (ParamLists[ParamIdx]->size() == 0) {
1788        if (SawNonEmptyTemplateParameterList) {
1789          Diag(DeclLoc, diag::err_specialize_member_of_template)
1790            << ParamLists[ParamIdx]->getSourceRange();
1791          Invalid = true;
1792          IsExplicitSpecialization = false;
1793          return 0;
1794        }
1795      } else
1796        SawNonEmptyTemplateParameterList = true;
1797    }
1798
1799    if (NeedEmptyTemplateHeader) {
1800      // If we're on the last of the types, and we need a 'template<>' header
1801      // here, then it's an explicit specialization.
1802      if (TypeIdx == NumTypes - 1)
1803        IsExplicitSpecialization = true;
1804
1805      if (ParamIdx < NumParamLists) {
1806        if (ParamLists[ParamIdx]->size() > 0) {
1807          // The header has template parameters when it shouldn't. Complain.
1808          Diag(ParamLists[ParamIdx]->getTemplateLoc(),
1809               diag::err_template_param_list_matches_nontemplate)
1810            << T
1811            << SourceRange(ParamLists[ParamIdx]->getLAngleLoc(),
1812                           ParamLists[ParamIdx]->getRAngleLoc())
1813            << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
1814          Invalid = true;
1815          return 0;
1816        }
1817
1818        // Consume this template header.
1819        ++ParamIdx;
1820        continue;
1821      }
1822
1823      if (!IsFriend) {
1824        // We don't have a template header, but we should.
1825        SourceLocation ExpectedTemplateLoc;
1826        if (NumParamLists > 0)
1827          ExpectedTemplateLoc = ParamLists[0]->getTemplateLoc();
1828        else
1829          ExpectedTemplateLoc = DeclStartLoc;
1830
1831        Diag(DeclLoc, diag::err_template_spec_needs_header)
1832          << getRangeOfTypeInNestedNameSpecifier(Context, T, SS)
1833          << FixItHint::CreateInsertion(ExpectedTemplateLoc, "template<> ");
1834      }
1835
1836      continue;
1837    }
1838
1839    if (NeedNonemptyTemplateHeader) {
1840      // In friend declarations we can have template-ids which don't
1841      // depend on the corresponding template parameter lists.  But
1842      // assume that empty parameter lists are supposed to match this
1843      // template-id.
1844      if (IsFriend && T->isDependentType()) {
1845        if (ParamIdx < NumParamLists &&
1846            DependsOnTemplateParameters(T, ParamLists[ParamIdx]))
1847          ExpectedTemplateParams = 0;
1848        else
1849          continue;
1850      }
1851
1852      if (ParamIdx < NumParamLists) {
1853        // Check the template parameter list, if we can.
1854        if (ExpectedTemplateParams &&
1855            !TemplateParameterListsAreEqual(ParamLists[ParamIdx],
1856                                            ExpectedTemplateParams,
1857                                            true, TPL_TemplateMatch))
1858          Invalid = true;
1859
1860        if (!Invalid &&
1861            CheckTemplateParameterList(ParamLists[ParamIdx], 0,
1862                                       TPC_ClassTemplateMember))
1863          Invalid = true;
1864
1865        ++ParamIdx;
1866        continue;
1867      }
1868
1869      Diag(DeclLoc, diag::err_template_spec_needs_template_parameters)
1870        << T
1871        << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
1872      Invalid = true;
1873      continue;
1874    }
1875  }
1876
1877  // If there were at least as many template-ids as there were template
1878  // parameter lists, then there are no template parameter lists remaining for
1879  // the declaration itself.
1880  if (ParamIdx >= NumParamLists)
1881    return 0;
1882
1883  // If there were too many template parameter lists, complain about that now.
1884  if (ParamIdx < NumParamLists - 1) {
1885    bool HasAnyExplicitSpecHeader = false;
1886    bool AllExplicitSpecHeaders = true;
1887    for (unsigned I = ParamIdx; I != NumParamLists - 1; ++I) {
1888      if (ParamLists[I]->size() == 0)
1889        HasAnyExplicitSpecHeader = true;
1890      else
1891        AllExplicitSpecHeaders = false;
1892    }
1893
1894    Diag(ParamLists[ParamIdx]->getTemplateLoc(),
1895         AllExplicitSpecHeaders? diag::warn_template_spec_extra_headers
1896                               : diag::err_template_spec_extra_headers)
1897      << SourceRange(ParamLists[ParamIdx]->getTemplateLoc(),
1898                     ParamLists[NumParamLists - 2]->getRAngleLoc());
1899
1900    // If there was a specialization somewhere, such that 'template<>' is
1901    // not required, and there were any 'template<>' headers, note where the
1902    // specialization occurred.
1903    if (ExplicitSpecLoc.isValid() && HasAnyExplicitSpecHeader)
1904      Diag(ExplicitSpecLoc,
1905           diag::note_explicit_template_spec_does_not_need_header)
1906        << NestedTypes.back();
1907
1908    // We have a template parameter list with no corresponding scope, which
1909    // means that the resulting template declaration can't be instantiated
1910    // properly (we'll end up with dependent nodes when we shouldn't).
1911    if (!AllExplicitSpecHeaders)
1912      Invalid = true;
1913  }
1914
1915  // C++ [temp.expl.spec]p16:
1916  //   In an explicit specialization declaration for a member of a class
1917  //   template or a member template that ap- pears in namespace scope, the
1918  //   member template and some of its enclosing class templates may remain
1919  //   unspecialized, except that the declaration shall not explicitly
1920  //   specialize a class member template if its en- closing class templates
1921  //   are not explicitly specialized as well.
1922  if (ParamLists[NumParamLists - 1]->size() == 0 &&
1923      SawNonEmptyTemplateParameterList) {
1924    Diag(DeclLoc, diag::err_specialize_member_of_template)
1925      << ParamLists[ParamIdx]->getSourceRange();
1926    Invalid = true;
1927    IsExplicitSpecialization = false;
1928    return 0;
1929  }
1930
1931  // Return the last template parameter list, which corresponds to the
1932  // entity being declared.
1933  return ParamLists[NumParamLists - 1];
1934}
1935
1936void Sema::NoteAllFoundTemplates(TemplateName Name) {
1937  if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
1938    Diag(Template->getLocation(), diag::note_template_declared_here)
1939      << (isa<FunctionTemplateDecl>(Template)? 0
1940          : isa<ClassTemplateDecl>(Template)? 1
1941          : isa<TypeAliasTemplateDecl>(Template)? 2
1942          : 3)
1943      << Template->getDeclName();
1944    return;
1945  }
1946
1947  if (OverloadedTemplateStorage *OST = Name.getAsOverloadedTemplate()) {
1948    for (OverloadedTemplateStorage::iterator I = OST->begin(),
1949                                          IEnd = OST->end();
1950         I != IEnd; ++I)
1951      Diag((*I)->getLocation(), diag::note_template_declared_here)
1952        << 0 << (*I)->getDeclName();
1953
1954    return;
1955  }
1956}
1957
1958QualType Sema::CheckTemplateIdType(TemplateName Name,
1959                                   SourceLocation TemplateLoc,
1960                                   TemplateArgumentListInfo &TemplateArgs) {
1961  DependentTemplateName *DTN
1962    = Name.getUnderlying().getAsDependentTemplateName();
1963  if (DTN && DTN->isIdentifier())
1964    // When building a template-id where the template-name is dependent,
1965    // assume the template is a type template. Either our assumption is
1966    // correct, or the code is ill-formed and will be diagnosed when the
1967    // dependent name is substituted.
1968    return Context.getDependentTemplateSpecializationType(ETK_None,
1969                                                          DTN->getQualifier(),
1970                                                          DTN->getIdentifier(),
1971                                                          TemplateArgs);
1972
1973  TemplateDecl *Template = Name.getAsTemplateDecl();
1974  if (!Template || isa<FunctionTemplateDecl>(Template)) {
1975    // We might have a substituted template template parameter pack. If so,
1976    // build a template specialization type for it.
1977    if (Name.getAsSubstTemplateTemplateParmPack())
1978      return Context.getTemplateSpecializationType(Name, TemplateArgs);
1979
1980    Diag(TemplateLoc, diag::err_template_id_not_a_type)
1981      << Name;
1982    NoteAllFoundTemplates(Name);
1983    return QualType();
1984  }
1985
1986  // Check that the template argument list is well-formed for this
1987  // template.
1988  SmallVector<TemplateArgument, 4> Converted;
1989  bool ExpansionIntoFixedList = false;
1990  if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
1991                                false, Converted, &ExpansionIntoFixedList))
1992    return QualType();
1993
1994  QualType CanonType;
1995
1996  bool InstantiationDependent = false;
1997  TypeAliasTemplateDecl *AliasTemplate = 0;
1998  if (!ExpansionIntoFixedList &&
1999      (AliasTemplate = dyn_cast<TypeAliasTemplateDecl>(Template))) {
2000    // Find the canonical type for this type alias template specialization.
2001    TypeAliasDecl *Pattern = AliasTemplate->getTemplatedDecl();
2002    if (Pattern->isInvalidDecl())
2003      return QualType();
2004
2005    TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
2006                                      Converted.data(), Converted.size());
2007
2008    // Only substitute for the innermost template argument list.
2009    MultiLevelTemplateArgumentList TemplateArgLists;
2010    TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
2011    unsigned Depth = AliasTemplate->getTemplateParameters()->getDepth();
2012    for (unsigned I = 0; I < Depth; ++I)
2013      TemplateArgLists.addOuterTemplateArguments(None);
2014
2015    LocalInstantiationScope Scope(*this);
2016    InstantiatingTemplate Inst(*this, TemplateLoc, Template);
2017    if (Inst)
2018      return QualType();
2019
2020    CanonType = SubstType(Pattern->getUnderlyingType(),
2021                          TemplateArgLists, AliasTemplate->getLocation(),
2022                          AliasTemplate->getDeclName());
2023    if (CanonType.isNull())
2024      return QualType();
2025  } else if (Name.isDependent() ||
2026             TemplateSpecializationType::anyDependentTemplateArguments(
2027               TemplateArgs, InstantiationDependent)) {
2028    // This class template specialization is a dependent
2029    // type. Therefore, its canonical type is another class template
2030    // specialization type that contains all of the converted
2031    // arguments in canonical form. This ensures that, e.g., A<T> and
2032    // A<T, T> have identical types when A is declared as:
2033    //
2034    //   template<typename T, typename U = T> struct A;
2035    TemplateName CanonName = Context.getCanonicalTemplateName(Name);
2036    CanonType = Context.getTemplateSpecializationType(CanonName,
2037                                                      Converted.data(),
2038                                                      Converted.size());
2039
2040    // FIXME: CanonType is not actually the canonical type, and unfortunately
2041    // it is a TemplateSpecializationType that we will never use again.
2042    // In the future, we need to teach getTemplateSpecializationType to only
2043    // build the canonical type and return that to us.
2044    CanonType = Context.getCanonicalType(CanonType);
2045
2046    // This might work out to be a current instantiation, in which
2047    // case the canonical type needs to be the InjectedClassNameType.
2048    //
2049    // TODO: in theory this could be a simple hashtable lookup; most
2050    // changes to CurContext don't change the set of current
2051    // instantiations.
2052    if (isa<ClassTemplateDecl>(Template)) {
2053      for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
2054        // If we get out to a namespace, we're done.
2055        if (Ctx->isFileContext()) break;
2056
2057        // If this isn't a record, keep looking.
2058        CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
2059        if (!Record) continue;
2060
2061        // Look for one of the two cases with InjectedClassNameTypes
2062        // and check whether it's the same template.
2063        if (!isa<ClassTemplatePartialSpecializationDecl>(Record) &&
2064            !Record->getDescribedClassTemplate())
2065          continue;
2066
2067        // Fetch the injected class name type and check whether its
2068        // injected type is equal to the type we just built.
2069        QualType ICNT = Context.getTypeDeclType(Record);
2070        QualType Injected = cast<InjectedClassNameType>(ICNT)
2071          ->getInjectedSpecializationType();
2072
2073        if (CanonType != Injected->getCanonicalTypeInternal())
2074          continue;
2075
2076        // If so, the canonical type of this TST is the injected
2077        // class name type of the record we just found.
2078        assert(ICNT.isCanonical());
2079        CanonType = ICNT;
2080        break;
2081      }
2082    }
2083  } else if (ClassTemplateDecl *ClassTemplate
2084               = dyn_cast<ClassTemplateDecl>(Template)) {
2085    // Find the class template specialization declaration that
2086    // corresponds to these arguments.
2087    void *InsertPos = 0;
2088    ClassTemplateSpecializationDecl *Decl
2089      = ClassTemplate->findSpecialization(Converted.data(), Converted.size(),
2090                                          InsertPos);
2091    if (!Decl) {
2092      // This is the first time we have referenced this class template
2093      // specialization. Create the canonical declaration and add it to
2094      // the set of specializations.
2095      Decl = ClassTemplateSpecializationDecl::Create(Context,
2096                            ClassTemplate->getTemplatedDecl()->getTagKind(),
2097                                                ClassTemplate->getDeclContext(),
2098                            ClassTemplate->getTemplatedDecl()->getLocStart(),
2099                                                ClassTemplate->getLocation(),
2100                                                     ClassTemplate,
2101                                                     Converted.data(),
2102                                                     Converted.size(), 0);
2103      ClassTemplate->AddSpecialization(Decl, InsertPos);
2104      if (ClassTemplate->isOutOfLine())
2105        Decl->setLexicalDeclContext(ClassTemplate->getLexicalDeclContext());
2106    }
2107
2108    CanonType = Context.getTypeDeclType(Decl);
2109    assert(isa<RecordType>(CanonType) &&
2110           "type of non-dependent specialization is not a RecordType");
2111  }
2112
2113  // Build the fully-sugared type for this class template
2114  // specialization, which refers back to the class template
2115  // specialization we created or found.
2116  return Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType);
2117}
2118
2119TypeResult
2120Sema::ActOnTemplateIdType(CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
2121                          TemplateTy TemplateD, SourceLocation TemplateLoc,
2122                          SourceLocation LAngleLoc,
2123                          ASTTemplateArgsPtr TemplateArgsIn,
2124                          SourceLocation RAngleLoc,
2125                          bool IsCtorOrDtorName) {
2126  if (SS.isInvalid())
2127    return true;
2128
2129  TemplateName Template = TemplateD.getAsVal<TemplateName>();
2130
2131  // Translate the parser's template argument list in our AST format.
2132  TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
2133  translateTemplateArguments(TemplateArgsIn, TemplateArgs);
2134
2135  if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
2136    QualType T
2137      = Context.getDependentTemplateSpecializationType(ETK_None,
2138                                                       DTN->getQualifier(),
2139                                                       DTN->getIdentifier(),
2140                                                       TemplateArgs);
2141    // Build type-source information.
2142    TypeLocBuilder TLB;
2143    DependentTemplateSpecializationTypeLoc SpecTL
2144      = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
2145    SpecTL.setElaboratedKeywordLoc(SourceLocation());
2146    SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
2147    SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
2148    SpecTL.setTemplateNameLoc(TemplateLoc);
2149    SpecTL.setLAngleLoc(LAngleLoc);
2150    SpecTL.setRAngleLoc(RAngleLoc);
2151    for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
2152      SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
2153    return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
2154  }
2155
2156  QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
2157
2158  if (Result.isNull())
2159    return true;
2160
2161  // Build type-source information.
2162  TypeLocBuilder TLB;
2163  TemplateSpecializationTypeLoc SpecTL
2164    = TLB.push<TemplateSpecializationTypeLoc>(Result);
2165  SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
2166  SpecTL.setTemplateNameLoc(TemplateLoc);
2167  SpecTL.setLAngleLoc(LAngleLoc);
2168  SpecTL.setRAngleLoc(RAngleLoc);
2169  for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
2170    SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
2171
2172  // NOTE: avoid constructing an ElaboratedTypeLoc if this is a
2173  // constructor or destructor name (in such a case, the scope specifier
2174  // will be attached to the enclosing Decl or Expr node).
2175  if (SS.isNotEmpty() && !IsCtorOrDtorName) {
2176    // Create an elaborated-type-specifier containing the nested-name-specifier.
2177    Result = Context.getElaboratedType(ETK_None, SS.getScopeRep(), Result);
2178    ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
2179    ElabTL.setElaboratedKeywordLoc(SourceLocation());
2180    ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
2181  }
2182
2183  return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
2184}
2185
2186TypeResult Sema::ActOnTagTemplateIdType(TagUseKind TUK,
2187                                        TypeSpecifierType TagSpec,
2188                                        SourceLocation TagLoc,
2189                                        CXXScopeSpec &SS,
2190                                        SourceLocation TemplateKWLoc,
2191                                        TemplateTy TemplateD,
2192                                        SourceLocation TemplateLoc,
2193                                        SourceLocation LAngleLoc,
2194                                        ASTTemplateArgsPtr TemplateArgsIn,
2195                                        SourceLocation RAngleLoc) {
2196  TemplateName Template = TemplateD.getAsVal<TemplateName>();
2197
2198  // Translate the parser's template argument list in our AST format.
2199  TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
2200  translateTemplateArguments(TemplateArgsIn, TemplateArgs);
2201
2202  // Determine the tag kind
2203  TagTypeKind TagKind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
2204  ElaboratedTypeKeyword Keyword
2205    = TypeWithKeyword::getKeywordForTagTypeKind(TagKind);
2206
2207  if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
2208    QualType T = Context.getDependentTemplateSpecializationType(Keyword,
2209                                                          DTN->getQualifier(),
2210                                                          DTN->getIdentifier(),
2211                                                                TemplateArgs);
2212
2213    // Build type-source information.
2214    TypeLocBuilder TLB;
2215    DependentTemplateSpecializationTypeLoc SpecTL
2216      = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
2217    SpecTL.setElaboratedKeywordLoc(TagLoc);
2218    SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
2219    SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
2220    SpecTL.setTemplateNameLoc(TemplateLoc);
2221    SpecTL.setLAngleLoc(LAngleLoc);
2222    SpecTL.setRAngleLoc(RAngleLoc);
2223    for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
2224      SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
2225    return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
2226  }
2227
2228  if (TypeAliasTemplateDecl *TAT =
2229        dyn_cast_or_null<TypeAliasTemplateDecl>(Template.getAsTemplateDecl())) {
2230    // C++0x [dcl.type.elab]p2:
2231    //   If the identifier resolves to a typedef-name or the simple-template-id
2232    //   resolves to an alias template specialization, the
2233    //   elaborated-type-specifier is ill-formed.
2234    Diag(TemplateLoc, diag::err_tag_reference_non_tag) << 4;
2235    Diag(TAT->getLocation(), diag::note_declared_at);
2236  }
2237
2238  QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
2239  if (Result.isNull())
2240    return TypeResult(true);
2241
2242  // Check the tag kind
2243  if (const RecordType *RT = Result->getAs<RecordType>()) {
2244    RecordDecl *D = RT->getDecl();
2245
2246    IdentifierInfo *Id = D->getIdentifier();
2247    assert(Id && "templated class must have an identifier");
2248
2249    if (!isAcceptableTagRedeclaration(D, TagKind, TUK == TUK_Definition,
2250                                      TagLoc, *Id)) {
2251      Diag(TagLoc, diag::err_use_with_wrong_tag)
2252        << Result
2253        << FixItHint::CreateReplacement(SourceRange(TagLoc), D->getKindName());
2254      Diag(D->getLocation(), diag::note_previous_use);
2255    }
2256  }
2257
2258  // Provide source-location information for the template specialization.
2259  TypeLocBuilder TLB;
2260  TemplateSpecializationTypeLoc SpecTL
2261    = TLB.push<TemplateSpecializationTypeLoc>(Result);
2262  SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
2263  SpecTL.setTemplateNameLoc(TemplateLoc);
2264  SpecTL.setLAngleLoc(LAngleLoc);
2265  SpecTL.setRAngleLoc(RAngleLoc);
2266  for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
2267    SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
2268
2269  // Construct an elaborated type containing the nested-name-specifier (if any)
2270  // and tag keyword.
2271  Result = Context.getElaboratedType(Keyword, SS.getScopeRep(), Result);
2272  ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
2273  ElabTL.setElaboratedKeywordLoc(TagLoc);
2274  ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
2275  return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
2276}
2277
2278ExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,
2279                                     SourceLocation TemplateKWLoc,
2280                                     LookupResult &R,
2281                                     bool RequiresADL,
2282                                 const TemplateArgumentListInfo *TemplateArgs) {
2283  // FIXME: Can we do any checking at this point? I guess we could check the
2284  // template arguments that we have against the template name, if the template
2285  // name refers to a single template. That's not a terribly common case,
2286  // though.
2287  // foo<int> could identify a single function unambiguously
2288  // This approach does NOT work, since f<int>(1);
2289  // gets resolved prior to resorting to overload resolution
2290  // i.e., template<class T> void f(double);
2291  //       vs template<class T, class U> void f(U);
2292
2293  // These should be filtered out by our callers.
2294  assert(!R.empty() && "empty lookup results when building templateid");
2295  assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
2296
2297  // We don't want lookup warnings at this point.
2298  R.suppressDiagnostics();
2299
2300  UnresolvedLookupExpr *ULE
2301    = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
2302                                   SS.getWithLocInContext(Context),
2303                                   TemplateKWLoc,
2304                                   R.getLookupNameInfo(),
2305                                   RequiresADL, TemplateArgs,
2306                                   R.begin(), R.end());
2307
2308  return Owned(ULE);
2309}
2310
2311// We actually only call this from template instantiation.
2312ExprResult
2313Sema::BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
2314                                   SourceLocation TemplateKWLoc,
2315                                   const DeclarationNameInfo &NameInfo,
2316                             const TemplateArgumentListInfo *TemplateArgs) {
2317  assert(TemplateArgs || TemplateKWLoc.isValid());
2318  DeclContext *DC;
2319  if (!(DC = computeDeclContext(SS, false)) ||
2320      DC->isDependentContext() ||
2321      RequireCompleteDeclContext(SS, DC))
2322    return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
2323
2324  bool MemberOfUnknownSpecialization;
2325  LookupResult R(*this, NameInfo, LookupOrdinaryName);
2326  LookupTemplateName(R, (Scope*) 0, SS, QualType(), /*Entering*/ false,
2327                     MemberOfUnknownSpecialization);
2328
2329  if (R.isAmbiguous())
2330    return ExprError();
2331
2332  if (R.empty()) {
2333    Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_non_template)
2334      << NameInfo.getName() << SS.getRange();
2335    return ExprError();
2336  }
2337
2338  if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>()) {
2339    Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_class_template)
2340      << (NestedNameSpecifier*) SS.getScopeRep()
2341      << NameInfo.getName() << SS.getRange();
2342    Diag(Temp->getLocation(), diag::note_referenced_class_template);
2343    return ExprError();
2344  }
2345
2346  return BuildTemplateIdExpr(SS, TemplateKWLoc, R, /*ADL*/ false, TemplateArgs);
2347}
2348
2349/// \brief Form a dependent template name.
2350///
2351/// This action forms a dependent template name given the template
2352/// name and its (presumably dependent) scope specifier. For
2353/// example, given "MetaFun::template apply", the scope specifier \p
2354/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
2355/// of the "template" keyword, and "apply" is the \p Name.
2356TemplateNameKind Sema::ActOnDependentTemplateName(Scope *S,
2357                                                  CXXScopeSpec &SS,
2358                                                  SourceLocation TemplateKWLoc,
2359                                                  UnqualifiedId &Name,
2360                                                  ParsedType ObjectType,
2361                                                  bool EnteringContext,
2362                                                  TemplateTy &Result) {
2363  if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent())
2364    Diag(TemplateKWLoc,
2365         getLangOpts().CPlusPlus11 ?
2366           diag::warn_cxx98_compat_template_outside_of_template :
2367           diag::ext_template_outside_of_template)
2368      << FixItHint::CreateRemoval(TemplateKWLoc);
2369
2370  DeclContext *LookupCtx = 0;
2371  if (SS.isSet())
2372    LookupCtx = computeDeclContext(SS, EnteringContext);
2373  if (!LookupCtx && ObjectType)
2374    LookupCtx = computeDeclContext(ObjectType.get());
2375  if (LookupCtx) {
2376    // C++0x [temp.names]p5:
2377    //   If a name prefixed by the keyword template is not the name of
2378    //   a template, the program is ill-formed. [Note: the keyword
2379    //   template may not be applied to non-template members of class
2380    //   templates. -end note ] [ Note: as is the case with the
2381    //   typename prefix, the template prefix is allowed in cases
2382    //   where it is not strictly necessary; i.e., when the
2383    //   nested-name-specifier or the expression on the left of the ->
2384    //   or . is not dependent on a template-parameter, or the use
2385    //   does not appear in the scope of a template. -end note]
2386    //
2387    // Note: C++03 was more strict here, because it banned the use of
2388    // the "template" keyword prior to a template-name that was not a
2389    // dependent name. C++ DR468 relaxed this requirement (the
2390    // "template" keyword is now permitted). We follow the C++0x
2391    // rules, even in C++03 mode with a warning, retroactively applying the DR.
2392    bool MemberOfUnknownSpecialization;
2393    TemplateNameKind TNK = isTemplateName(S, SS, TemplateKWLoc.isValid(), Name,
2394                                          ObjectType, EnteringContext, Result,
2395                                          MemberOfUnknownSpecialization);
2396    if (TNK == TNK_Non_template && LookupCtx->isDependentContext() &&
2397        isa<CXXRecordDecl>(LookupCtx) &&
2398        (!cast<CXXRecordDecl>(LookupCtx)->hasDefinition() ||
2399         cast<CXXRecordDecl>(LookupCtx)->hasAnyDependentBases())) {
2400      // This is a dependent template. Handle it below.
2401    } else if (TNK == TNK_Non_template) {
2402      Diag(Name.getLocStart(),
2403           diag::err_template_kw_refers_to_non_template)
2404        << GetNameFromUnqualifiedId(Name).getName()
2405        << Name.getSourceRange()
2406        << TemplateKWLoc;
2407      return TNK_Non_template;
2408    } else {
2409      // We found something; return it.
2410      return TNK;
2411    }
2412  }
2413
2414  NestedNameSpecifier *Qualifier
2415    = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
2416
2417  switch (Name.getKind()) {
2418  case UnqualifiedId::IK_Identifier:
2419    Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
2420                                                              Name.Identifier));
2421    return TNK_Dependent_template_name;
2422
2423  case UnqualifiedId::IK_OperatorFunctionId:
2424    Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
2425                                             Name.OperatorFunctionId.Operator));
2426    return TNK_Dependent_template_name;
2427
2428  case UnqualifiedId::IK_LiteralOperatorId:
2429    llvm_unreachable(
2430            "We don't support these; Parse shouldn't have allowed propagation");
2431
2432  default:
2433    break;
2434  }
2435
2436  Diag(Name.getLocStart(),
2437       diag::err_template_kw_refers_to_non_template)
2438    << GetNameFromUnqualifiedId(Name).getName()
2439    << Name.getSourceRange()
2440    << TemplateKWLoc;
2441  return TNK_Non_template;
2442}
2443
2444bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
2445                                     const TemplateArgumentLoc &AL,
2446                          SmallVectorImpl<TemplateArgument> &Converted) {
2447  const TemplateArgument &Arg = AL.getArgument();
2448
2449  // Check template type parameter.
2450  switch(Arg.getKind()) {
2451  case TemplateArgument::Type:
2452    // C++ [temp.arg.type]p1:
2453    //   A template-argument for a template-parameter which is a
2454    //   type shall be a type-id.
2455    break;
2456  case TemplateArgument::Template: {
2457    // We have a template type parameter but the template argument
2458    // is a template without any arguments.
2459    SourceRange SR = AL.getSourceRange();
2460    TemplateName Name = Arg.getAsTemplate();
2461    Diag(SR.getBegin(), diag::err_template_missing_args)
2462      << Name << SR;
2463    if (TemplateDecl *Decl = Name.getAsTemplateDecl())
2464      Diag(Decl->getLocation(), diag::note_template_decl_here);
2465
2466    return true;
2467  }
2468  case TemplateArgument::Expression: {
2469    // We have a template type parameter but the template argument is an
2470    // expression; see if maybe it is missing the "typename" keyword.
2471    CXXScopeSpec SS;
2472    DeclarationNameInfo NameInfo;
2473
2474    if (DeclRefExpr *ArgExpr = dyn_cast<DeclRefExpr>(Arg.getAsExpr())) {
2475      SS.Adopt(ArgExpr->getQualifierLoc());
2476      NameInfo = ArgExpr->getNameInfo();
2477    } else if (DependentScopeDeclRefExpr *ArgExpr =
2478               dyn_cast<DependentScopeDeclRefExpr>(Arg.getAsExpr())) {
2479      SS.Adopt(ArgExpr->getQualifierLoc());
2480      NameInfo = ArgExpr->getNameInfo();
2481    } else if (CXXDependentScopeMemberExpr *ArgExpr =
2482               dyn_cast<CXXDependentScopeMemberExpr>(Arg.getAsExpr())) {
2483      if (ArgExpr->isImplicitAccess()) {
2484        SS.Adopt(ArgExpr->getQualifierLoc());
2485        NameInfo = ArgExpr->getMemberNameInfo();
2486      }
2487    }
2488
2489    if (NameInfo.getName().isIdentifier()) {
2490      LookupResult Result(*this, NameInfo, LookupOrdinaryName);
2491      LookupParsedName(Result, CurScope, &SS);
2492
2493      if (Result.getAsSingle<TypeDecl>() ||
2494          Result.getResultKind() ==
2495            LookupResult::NotFoundInCurrentInstantiation) {
2496        // FIXME: Add a FixIt and fix up the template argument for recovery.
2497        SourceLocation Loc = AL.getSourceRange().getBegin();
2498        Diag(Loc, diag::err_template_arg_must_be_type_suggest);
2499        Diag(Param->getLocation(), diag::note_template_param_here);
2500        return true;
2501      }
2502    }
2503    // fallthrough
2504  }
2505  default: {
2506    // We have a template type parameter but the template argument
2507    // is not a type.
2508    SourceRange SR = AL.getSourceRange();
2509    Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
2510    Diag(Param->getLocation(), diag::note_template_param_here);
2511
2512    return true;
2513  }
2514  }
2515
2516  if (CheckTemplateArgument(Param, AL.getTypeSourceInfo()))
2517    return true;
2518
2519  // Add the converted template type argument.
2520  QualType ArgType = Context.getCanonicalType(Arg.getAsType());
2521
2522  // Objective-C ARC:
2523  //   If an explicitly-specified template argument type is a lifetime type
2524  //   with no lifetime qualifier, the __strong lifetime qualifier is inferred.
2525  if (getLangOpts().ObjCAutoRefCount &&
2526      ArgType->isObjCLifetimeType() &&
2527      !ArgType.getObjCLifetime()) {
2528    Qualifiers Qs;
2529    Qs.setObjCLifetime(Qualifiers::OCL_Strong);
2530    ArgType = Context.getQualifiedType(ArgType, Qs);
2531  }
2532
2533  Converted.push_back(TemplateArgument(ArgType));
2534  return false;
2535}
2536
2537/// \brief Substitute template arguments into the default template argument for
2538/// the given template type parameter.
2539///
2540/// \param SemaRef the semantic analysis object for which we are performing
2541/// the substitution.
2542///
2543/// \param Template the template that we are synthesizing template arguments
2544/// for.
2545///
2546/// \param TemplateLoc the location of the template name that started the
2547/// template-id we are checking.
2548///
2549/// \param RAngleLoc the location of the right angle bracket ('>') that
2550/// terminates the template-id.
2551///
2552/// \param Param the template template parameter whose default we are
2553/// substituting into.
2554///
2555/// \param Converted the list of template arguments provided for template
2556/// parameters that precede \p Param in the template parameter list.
2557/// \returns the substituted template argument, or NULL if an error occurred.
2558static TypeSourceInfo *
2559SubstDefaultTemplateArgument(Sema &SemaRef,
2560                             TemplateDecl *Template,
2561                             SourceLocation TemplateLoc,
2562                             SourceLocation RAngleLoc,
2563                             TemplateTypeParmDecl *Param,
2564                         SmallVectorImpl<TemplateArgument> &Converted) {
2565  TypeSourceInfo *ArgType = Param->getDefaultArgumentInfo();
2566
2567  // If the argument type is dependent, instantiate it now based
2568  // on the previously-computed template arguments.
2569  if (ArgType->getType()->isDependentType()) {
2570    TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
2571                                      Converted.data(), Converted.size());
2572
2573    MultiLevelTemplateArgumentList AllTemplateArgs
2574      = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
2575
2576    Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
2577                                     Template, Converted,
2578                                     SourceRange(TemplateLoc, RAngleLoc));
2579    if (Inst)
2580      return 0;
2581
2582    Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
2583    ArgType = SemaRef.SubstType(ArgType, AllTemplateArgs,
2584                                Param->getDefaultArgumentLoc(),
2585                                Param->getDeclName());
2586  }
2587
2588  return ArgType;
2589}
2590
2591/// \brief Substitute template arguments into the default template argument for
2592/// the given non-type template parameter.
2593///
2594/// \param SemaRef the semantic analysis object for which we are performing
2595/// the substitution.
2596///
2597/// \param Template the template that we are synthesizing template arguments
2598/// for.
2599///
2600/// \param TemplateLoc the location of the template name that started the
2601/// template-id we are checking.
2602///
2603/// \param RAngleLoc the location of the right angle bracket ('>') that
2604/// terminates the template-id.
2605///
2606/// \param Param the non-type template parameter whose default we are
2607/// substituting into.
2608///
2609/// \param Converted the list of template arguments provided for template
2610/// parameters that precede \p Param in the template parameter list.
2611///
2612/// \returns the substituted template argument, or NULL if an error occurred.
2613static ExprResult
2614SubstDefaultTemplateArgument(Sema &SemaRef,
2615                             TemplateDecl *Template,
2616                             SourceLocation TemplateLoc,
2617                             SourceLocation RAngleLoc,
2618                             NonTypeTemplateParmDecl *Param,
2619                        SmallVectorImpl<TemplateArgument> &Converted) {
2620  TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
2621                                    Converted.data(), Converted.size());
2622
2623  MultiLevelTemplateArgumentList AllTemplateArgs
2624    = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
2625
2626  Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
2627                                   Template, Converted,
2628                                   SourceRange(TemplateLoc, RAngleLoc));
2629  if (Inst)
2630    return ExprError();
2631
2632  Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
2633  EnterExpressionEvaluationContext Unevaluated(SemaRef, Sema::Unevaluated);
2634  return SemaRef.SubstExpr(Param->getDefaultArgument(), AllTemplateArgs);
2635}
2636
2637/// \brief Substitute template arguments into the default template argument for
2638/// the given template template parameter.
2639///
2640/// \param SemaRef the semantic analysis object for which we are performing
2641/// the substitution.
2642///
2643/// \param Template the template that we are synthesizing template arguments
2644/// for.
2645///
2646/// \param TemplateLoc the location of the template name that started the
2647/// template-id we are checking.
2648///
2649/// \param RAngleLoc the location of the right angle bracket ('>') that
2650/// terminates the template-id.
2651///
2652/// \param Param the template template parameter whose default we are
2653/// substituting into.
2654///
2655/// \param Converted the list of template arguments provided for template
2656/// parameters that precede \p Param in the template parameter list.
2657///
2658/// \param QualifierLoc Will be set to the nested-name-specifier (with
2659/// source-location information) that precedes the template name.
2660///
2661/// \returns the substituted template argument, or NULL if an error occurred.
2662static TemplateName
2663SubstDefaultTemplateArgument(Sema &SemaRef,
2664                             TemplateDecl *Template,
2665                             SourceLocation TemplateLoc,
2666                             SourceLocation RAngleLoc,
2667                             TemplateTemplateParmDecl *Param,
2668                       SmallVectorImpl<TemplateArgument> &Converted,
2669                             NestedNameSpecifierLoc &QualifierLoc) {
2670  TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
2671                                    Converted.data(), Converted.size());
2672
2673  MultiLevelTemplateArgumentList AllTemplateArgs
2674    = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
2675
2676  Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
2677                                   Template, Converted,
2678                                   SourceRange(TemplateLoc, RAngleLoc));
2679  if (Inst)
2680    return TemplateName();
2681
2682  Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
2683  // Substitute into the nested-name-specifier first,
2684  QualifierLoc = Param->getDefaultArgument().getTemplateQualifierLoc();
2685  if (QualifierLoc) {
2686    QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
2687                                                       AllTemplateArgs);
2688    if (!QualifierLoc)
2689      return TemplateName();
2690  }
2691
2692  return SemaRef.SubstTemplateName(QualifierLoc,
2693                      Param->getDefaultArgument().getArgument().getAsTemplate(),
2694                              Param->getDefaultArgument().getTemplateNameLoc(),
2695                                   AllTemplateArgs);
2696}
2697
2698/// \brief If the given template parameter has a default template
2699/// argument, substitute into that default template argument and
2700/// return the corresponding template argument.
2701TemplateArgumentLoc
2702Sema::SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
2703                                              SourceLocation TemplateLoc,
2704                                              SourceLocation RAngleLoc,
2705                                              Decl *Param,
2706                                              SmallVectorImpl<TemplateArgument>
2707                                                &Converted,
2708                                              bool &HasDefaultArg) {
2709  HasDefaultArg = false;
2710
2711  if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
2712    if (!TypeParm->hasDefaultArgument())
2713      return TemplateArgumentLoc();
2714
2715    HasDefaultArg = true;
2716    TypeSourceInfo *DI = SubstDefaultTemplateArgument(*this, Template,
2717                                                      TemplateLoc,
2718                                                      RAngleLoc,
2719                                                      TypeParm,
2720                                                      Converted);
2721    if (DI)
2722      return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
2723
2724    return TemplateArgumentLoc();
2725  }
2726
2727  if (NonTypeTemplateParmDecl *NonTypeParm
2728        = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
2729    if (!NonTypeParm->hasDefaultArgument())
2730      return TemplateArgumentLoc();
2731
2732    HasDefaultArg = true;
2733    ExprResult Arg = SubstDefaultTemplateArgument(*this, Template,
2734                                                  TemplateLoc,
2735                                                  RAngleLoc,
2736                                                  NonTypeParm,
2737                                                  Converted);
2738    if (Arg.isInvalid())
2739      return TemplateArgumentLoc();
2740
2741    Expr *ArgE = Arg.takeAs<Expr>();
2742    return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE);
2743  }
2744
2745  TemplateTemplateParmDecl *TempTempParm
2746    = cast<TemplateTemplateParmDecl>(Param);
2747  if (!TempTempParm->hasDefaultArgument())
2748    return TemplateArgumentLoc();
2749
2750  HasDefaultArg = true;
2751  NestedNameSpecifierLoc QualifierLoc;
2752  TemplateName TName = SubstDefaultTemplateArgument(*this, Template,
2753                                                    TemplateLoc,
2754                                                    RAngleLoc,
2755                                                    TempTempParm,
2756                                                    Converted,
2757                                                    QualifierLoc);
2758  if (TName.isNull())
2759    return TemplateArgumentLoc();
2760
2761  return TemplateArgumentLoc(TemplateArgument(TName),
2762                TempTempParm->getDefaultArgument().getTemplateQualifierLoc(),
2763                TempTempParm->getDefaultArgument().getTemplateNameLoc());
2764}
2765
2766/// \brief Check that the given template argument corresponds to the given
2767/// template parameter.
2768///
2769/// \param Param The template parameter against which the argument will be
2770/// checked.
2771///
2772/// \param Arg The template argument.
2773///
2774/// \param Template The template in which the template argument resides.
2775///
2776/// \param TemplateLoc The location of the template name for the template
2777/// whose argument list we're matching.
2778///
2779/// \param RAngleLoc The location of the right angle bracket ('>') that closes
2780/// the template argument list.
2781///
2782/// \param ArgumentPackIndex The index into the argument pack where this
2783/// argument will be placed. Only valid if the parameter is a parameter pack.
2784///
2785/// \param Converted The checked, converted argument will be added to the
2786/// end of this small vector.
2787///
2788/// \param CTAK Describes how we arrived at this particular template argument:
2789/// explicitly written, deduced, etc.
2790///
2791/// \returns true on error, false otherwise.
2792bool Sema::CheckTemplateArgument(NamedDecl *Param,
2793                                 const TemplateArgumentLoc &Arg,
2794                                 NamedDecl *Template,
2795                                 SourceLocation TemplateLoc,
2796                                 SourceLocation RAngleLoc,
2797                                 unsigned ArgumentPackIndex,
2798                            SmallVectorImpl<TemplateArgument> &Converted,
2799                                 CheckTemplateArgumentKind CTAK) {
2800  // Check template type parameters.
2801  if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
2802    return CheckTemplateTypeArgument(TTP, Arg, Converted);
2803
2804  // Check non-type template parameters.
2805  if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
2806    // Do substitution on the type of the non-type template parameter
2807    // with the template arguments we've seen thus far.  But if the
2808    // template has a dependent context then we cannot substitute yet.
2809    QualType NTTPType = NTTP->getType();
2810    if (NTTP->isParameterPack() && NTTP->isExpandedParameterPack())
2811      NTTPType = NTTP->getExpansionType(ArgumentPackIndex);
2812
2813    if (NTTPType->isDependentType() &&
2814        !isa<TemplateTemplateParmDecl>(Template) &&
2815        !Template->getDeclContext()->isDependentContext()) {
2816      // Do substitution on the type of the non-type template parameter.
2817      InstantiatingTemplate Inst(*this, TemplateLoc, Template,
2818                                 NTTP, Converted,
2819                                 SourceRange(TemplateLoc, RAngleLoc));
2820      if (Inst)
2821        return true;
2822
2823      TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
2824                                        Converted.data(), Converted.size());
2825      NTTPType = SubstType(NTTPType,
2826                           MultiLevelTemplateArgumentList(TemplateArgs),
2827                           NTTP->getLocation(),
2828                           NTTP->getDeclName());
2829      // If that worked, check the non-type template parameter type
2830      // for validity.
2831      if (!NTTPType.isNull())
2832        NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
2833                                                     NTTP->getLocation());
2834      if (NTTPType.isNull())
2835        return true;
2836    }
2837
2838    switch (Arg.getArgument().getKind()) {
2839    case TemplateArgument::Null:
2840      llvm_unreachable("Should never see a NULL template argument here");
2841
2842    case TemplateArgument::Expression: {
2843      TemplateArgument Result;
2844      ExprResult Res =
2845        CheckTemplateArgument(NTTP, NTTPType, Arg.getArgument().getAsExpr(),
2846                              Result, CTAK);
2847      if (Res.isInvalid())
2848        return true;
2849
2850      Converted.push_back(Result);
2851      break;
2852    }
2853
2854    case TemplateArgument::Declaration:
2855    case TemplateArgument::Integral:
2856    case TemplateArgument::NullPtr:
2857      // We've already checked this template argument, so just copy
2858      // it to the list of converted arguments.
2859      Converted.push_back(Arg.getArgument());
2860      break;
2861
2862    case TemplateArgument::Template:
2863    case TemplateArgument::TemplateExpansion:
2864      // We were given a template template argument. It may not be ill-formed;
2865      // see below.
2866      if (DependentTemplateName *DTN
2867            = Arg.getArgument().getAsTemplateOrTemplatePattern()
2868                                              .getAsDependentTemplateName()) {
2869        // We have a template argument such as \c T::template X, which we
2870        // parsed as a template template argument. However, since we now
2871        // know that we need a non-type template argument, convert this
2872        // template name into an expression.
2873
2874        DeclarationNameInfo NameInfo(DTN->getIdentifier(),
2875                                     Arg.getTemplateNameLoc());
2876
2877        CXXScopeSpec SS;
2878        SS.Adopt(Arg.getTemplateQualifierLoc());
2879        // FIXME: the template-template arg was a DependentTemplateName,
2880        // so it was provided with a template keyword. However, its source
2881        // location is not stored in the template argument structure.
2882        SourceLocation TemplateKWLoc;
2883        ExprResult E = Owned(DependentScopeDeclRefExpr::Create(Context,
2884                                                SS.getWithLocInContext(Context),
2885                                                               TemplateKWLoc,
2886                                                               NameInfo, 0));
2887
2888        // If we parsed the template argument as a pack expansion, create a
2889        // pack expansion expression.
2890        if (Arg.getArgument().getKind() == TemplateArgument::TemplateExpansion){
2891          E = ActOnPackExpansion(E.take(), Arg.getTemplateEllipsisLoc());
2892          if (E.isInvalid())
2893            return true;
2894        }
2895
2896        TemplateArgument Result;
2897        E = CheckTemplateArgument(NTTP, NTTPType, E.take(), Result);
2898        if (E.isInvalid())
2899          return true;
2900
2901        Converted.push_back(Result);
2902        break;
2903      }
2904
2905      // We have a template argument that actually does refer to a class
2906      // template, alias template, or template template parameter, and
2907      // therefore cannot be a non-type template argument.
2908      Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
2909        << Arg.getSourceRange();
2910
2911      Diag(Param->getLocation(), diag::note_template_param_here);
2912      return true;
2913
2914    case TemplateArgument::Type: {
2915      // We have a non-type template parameter but the template
2916      // argument is a type.
2917
2918      // C++ [temp.arg]p2:
2919      //   In a template-argument, an ambiguity between a type-id and
2920      //   an expression is resolved to a type-id, regardless of the
2921      //   form of the corresponding template-parameter.
2922      //
2923      // We warn specifically about this case, since it can be rather
2924      // confusing for users.
2925      QualType T = Arg.getArgument().getAsType();
2926      SourceRange SR = Arg.getSourceRange();
2927      if (T->isFunctionType())
2928        Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
2929      else
2930        Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
2931      Diag(Param->getLocation(), diag::note_template_param_here);
2932      return true;
2933    }
2934
2935    case TemplateArgument::Pack:
2936      llvm_unreachable("Caller must expand template argument packs");
2937    }
2938
2939    return false;
2940  }
2941
2942
2943  // Check template template parameters.
2944  TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
2945
2946  // Substitute into the template parameter list of the template
2947  // template parameter, since previously-supplied template arguments
2948  // may appear within the template template parameter.
2949  {
2950    // Set up a template instantiation context.
2951    LocalInstantiationScope Scope(*this);
2952    InstantiatingTemplate Inst(*this, TemplateLoc, Template,
2953                               TempParm, Converted,
2954                               SourceRange(TemplateLoc, RAngleLoc));
2955    if (Inst)
2956      return true;
2957
2958    TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
2959                                      Converted.data(), Converted.size());
2960    TempParm = cast_or_null<TemplateTemplateParmDecl>(
2961                      SubstDecl(TempParm, CurContext,
2962                                MultiLevelTemplateArgumentList(TemplateArgs)));
2963    if (!TempParm)
2964      return true;
2965  }
2966
2967  switch (Arg.getArgument().getKind()) {
2968  case TemplateArgument::Null:
2969    llvm_unreachable("Should never see a NULL template argument here");
2970
2971  case TemplateArgument::Template:
2972  case TemplateArgument::TemplateExpansion:
2973    if (CheckTemplateArgument(TempParm, Arg, ArgumentPackIndex))
2974      return true;
2975
2976    Converted.push_back(Arg.getArgument());
2977    break;
2978
2979  case TemplateArgument::Expression:
2980  case TemplateArgument::Type:
2981    // We have a template template parameter but the template
2982    // argument does not refer to a template.
2983    Diag(Arg.getLocation(), diag::err_template_arg_must_be_template)
2984      << getLangOpts().CPlusPlus11;
2985    return true;
2986
2987  case TemplateArgument::Declaration:
2988    llvm_unreachable("Declaration argument with template template parameter");
2989  case TemplateArgument::Integral:
2990    llvm_unreachable("Integral argument with template template parameter");
2991  case TemplateArgument::NullPtr:
2992    llvm_unreachable("Null pointer argument with template template parameter");
2993
2994  case TemplateArgument::Pack:
2995    llvm_unreachable("Caller must expand template argument packs");
2996  }
2997
2998  return false;
2999}
3000
3001/// \brief Diagnose an arity mismatch in the
3002static bool diagnoseArityMismatch(Sema &S, TemplateDecl *Template,
3003                                  SourceLocation TemplateLoc,
3004                                  TemplateArgumentListInfo &TemplateArgs) {
3005  TemplateParameterList *Params = Template->getTemplateParameters();
3006  unsigned NumParams = Params->size();
3007  unsigned NumArgs = TemplateArgs.size();
3008
3009  SourceRange Range;
3010  if (NumArgs > NumParams)
3011    Range = SourceRange(TemplateArgs[NumParams].getLocation(),
3012                        TemplateArgs.getRAngleLoc());
3013  S.Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
3014    << (NumArgs > NumParams)
3015    << (isa<ClassTemplateDecl>(Template)? 0 :
3016        isa<FunctionTemplateDecl>(Template)? 1 :
3017        isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
3018    << Template << Range;
3019  S.Diag(Template->getLocation(), diag::note_template_decl_here)
3020    << Params->getSourceRange();
3021  return true;
3022}
3023
3024/// \brief Check whether the template parameter is a pack expansion, and if so,
3025/// determine the number of parameters produced by that expansion. For instance:
3026///
3027/// \code
3028/// template<typename ...Ts> struct A {
3029///   template<Ts ...NTs, template<Ts> class ...TTs, typename ...Us> struct B;
3030/// };
3031/// \endcode
3032///
3033/// In \c A<int,int>::B, \c NTs and \c TTs have expanded pack size 2, and \c Us
3034/// is not a pack expansion, so returns an empty Optional.
3035static Optional<unsigned> getExpandedPackSize(NamedDecl *Param) {
3036  if (NonTypeTemplateParmDecl *NTTP
3037        = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
3038    if (NTTP->isExpandedParameterPack())
3039      return NTTP->getNumExpansionTypes();
3040  }
3041
3042  if (TemplateTemplateParmDecl *TTP
3043        = dyn_cast<TemplateTemplateParmDecl>(Param)) {
3044    if (TTP->isExpandedParameterPack())
3045      return TTP->getNumExpansionTemplateParameters();
3046  }
3047
3048  return None;
3049}
3050
3051/// \brief Check that the given template argument list is well-formed
3052/// for specializing the given template.
3053bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
3054                                     SourceLocation TemplateLoc,
3055                                     TemplateArgumentListInfo &TemplateArgs,
3056                                     bool PartialTemplateArgs,
3057                          SmallVectorImpl<TemplateArgument> &Converted,
3058                                     bool *ExpansionIntoFixedList) {
3059  if (ExpansionIntoFixedList)
3060    *ExpansionIntoFixedList = false;
3061
3062  TemplateParameterList *Params = Template->getTemplateParameters();
3063
3064  SourceLocation RAngleLoc = TemplateArgs.getRAngleLoc();
3065
3066  // C++ [temp.arg]p1:
3067  //   [...] The type and form of each template-argument specified in
3068  //   a template-id shall match the type and form specified for the
3069  //   corresponding parameter declared by the template in its
3070  //   template-parameter-list.
3071  bool isTemplateTemplateParameter = isa<TemplateTemplateParmDecl>(Template);
3072  SmallVector<TemplateArgument, 2> ArgumentPack;
3073  unsigned ArgIdx = 0, NumArgs = TemplateArgs.size();
3074  LocalInstantiationScope InstScope(*this, true);
3075  for (TemplateParameterList::iterator Param = Params->begin(),
3076                                       ParamEnd = Params->end();
3077       Param != ParamEnd; /* increment in loop */) {
3078    // If we have an expanded parameter pack, make sure we don't have too
3079    // many arguments.
3080    if (Optional<unsigned> Expansions = getExpandedPackSize(*Param)) {
3081      if (*Expansions == ArgumentPack.size()) {
3082        // We're done with this parameter pack. Pack up its arguments and add
3083        // them to the list.
3084        Converted.push_back(
3085          TemplateArgument::CreatePackCopy(Context,
3086                                           ArgumentPack.data(),
3087                                           ArgumentPack.size()));
3088        ArgumentPack.clear();
3089
3090        // This argument is assigned to the next parameter.
3091        ++Param;
3092        continue;
3093      } else if (ArgIdx == NumArgs && !PartialTemplateArgs) {
3094        // Not enough arguments for this parameter pack.
3095        Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
3096          << false
3097          << (isa<ClassTemplateDecl>(Template)? 0 :
3098              isa<FunctionTemplateDecl>(Template)? 1 :
3099              isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
3100          << Template;
3101        Diag(Template->getLocation(), diag::note_template_decl_here)
3102          << Params->getSourceRange();
3103        return true;
3104      }
3105    }
3106
3107    if (ArgIdx < NumArgs) {
3108      // Check the template argument we were given.
3109      if (CheckTemplateArgument(*Param, TemplateArgs[ArgIdx], Template,
3110                                TemplateLoc, RAngleLoc,
3111                                ArgumentPack.size(), Converted))
3112        return true;
3113
3114      // We're now done with this argument.
3115      ++ArgIdx;
3116
3117      if ((*Param)->isTemplateParameterPack()) {
3118        // The template parameter was a template parameter pack, so take the
3119        // deduced argument and place it on the argument pack. Note that we
3120        // stay on the same template parameter so that we can deduce more
3121        // arguments.
3122        ArgumentPack.push_back(Converted.back());
3123        Converted.pop_back();
3124      } else {
3125        // Move to the next template parameter.
3126        ++Param;
3127      }
3128
3129      // If we just saw a pack expansion, then directly convert the remaining
3130      // arguments, because we don't know what parameters they'll match up
3131      // with.
3132      if (TemplateArgs[ArgIdx-1].getArgument().isPackExpansion()) {
3133        bool InFinalParameterPack = Param != ParamEnd &&
3134                                    Param + 1 == ParamEnd &&
3135                                    (*Param)->isTemplateParameterPack() &&
3136                                    !getExpandedPackSize(*Param);
3137
3138        if (!InFinalParameterPack && !ArgumentPack.empty()) {
3139          // If we were part way through filling in an expanded parameter pack,
3140          // fall back to just producing individual arguments.
3141          Converted.insert(Converted.end(),
3142                           ArgumentPack.begin(), ArgumentPack.end());
3143          ArgumentPack.clear();
3144        }
3145
3146        while (ArgIdx < NumArgs) {
3147          if (InFinalParameterPack)
3148            ArgumentPack.push_back(TemplateArgs[ArgIdx].getArgument());
3149          else
3150            Converted.push_back(TemplateArgs[ArgIdx].getArgument());
3151          ++ArgIdx;
3152        }
3153
3154        // Push the argument pack onto the list of converted arguments.
3155        if (InFinalParameterPack) {
3156          Converted.push_back(
3157            TemplateArgument::CreatePackCopy(Context,
3158                                             ArgumentPack.data(),
3159                                             ArgumentPack.size()));
3160          ArgumentPack.clear();
3161        } else if (ExpansionIntoFixedList) {
3162          // We have expanded a pack into a fixed list.
3163          *ExpansionIntoFixedList = true;
3164        }
3165
3166        return false;
3167      }
3168
3169      continue;
3170    }
3171
3172    // If we're checking a partial template argument list, we're done.
3173    if (PartialTemplateArgs) {
3174      if ((*Param)->isTemplateParameterPack() && !ArgumentPack.empty())
3175        Converted.push_back(TemplateArgument::CreatePackCopy(Context,
3176                                                         ArgumentPack.data(),
3177                                                         ArgumentPack.size()));
3178
3179      return false;
3180    }
3181
3182    // If we have a template parameter pack with no more corresponding
3183    // arguments, just break out now and we'll fill in the argument pack below.
3184    if ((*Param)->isTemplateParameterPack()) {
3185      assert(!getExpandedPackSize(*Param) &&
3186             "Should have dealt with this already");
3187
3188      // A non-expanded parameter pack before the end of the parameter list
3189      // only occurs for an ill-formed template parameter list, unless we've
3190      // got a partial argument list for a function template, so just bail out.
3191      if (Param + 1 != ParamEnd)
3192        return true;
3193
3194      Converted.push_back(TemplateArgument::CreatePackCopy(Context,
3195                                                       ArgumentPack.data(),
3196                                                       ArgumentPack.size()));
3197      ArgumentPack.clear();
3198
3199      ++Param;
3200      continue;
3201    }
3202
3203    // Check whether we have a default argument.
3204    TemplateArgumentLoc Arg;
3205
3206    // Retrieve the default template argument from the template
3207    // parameter. For each kind of template parameter, we substitute the
3208    // template arguments provided thus far and any "outer" template arguments
3209    // (when the template parameter was part of a nested template) into
3210    // the default argument.
3211    if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
3212      if (!TTP->hasDefaultArgument())
3213        return diagnoseArityMismatch(*this, Template, TemplateLoc,
3214                                     TemplateArgs);
3215
3216      TypeSourceInfo *ArgType = SubstDefaultTemplateArgument(*this,
3217                                                             Template,
3218                                                             TemplateLoc,
3219                                                             RAngleLoc,
3220                                                             TTP,
3221                                                             Converted);
3222      if (!ArgType)
3223        return true;
3224
3225      Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()),
3226                                ArgType);
3227    } else if (NonTypeTemplateParmDecl *NTTP
3228                 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
3229      if (!NTTP->hasDefaultArgument())
3230        return diagnoseArityMismatch(*this, Template, TemplateLoc,
3231                                     TemplateArgs);
3232
3233      ExprResult E = SubstDefaultTemplateArgument(*this, Template,
3234                                                              TemplateLoc,
3235                                                              RAngleLoc,
3236                                                              NTTP,
3237                                                              Converted);
3238      if (E.isInvalid())
3239        return true;
3240
3241      Expr *Ex = E.takeAs<Expr>();
3242      Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
3243    } else {
3244      TemplateTemplateParmDecl *TempParm
3245        = cast<TemplateTemplateParmDecl>(*Param);
3246
3247      if (!TempParm->hasDefaultArgument())
3248        return diagnoseArityMismatch(*this, Template, TemplateLoc,
3249                                     TemplateArgs);
3250
3251      NestedNameSpecifierLoc QualifierLoc;
3252      TemplateName Name = SubstDefaultTemplateArgument(*this, Template,
3253                                                       TemplateLoc,
3254                                                       RAngleLoc,
3255                                                       TempParm,
3256                                                       Converted,
3257                                                       QualifierLoc);
3258      if (Name.isNull())
3259        return true;
3260
3261      Arg = TemplateArgumentLoc(TemplateArgument(Name), QualifierLoc,
3262                           TempParm->getDefaultArgument().getTemplateNameLoc());
3263    }
3264
3265    // Introduce an instantiation record that describes where we are using
3266    // the default template argument.
3267    InstantiatingTemplate Instantiating(*this, RAngleLoc, Template,
3268                                        *Param, Converted,
3269                                        SourceRange(TemplateLoc, RAngleLoc));
3270    if (Instantiating)
3271      return true;
3272
3273    // Check the default template argument.
3274    if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc,
3275                              RAngleLoc, 0, Converted))
3276      return true;
3277
3278    // Core issue 150 (assumed resolution): if this is a template template
3279    // parameter, keep track of the default template arguments from the
3280    // template definition.
3281    if (isTemplateTemplateParameter)
3282      TemplateArgs.addArgument(Arg);
3283
3284    // Move to the next template parameter and argument.
3285    ++Param;
3286    ++ArgIdx;
3287  }
3288
3289  // If we have any leftover arguments, then there were too many arguments.
3290  // Complain and fail.
3291  if (ArgIdx < NumArgs)
3292    return diagnoseArityMismatch(*this, Template, TemplateLoc, TemplateArgs);
3293
3294  return false;
3295}
3296
3297namespace {
3298  class UnnamedLocalNoLinkageFinder
3299    : public TypeVisitor<UnnamedLocalNoLinkageFinder, bool>
3300  {
3301    Sema &S;
3302    SourceRange SR;
3303
3304    typedef TypeVisitor<UnnamedLocalNoLinkageFinder, bool> inherited;
3305
3306  public:
3307    UnnamedLocalNoLinkageFinder(Sema &S, SourceRange SR) : S(S), SR(SR) { }
3308
3309    bool Visit(QualType T) {
3310      return inherited::Visit(T.getTypePtr());
3311    }
3312
3313#define TYPE(Class, Parent) \
3314    bool Visit##Class##Type(const Class##Type *);
3315#define ABSTRACT_TYPE(Class, Parent) \
3316    bool Visit##Class##Type(const Class##Type *) { return false; }
3317#define NON_CANONICAL_TYPE(Class, Parent) \
3318    bool Visit##Class##Type(const Class##Type *) { return false; }
3319#include "clang/AST/TypeNodes.def"
3320
3321    bool VisitTagDecl(const TagDecl *Tag);
3322    bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS);
3323  };
3324}
3325
3326bool UnnamedLocalNoLinkageFinder::VisitBuiltinType(const BuiltinType*) {
3327  return false;
3328}
3329
3330bool UnnamedLocalNoLinkageFinder::VisitComplexType(const ComplexType* T) {
3331  return Visit(T->getElementType());
3332}
3333
3334bool UnnamedLocalNoLinkageFinder::VisitPointerType(const PointerType* T) {
3335  return Visit(T->getPointeeType());
3336}
3337
3338bool UnnamedLocalNoLinkageFinder::VisitBlockPointerType(
3339                                                    const BlockPointerType* T) {
3340  return Visit(T->getPointeeType());
3341}
3342
3343bool UnnamedLocalNoLinkageFinder::VisitLValueReferenceType(
3344                                                const LValueReferenceType* T) {
3345  return Visit(T->getPointeeType());
3346}
3347
3348bool UnnamedLocalNoLinkageFinder::VisitRValueReferenceType(
3349                                                const RValueReferenceType* T) {
3350  return Visit(T->getPointeeType());
3351}
3352
3353bool UnnamedLocalNoLinkageFinder::VisitMemberPointerType(
3354                                                  const MemberPointerType* T) {
3355  return Visit(T->getPointeeType()) || Visit(QualType(T->getClass(), 0));
3356}
3357
3358bool UnnamedLocalNoLinkageFinder::VisitConstantArrayType(
3359                                                  const ConstantArrayType* T) {
3360  return Visit(T->getElementType());
3361}
3362
3363bool UnnamedLocalNoLinkageFinder::VisitIncompleteArrayType(
3364                                                 const IncompleteArrayType* T) {
3365  return Visit(T->getElementType());
3366}
3367
3368bool UnnamedLocalNoLinkageFinder::VisitVariableArrayType(
3369                                                   const VariableArrayType* T) {
3370  return Visit(T->getElementType());
3371}
3372
3373bool UnnamedLocalNoLinkageFinder::VisitDependentSizedArrayType(
3374                                            const DependentSizedArrayType* T) {
3375  return Visit(T->getElementType());
3376}
3377
3378bool UnnamedLocalNoLinkageFinder::VisitDependentSizedExtVectorType(
3379                                         const DependentSizedExtVectorType* T) {
3380  return Visit(T->getElementType());
3381}
3382
3383bool UnnamedLocalNoLinkageFinder::VisitVectorType(const VectorType* T) {
3384  return Visit(T->getElementType());
3385}
3386
3387bool UnnamedLocalNoLinkageFinder::VisitExtVectorType(const ExtVectorType* T) {
3388  return Visit(T->getElementType());
3389}
3390
3391bool UnnamedLocalNoLinkageFinder::VisitFunctionProtoType(
3392                                                  const FunctionProtoType* T) {
3393  for (FunctionProtoType::arg_type_iterator A = T->arg_type_begin(),
3394                                         AEnd = T->arg_type_end();
3395       A != AEnd; ++A) {
3396    if (Visit(*A))
3397      return true;
3398  }
3399
3400  return Visit(T->getResultType());
3401}
3402
3403bool UnnamedLocalNoLinkageFinder::VisitFunctionNoProtoType(
3404                                               const FunctionNoProtoType* T) {
3405  return Visit(T->getResultType());
3406}
3407
3408bool UnnamedLocalNoLinkageFinder::VisitUnresolvedUsingType(
3409                                                  const UnresolvedUsingType*) {
3410  return false;
3411}
3412
3413bool UnnamedLocalNoLinkageFinder::VisitTypeOfExprType(const TypeOfExprType*) {
3414  return false;
3415}
3416
3417bool UnnamedLocalNoLinkageFinder::VisitTypeOfType(const TypeOfType* T) {
3418  return Visit(T->getUnderlyingType());
3419}
3420
3421bool UnnamedLocalNoLinkageFinder::VisitDecltypeType(const DecltypeType*) {
3422  return false;
3423}
3424
3425bool UnnamedLocalNoLinkageFinder::VisitUnaryTransformType(
3426                                                    const UnaryTransformType*) {
3427  return false;
3428}
3429
3430bool UnnamedLocalNoLinkageFinder::VisitAutoType(const AutoType *T) {
3431  return Visit(T->getDeducedType());
3432}
3433
3434bool UnnamedLocalNoLinkageFinder::VisitRecordType(const RecordType* T) {
3435  return VisitTagDecl(T->getDecl());
3436}
3437
3438bool UnnamedLocalNoLinkageFinder::VisitEnumType(const EnumType* T) {
3439  return VisitTagDecl(T->getDecl());
3440}
3441
3442bool UnnamedLocalNoLinkageFinder::VisitTemplateTypeParmType(
3443                                                 const TemplateTypeParmType*) {
3444  return false;
3445}
3446
3447bool UnnamedLocalNoLinkageFinder::VisitSubstTemplateTypeParmPackType(
3448                                        const SubstTemplateTypeParmPackType *) {
3449  return false;
3450}
3451
3452bool UnnamedLocalNoLinkageFinder::VisitTemplateSpecializationType(
3453                                            const TemplateSpecializationType*) {
3454  return false;
3455}
3456
3457bool UnnamedLocalNoLinkageFinder::VisitInjectedClassNameType(
3458                                              const InjectedClassNameType* T) {
3459  return VisitTagDecl(T->getDecl());
3460}
3461
3462bool UnnamedLocalNoLinkageFinder::VisitDependentNameType(
3463                                                   const DependentNameType* T) {
3464  return VisitNestedNameSpecifier(T->getQualifier());
3465}
3466
3467bool UnnamedLocalNoLinkageFinder::VisitDependentTemplateSpecializationType(
3468                                 const DependentTemplateSpecializationType* T) {
3469  return VisitNestedNameSpecifier(T->getQualifier());
3470}
3471
3472bool UnnamedLocalNoLinkageFinder::VisitPackExpansionType(
3473                                                   const PackExpansionType* T) {
3474  return Visit(T->getPattern());
3475}
3476
3477bool UnnamedLocalNoLinkageFinder::VisitObjCObjectType(const ObjCObjectType *) {
3478  return false;
3479}
3480
3481bool UnnamedLocalNoLinkageFinder::VisitObjCInterfaceType(
3482                                                   const ObjCInterfaceType *) {
3483  return false;
3484}
3485
3486bool UnnamedLocalNoLinkageFinder::VisitObjCObjectPointerType(
3487                                                const ObjCObjectPointerType *) {
3488  return false;
3489}
3490
3491bool UnnamedLocalNoLinkageFinder::VisitAtomicType(const AtomicType* T) {
3492  return Visit(T->getValueType());
3493}
3494
3495bool UnnamedLocalNoLinkageFinder::VisitTagDecl(const TagDecl *Tag) {
3496  if (Tag->getDeclContext()->isFunctionOrMethod()) {
3497    S.Diag(SR.getBegin(),
3498           S.getLangOpts().CPlusPlus11 ?
3499             diag::warn_cxx98_compat_template_arg_local_type :
3500             diag::ext_template_arg_local_type)
3501      << S.Context.getTypeDeclType(Tag) << SR;
3502    return true;
3503  }
3504
3505  if (!Tag->hasNameForLinkage()) {
3506    S.Diag(SR.getBegin(),
3507           S.getLangOpts().CPlusPlus11 ?
3508             diag::warn_cxx98_compat_template_arg_unnamed_type :
3509             diag::ext_template_arg_unnamed_type) << SR;
3510    S.Diag(Tag->getLocation(), diag::note_template_unnamed_type_here);
3511    return true;
3512  }
3513
3514  return false;
3515}
3516
3517bool UnnamedLocalNoLinkageFinder::VisitNestedNameSpecifier(
3518                                                    NestedNameSpecifier *NNS) {
3519  if (NNS->getPrefix() && VisitNestedNameSpecifier(NNS->getPrefix()))
3520    return true;
3521
3522  switch (NNS->getKind()) {
3523  case NestedNameSpecifier::Identifier:
3524  case NestedNameSpecifier::Namespace:
3525  case NestedNameSpecifier::NamespaceAlias:
3526  case NestedNameSpecifier::Global:
3527    return false;
3528
3529  case NestedNameSpecifier::TypeSpec:
3530  case NestedNameSpecifier::TypeSpecWithTemplate:
3531    return Visit(QualType(NNS->getAsType(), 0));
3532  }
3533  llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
3534}
3535
3536
3537/// \brief Check a template argument against its corresponding
3538/// template type parameter.
3539///
3540/// This routine implements the semantics of C++ [temp.arg.type]. It
3541/// returns true if an error occurred, and false otherwise.
3542bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
3543                                 TypeSourceInfo *ArgInfo) {
3544  assert(ArgInfo && "invalid TypeSourceInfo");
3545  QualType Arg = ArgInfo->getType();
3546  SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
3547
3548  if (Arg->isVariablyModifiedType()) {
3549    return Diag(SR.getBegin(), diag::err_variably_modified_template_arg) << Arg;
3550  } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
3551    return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
3552  }
3553
3554  // C++03 [temp.arg.type]p2:
3555  //   A local type, a type with no linkage, an unnamed type or a type
3556  //   compounded from any of these types shall not be used as a
3557  //   template-argument for a template type-parameter.
3558  //
3559  // C++11 allows these, and even in C++03 we allow them as an extension with
3560  // a warning.
3561  if (LangOpts.CPlusPlus11 ?
3562     Diags.getDiagnosticLevel(diag::warn_cxx98_compat_template_arg_unnamed_type,
3563                              SR.getBegin()) != DiagnosticsEngine::Ignored ||
3564      Diags.getDiagnosticLevel(diag::warn_cxx98_compat_template_arg_local_type,
3565                               SR.getBegin()) != DiagnosticsEngine::Ignored :
3566      Arg->hasUnnamedOrLocalType()) {
3567    UnnamedLocalNoLinkageFinder Finder(*this, SR);
3568    (void)Finder.Visit(Context.getCanonicalType(Arg));
3569  }
3570
3571  return false;
3572}
3573
3574enum NullPointerValueKind {
3575  NPV_NotNullPointer,
3576  NPV_NullPointer,
3577  NPV_Error
3578};
3579
3580/// \brief Determine whether the given template argument is a null pointer
3581/// value of the appropriate type.
3582static NullPointerValueKind
3583isNullPointerValueTemplateArgument(Sema &S, NonTypeTemplateParmDecl *Param,
3584                                   QualType ParamType, Expr *Arg) {
3585  if (Arg->isValueDependent() || Arg->isTypeDependent())
3586    return NPV_NotNullPointer;
3587
3588  if (!S.getLangOpts().CPlusPlus11)
3589    return NPV_NotNullPointer;
3590
3591  // Determine whether we have a constant expression.
3592  ExprResult ArgRV = S.DefaultFunctionArrayConversion(Arg);
3593  if (ArgRV.isInvalid())
3594    return NPV_Error;
3595  Arg = ArgRV.take();
3596
3597  Expr::EvalResult EvalResult;
3598  SmallVector<PartialDiagnosticAt, 8> Notes;
3599  EvalResult.Diag = &Notes;
3600  if (!Arg->EvaluateAsRValue(EvalResult, S.Context) ||
3601      EvalResult.HasSideEffects) {
3602    SourceLocation DiagLoc = Arg->getExprLoc();
3603
3604    // If our only note is the usual "invalid subexpression" note, just point
3605    // the caret at its location rather than producing an essentially
3606    // redundant note.
3607    if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
3608        diag::note_invalid_subexpr_in_const_expr) {
3609      DiagLoc = Notes[0].first;
3610      Notes.clear();
3611    }
3612
3613    S.Diag(DiagLoc, diag::err_template_arg_not_address_constant)
3614      << Arg->getType() << Arg->getSourceRange();
3615    for (unsigned I = 0, N = Notes.size(); I != N; ++I)
3616      S.Diag(Notes[I].first, Notes[I].second);
3617
3618    S.Diag(Param->getLocation(), diag::note_template_param_here);
3619    return NPV_Error;
3620  }
3621
3622  // C++11 [temp.arg.nontype]p1:
3623  //   - an address constant expression of type std::nullptr_t
3624  if (Arg->getType()->isNullPtrType())
3625    return NPV_NullPointer;
3626
3627  //   - a constant expression that evaluates to a null pointer value (4.10); or
3628  //   - a constant expression that evaluates to a null member pointer value
3629  //     (4.11); or
3630  if ((EvalResult.Val.isLValue() && !EvalResult.Val.getLValueBase()) ||
3631      (EvalResult.Val.isMemberPointer() &&
3632       !EvalResult.Val.getMemberPointerDecl())) {
3633    // If our expression has an appropriate type, we've succeeded.
3634    bool ObjCLifetimeConversion;
3635    if (S.Context.hasSameUnqualifiedType(Arg->getType(), ParamType) ||
3636        S.IsQualificationConversion(Arg->getType(), ParamType, false,
3637                                     ObjCLifetimeConversion))
3638      return NPV_NullPointer;
3639
3640    // The types didn't match, but we know we got a null pointer; complain,
3641    // then recover as if the types were correct.
3642    S.Diag(Arg->getExprLoc(), diag::err_template_arg_wrongtype_null_constant)
3643      << Arg->getType() << ParamType << Arg->getSourceRange();
3644    S.Diag(Param->getLocation(), diag::note_template_param_here);
3645    return NPV_NullPointer;
3646  }
3647
3648  // If we don't have a null pointer value, but we do have a NULL pointer
3649  // constant, suggest a cast to the appropriate type.
3650  if (Arg->isNullPointerConstant(S.Context, Expr::NPC_NeverValueDependent)) {
3651    std::string Code = "static_cast<" + ParamType.getAsString() + ">(";
3652    S.Diag(Arg->getExprLoc(), diag::err_template_arg_untyped_null_constant)
3653      << ParamType
3654      << FixItHint::CreateInsertion(Arg->getLocStart(), Code)
3655      << FixItHint::CreateInsertion(S.PP.getLocForEndOfToken(Arg->getLocEnd()),
3656                                    ")");
3657    S.Diag(Param->getLocation(), diag::note_template_param_here);
3658    return NPV_NullPointer;
3659  }
3660
3661  // FIXME: If we ever want to support general, address-constant expressions
3662  // as non-type template arguments, we should return the ExprResult here to
3663  // be interpreted by the caller.
3664  return NPV_NotNullPointer;
3665}
3666
3667/// \brief Checks whether the given template argument is the address
3668/// of an object or function according to C++ [temp.arg.nontype]p1.
3669static bool
3670CheckTemplateArgumentAddressOfObjectOrFunction(Sema &S,
3671                                               NonTypeTemplateParmDecl *Param,
3672                                               QualType ParamType,
3673                                               Expr *ArgIn,
3674                                               TemplateArgument &Converted) {
3675  bool Invalid = false;
3676  Expr *Arg = ArgIn;
3677  QualType ArgType = Arg->getType();
3678
3679  // If our parameter has pointer type, check for a null template value.
3680  if (ParamType->isPointerType() || ParamType->isNullPtrType()) {
3681    switch (isNullPointerValueTemplateArgument(S, Param, ParamType, Arg)) {
3682    case NPV_NullPointer:
3683      S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
3684      Converted = TemplateArgument(ParamType, /*isNullPtr*/true);
3685      return false;
3686
3687    case NPV_Error:
3688      return true;
3689
3690    case NPV_NotNullPointer:
3691      break;
3692    }
3693  }
3694
3695  // See through any implicit casts we added to fix the type.
3696  Arg = Arg->IgnoreImpCasts();
3697
3698  // C++ [temp.arg.nontype]p1:
3699  //
3700  //   A template-argument for a non-type, non-template
3701  //   template-parameter shall be one of: [...]
3702  //
3703  //     -- the address of an object or function with external
3704  //        linkage, including function templates and function
3705  //        template-ids but excluding non-static class members,
3706  //        expressed as & id-expression where the & is optional if
3707  //        the name refers to a function or array, or if the
3708  //        corresponding template-parameter is a reference; or
3709
3710  // In C++98/03 mode, give an extension warning on any extra parentheses.
3711  // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
3712  bool ExtraParens = false;
3713  while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
3714    if (!Invalid && !ExtraParens) {
3715      S.Diag(Arg->getLocStart(),
3716             S.getLangOpts().CPlusPlus11 ?
3717               diag::warn_cxx98_compat_template_arg_extra_parens :
3718               diag::ext_template_arg_extra_parens)
3719        << Arg->getSourceRange();
3720      ExtraParens = true;
3721    }
3722
3723    Arg = Parens->getSubExpr();
3724  }
3725
3726  while (SubstNonTypeTemplateParmExpr *subst =
3727           dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
3728    Arg = subst->getReplacement()->IgnoreImpCasts();
3729
3730  bool AddressTaken = false;
3731  SourceLocation AddrOpLoc;
3732  if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
3733    if (UnOp->getOpcode() == UO_AddrOf) {
3734      Arg = UnOp->getSubExpr();
3735      AddressTaken = true;
3736      AddrOpLoc = UnOp->getOperatorLoc();
3737    }
3738  }
3739
3740  if (isa<CXXUuidofExpr>(Arg)) {
3741    Converted = TemplateArgument(ArgIn);
3742    return false;
3743  }
3744
3745  while (SubstNonTypeTemplateParmExpr *subst =
3746           dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
3747    Arg = subst->getReplacement()->IgnoreImpCasts();
3748
3749  // Stop checking the precise nature of the argument if it is value dependent,
3750  // it should be checked when instantiated.
3751  if (Arg->isValueDependent()) {
3752    Converted = TemplateArgument(ArgIn);
3753    return false;
3754  }
3755
3756  DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg);
3757  if (!DRE) {
3758    S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
3759    << Arg->getSourceRange();
3760    S.Diag(Param->getLocation(), diag::note_template_param_here);
3761    return true;
3762  }
3763
3764  if (!isa<ValueDecl>(DRE->getDecl())) {
3765    S.Diag(Arg->getLocStart(),
3766           diag::err_template_arg_not_object_or_func_form)
3767      << Arg->getSourceRange();
3768    S.Diag(Param->getLocation(), diag::note_template_param_here);
3769    return true;
3770  }
3771
3772  ValueDecl *Entity = DRE->getDecl();
3773
3774  // Cannot refer to non-static data members
3775  if (FieldDecl *Field = dyn_cast<FieldDecl>(Entity)) {
3776    S.Diag(Arg->getLocStart(), diag::err_template_arg_field)
3777      << Field << Arg->getSourceRange();
3778    S.Diag(Param->getLocation(), diag::note_template_param_here);
3779    return true;
3780  }
3781
3782  // Cannot refer to non-static member functions
3783  if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Entity)) {
3784    if (!Method->isStatic()) {
3785      S.Diag(Arg->getLocStart(), diag::err_template_arg_method)
3786        << Method << Arg->getSourceRange();
3787      S.Diag(Param->getLocation(), diag::note_template_param_here);
3788      return true;
3789    }
3790  }
3791
3792  FunctionDecl *Func = dyn_cast<FunctionDecl>(Entity);
3793  VarDecl *Var = dyn_cast<VarDecl>(Entity);
3794
3795  // A non-type template argument must refer to an object or function.
3796  if (!Func && !Var) {
3797    // We found something, but we don't know specifically what it is.
3798    S.Diag(Arg->getLocStart(), diag::err_template_arg_not_object_or_func)
3799      << Arg->getSourceRange();
3800    S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
3801    return true;
3802  }
3803
3804  // Address / reference template args must have external linkage in C++98.
3805  if (Entity->getFormalLinkage() == InternalLinkage) {
3806    S.Diag(Arg->getLocStart(), S.getLangOpts().CPlusPlus11 ?
3807             diag::warn_cxx98_compat_template_arg_object_internal :
3808             diag::ext_template_arg_object_internal)
3809      << !Func << Entity << Arg->getSourceRange();
3810    S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
3811      << !Func;
3812  } else if (!Entity->hasLinkage()) {
3813    S.Diag(Arg->getLocStart(), diag::err_template_arg_object_no_linkage)
3814      << !Func << Entity << Arg->getSourceRange();
3815    S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
3816      << !Func;
3817    return true;
3818  }
3819
3820  if (Func) {
3821    // If the template parameter has pointer type, the function decays.
3822    if (ParamType->isPointerType() && !AddressTaken)
3823      ArgType = S.Context.getPointerType(Func->getType());
3824    else if (AddressTaken && ParamType->isReferenceType()) {
3825      // If we originally had an address-of operator, but the
3826      // parameter has reference type, complain and (if things look
3827      // like they will work) drop the address-of operator.
3828      if (!S.Context.hasSameUnqualifiedType(Func->getType(),
3829                                            ParamType.getNonReferenceType())) {
3830        S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
3831          << ParamType;
3832        S.Diag(Param->getLocation(), diag::note_template_param_here);
3833        return true;
3834      }
3835
3836      S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
3837        << ParamType
3838        << FixItHint::CreateRemoval(AddrOpLoc);
3839      S.Diag(Param->getLocation(), diag::note_template_param_here);
3840
3841      ArgType = Func->getType();
3842    }
3843  } else {
3844    // A value of reference type is not an object.
3845    if (Var->getType()->isReferenceType()) {
3846      S.Diag(Arg->getLocStart(),
3847             diag::err_template_arg_reference_var)
3848        << Var->getType() << Arg->getSourceRange();
3849      S.Diag(Param->getLocation(), diag::note_template_param_here);
3850      return true;
3851    }
3852
3853    // A template argument must have static storage duration.
3854    if (Var->getTLSKind()) {
3855      S.Diag(Arg->getLocStart(), diag::err_template_arg_thread_local)
3856        << Arg->getSourceRange();
3857      S.Diag(Var->getLocation(), diag::note_template_arg_refers_here);
3858      return true;
3859    }
3860
3861    // If the template parameter has pointer type, we must have taken
3862    // the address of this object.
3863    if (ParamType->isReferenceType()) {
3864      if (AddressTaken) {
3865        // If we originally had an address-of operator, but the
3866        // parameter has reference type, complain and (if things look
3867        // like they will work) drop the address-of operator.
3868        if (!S.Context.hasSameUnqualifiedType(Var->getType(),
3869                                            ParamType.getNonReferenceType())) {
3870          S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
3871            << ParamType;
3872          S.Diag(Param->getLocation(), diag::note_template_param_here);
3873          return true;
3874        }
3875
3876        S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
3877          << ParamType
3878          << FixItHint::CreateRemoval(AddrOpLoc);
3879        S.Diag(Param->getLocation(), diag::note_template_param_here);
3880
3881        ArgType = Var->getType();
3882      }
3883    } else if (!AddressTaken && ParamType->isPointerType()) {
3884      if (Var->getType()->isArrayType()) {
3885        // Array-to-pointer decay.
3886        ArgType = S.Context.getArrayDecayedType(Var->getType());
3887      } else {
3888        // If the template parameter has pointer type but the address of
3889        // this object was not taken, complain and (possibly) recover by
3890        // taking the address of the entity.
3891        ArgType = S.Context.getPointerType(Var->getType());
3892        if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) {
3893          S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
3894            << ParamType;
3895          S.Diag(Param->getLocation(), diag::note_template_param_here);
3896          return true;
3897        }
3898
3899        S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
3900          << ParamType
3901          << FixItHint::CreateInsertion(Arg->getLocStart(), "&");
3902
3903        S.Diag(Param->getLocation(), diag::note_template_param_here);
3904      }
3905    }
3906  }
3907
3908  bool ObjCLifetimeConversion;
3909  if (ParamType->isPointerType() &&
3910      !ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType() &&
3911      S.IsQualificationConversion(ArgType, ParamType, false,
3912                                  ObjCLifetimeConversion)) {
3913    // For pointer-to-object types, qualification conversions are
3914    // permitted.
3915  } else {
3916    if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
3917      if (!ParamRef->getPointeeType()->isFunctionType()) {
3918        // C++ [temp.arg.nontype]p5b3:
3919        //   For a non-type template-parameter of type reference to
3920        //   object, no conversions apply. The type referred to by the
3921        //   reference may be more cv-qualified than the (otherwise
3922        //   identical) type of the template- argument. The
3923        //   template-parameter is bound directly to the
3924        //   template-argument, which shall be an lvalue.
3925
3926        // FIXME: Other qualifiers?
3927        unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
3928        unsigned ArgQuals = ArgType.getCVRQualifiers();
3929
3930        if ((ParamQuals | ArgQuals) != ParamQuals) {
3931          S.Diag(Arg->getLocStart(),
3932                 diag::err_template_arg_ref_bind_ignores_quals)
3933            << ParamType << Arg->getType()
3934            << Arg->getSourceRange();
3935          S.Diag(Param->getLocation(), diag::note_template_param_here);
3936          return true;
3937        }
3938      }
3939    }
3940
3941    // At this point, the template argument refers to an object or
3942    // function with external linkage. We now need to check whether the
3943    // argument and parameter types are compatible.
3944    if (!S.Context.hasSameUnqualifiedType(ArgType,
3945                                          ParamType.getNonReferenceType())) {
3946      // We can't perform this conversion or binding.
3947      if (ParamType->isReferenceType())
3948        S.Diag(Arg->getLocStart(), diag::err_template_arg_no_ref_bind)
3949          << ParamType << ArgIn->getType() << Arg->getSourceRange();
3950      else
3951        S.Diag(Arg->getLocStart(),  diag::err_template_arg_not_convertible)
3952          << ArgIn->getType() << ParamType << Arg->getSourceRange();
3953      S.Diag(Param->getLocation(), diag::note_template_param_here);
3954      return true;
3955    }
3956  }
3957
3958  // Create the template argument.
3959  Converted = TemplateArgument(cast<ValueDecl>(Entity->getCanonicalDecl()),
3960                               ParamType->isReferenceType());
3961  S.MarkAnyDeclReferenced(Arg->getLocStart(), Entity, false);
3962  return false;
3963}
3964
3965/// \brief Checks whether the given template argument is a pointer to
3966/// member constant according to C++ [temp.arg.nontype]p1.
3967static bool CheckTemplateArgumentPointerToMember(Sema &S,
3968                                                 NonTypeTemplateParmDecl *Param,
3969                                                 QualType ParamType,
3970                                                 Expr *&ResultArg,
3971                                                 TemplateArgument &Converted) {
3972  bool Invalid = false;
3973
3974  // Check for a null pointer value.
3975  Expr *Arg = ResultArg;
3976  switch (isNullPointerValueTemplateArgument(S, Param, ParamType, Arg)) {
3977  case NPV_Error:
3978    return true;
3979  case NPV_NullPointer:
3980    S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
3981    Converted = TemplateArgument(ParamType, /*isNullPtr*/true);
3982    return false;
3983  case NPV_NotNullPointer:
3984    break;
3985  }
3986
3987  bool ObjCLifetimeConversion;
3988  if (S.IsQualificationConversion(Arg->getType(),
3989                                  ParamType.getNonReferenceType(),
3990                                  false, ObjCLifetimeConversion)) {
3991    Arg = S.ImpCastExprToType(Arg, ParamType, CK_NoOp,
3992                              Arg->getValueKind()).take();
3993    ResultArg = Arg;
3994  } else if (!S.Context.hasSameUnqualifiedType(Arg->getType(),
3995                ParamType.getNonReferenceType())) {
3996    // We can't perform this conversion.
3997    S.Diag(Arg->getLocStart(), diag::err_template_arg_not_convertible)
3998      << Arg->getType() << ParamType << Arg->getSourceRange();
3999    S.Diag(Param->getLocation(), diag::note_template_param_here);
4000    return true;
4001  }
4002
4003  // See through any implicit casts we added to fix the type.
4004  while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
4005    Arg = Cast->getSubExpr();
4006
4007  // C++ [temp.arg.nontype]p1:
4008  //
4009  //   A template-argument for a non-type, non-template
4010  //   template-parameter shall be one of: [...]
4011  //
4012  //     -- a pointer to member expressed as described in 5.3.1.
4013  DeclRefExpr *DRE = 0;
4014
4015  // In C++98/03 mode, give an extension warning on any extra parentheses.
4016  // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
4017  bool ExtraParens = false;
4018  while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
4019    if (!Invalid && !ExtraParens) {
4020      S.Diag(Arg->getLocStart(),
4021             S.getLangOpts().CPlusPlus11 ?
4022               diag::warn_cxx98_compat_template_arg_extra_parens :
4023               diag::ext_template_arg_extra_parens)
4024        << Arg->getSourceRange();
4025      ExtraParens = true;
4026    }
4027
4028    Arg = Parens->getSubExpr();
4029  }
4030
4031  while (SubstNonTypeTemplateParmExpr *subst =
4032           dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
4033    Arg = subst->getReplacement()->IgnoreImpCasts();
4034
4035  // A pointer-to-member constant written &Class::member.
4036  if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
4037    if (UnOp->getOpcode() == UO_AddrOf) {
4038      DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
4039      if (DRE && !DRE->getQualifier())
4040        DRE = 0;
4041    }
4042  }
4043  // A constant of pointer-to-member type.
4044  else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
4045    if (ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl())) {
4046      if (VD->getType()->isMemberPointerType()) {
4047        if (isa<NonTypeTemplateParmDecl>(VD) ||
4048            (isa<VarDecl>(VD) &&
4049             S.Context.getCanonicalType(VD->getType()).isConstQualified())) {
4050          if (Arg->isTypeDependent() || Arg->isValueDependent()) {
4051            Converted = TemplateArgument(Arg);
4052          } else {
4053            VD = cast<ValueDecl>(VD->getCanonicalDecl());
4054            Converted = TemplateArgument(VD, /*isReferenceParam*/false);
4055          }
4056          return Invalid;
4057        }
4058      }
4059    }
4060
4061    DRE = 0;
4062  }
4063
4064  if (!DRE)
4065    return S.Diag(Arg->getLocStart(),
4066                  diag::err_template_arg_not_pointer_to_member_form)
4067      << Arg->getSourceRange();
4068
4069  if (isa<FieldDecl>(DRE->getDecl()) || isa<CXXMethodDecl>(DRE->getDecl())) {
4070    assert((isa<FieldDecl>(DRE->getDecl()) ||
4071            !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
4072           "Only non-static member pointers can make it here");
4073
4074    // Okay: this is the address of a non-static member, and therefore
4075    // a member pointer constant.
4076    if (Arg->isTypeDependent() || Arg->isValueDependent()) {
4077      Converted = TemplateArgument(Arg);
4078    } else {
4079      ValueDecl *D = cast<ValueDecl>(DRE->getDecl()->getCanonicalDecl());
4080      Converted = TemplateArgument(D, /*isReferenceParam*/false);
4081    }
4082    return Invalid;
4083  }
4084
4085  // We found something else, but we don't know specifically what it is.
4086  S.Diag(Arg->getLocStart(),
4087         diag::err_template_arg_not_pointer_to_member_form)
4088    << Arg->getSourceRange();
4089  S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
4090  return true;
4091}
4092
4093/// \brief Check a template argument against its corresponding
4094/// non-type template parameter.
4095///
4096/// This routine implements the semantics of C++ [temp.arg.nontype].
4097/// If an error occurred, it returns ExprError(); otherwise, it
4098/// returns the converted template argument. \p
4099/// InstantiatedParamType is the type of the non-type template
4100/// parameter after it has been instantiated.
4101ExprResult Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
4102                                       QualType InstantiatedParamType, Expr *Arg,
4103                                       TemplateArgument &Converted,
4104                                       CheckTemplateArgumentKind CTAK) {
4105  SourceLocation StartLoc = Arg->getLocStart();
4106
4107  // If either the parameter has a dependent type or the argument is
4108  // type-dependent, there's nothing we can check now.
4109  if (InstantiatedParamType->isDependentType() || Arg->isTypeDependent()) {
4110    // FIXME: Produce a cloned, canonical expression?
4111    Converted = TemplateArgument(Arg);
4112    return Owned(Arg);
4113  }
4114
4115  // C++ [temp.arg.nontype]p5:
4116  //   The following conversions are performed on each expression used
4117  //   as a non-type template-argument. If a non-type
4118  //   template-argument cannot be converted to the type of the
4119  //   corresponding template-parameter then the program is
4120  //   ill-formed.
4121  QualType ParamType = InstantiatedParamType;
4122  if (ParamType->isIntegralOrEnumerationType()) {
4123    // C++11:
4124    //   -- for a non-type template-parameter of integral or
4125    //      enumeration type, conversions permitted in a converted
4126    //      constant expression are applied.
4127    //
4128    // C++98:
4129    //   -- for a non-type template-parameter of integral or
4130    //      enumeration type, integral promotions (4.5) and integral
4131    //      conversions (4.7) are applied.
4132
4133    if (CTAK == CTAK_Deduced &&
4134        !Context.hasSameUnqualifiedType(ParamType, Arg->getType())) {
4135      // C++ [temp.deduct.type]p17:
4136      //   If, in the declaration of a function template with a non-type
4137      //   template-parameter, the non-type template-parameter is used
4138      //   in an expression in the function parameter-list and, if the
4139      //   corresponding template-argument is deduced, the
4140      //   template-argument type shall match the type of the
4141      //   template-parameter exactly, except that a template-argument
4142      //   deduced from an array bound may be of any integral type.
4143      Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
4144        << Arg->getType().getUnqualifiedType()
4145        << ParamType.getUnqualifiedType();
4146      Diag(Param->getLocation(), diag::note_template_param_here);
4147      return ExprError();
4148    }
4149
4150    if (getLangOpts().CPlusPlus11) {
4151      // We can't check arbitrary value-dependent arguments.
4152      // FIXME: If there's no viable conversion to the template parameter type,
4153      // we should be able to diagnose that prior to instantiation.
4154      if (Arg->isValueDependent()) {
4155        Converted = TemplateArgument(Arg);
4156        return Owned(Arg);
4157      }
4158
4159      // C++ [temp.arg.nontype]p1:
4160      //   A template-argument for a non-type, non-template template-parameter
4161      //   shall be one of:
4162      //
4163      //     -- for a non-type template-parameter of integral or enumeration
4164      //        type, a converted constant expression of the type of the
4165      //        template-parameter; or
4166      llvm::APSInt Value;
4167      ExprResult ArgResult =
4168        CheckConvertedConstantExpression(Arg, ParamType, Value,
4169                                         CCEK_TemplateArg);
4170      if (ArgResult.isInvalid())
4171        return ExprError();
4172
4173      // Widen the argument value to sizeof(parameter type). This is almost
4174      // always a no-op, except when the parameter type is bool. In
4175      // that case, this may extend the argument from 1 bit to 8 bits.
4176      QualType IntegerType = ParamType;
4177      if (const EnumType *Enum = IntegerType->getAs<EnumType>())
4178        IntegerType = Enum->getDecl()->getIntegerType();
4179      Value = Value.extOrTrunc(Context.getTypeSize(IntegerType));
4180
4181      Converted = TemplateArgument(Context, Value,
4182                                   Context.getCanonicalType(ParamType));
4183      return ArgResult;
4184    }
4185
4186    ExprResult ArgResult = DefaultLvalueConversion(Arg);
4187    if (ArgResult.isInvalid())
4188      return ExprError();
4189    Arg = ArgResult.take();
4190
4191    QualType ArgType = Arg->getType();
4192
4193    // C++ [temp.arg.nontype]p1:
4194    //   A template-argument for a non-type, non-template
4195    //   template-parameter shall be one of:
4196    //
4197    //     -- an integral constant-expression of integral or enumeration
4198    //        type; or
4199    //     -- the name of a non-type template-parameter; or
4200    SourceLocation NonConstantLoc;
4201    llvm::APSInt Value;
4202    if (!ArgType->isIntegralOrEnumerationType()) {
4203      Diag(Arg->getLocStart(),
4204           diag::err_template_arg_not_integral_or_enumeral)
4205        << ArgType << Arg->getSourceRange();
4206      Diag(Param->getLocation(), diag::note_template_param_here);
4207      return ExprError();
4208    } else if (!Arg->isValueDependent()) {
4209      class TmplArgICEDiagnoser : public VerifyICEDiagnoser {
4210        QualType T;
4211
4212      public:
4213        TmplArgICEDiagnoser(QualType T) : T(T) { }
4214
4215        virtual void diagnoseNotICE(Sema &S, SourceLocation Loc,
4216                                    SourceRange SR) {
4217          S.Diag(Loc, diag::err_template_arg_not_ice) << T << SR;
4218        }
4219      } Diagnoser(ArgType);
4220
4221      Arg = VerifyIntegerConstantExpression(Arg, &Value, Diagnoser,
4222                                            false).take();
4223      if (!Arg)
4224        return ExprError();
4225    }
4226
4227    // From here on out, all we care about are the unqualified forms
4228    // of the parameter and argument types.
4229    ParamType = ParamType.getUnqualifiedType();
4230    ArgType = ArgType.getUnqualifiedType();
4231
4232    // Try to convert the argument to the parameter's type.
4233    if (Context.hasSameType(ParamType, ArgType)) {
4234      // Okay: no conversion necessary
4235    } else if (ParamType->isBooleanType()) {
4236      // This is an integral-to-boolean conversion.
4237      Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralToBoolean).take();
4238    } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
4239               !ParamType->isEnumeralType()) {
4240      // This is an integral promotion or conversion.
4241      Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralCast).take();
4242    } else {
4243      // We can't perform this conversion.
4244      Diag(Arg->getLocStart(),
4245           diag::err_template_arg_not_convertible)
4246        << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
4247      Diag(Param->getLocation(), diag::note_template_param_here);
4248      return ExprError();
4249    }
4250
4251    // Add the value of this argument to the list of converted
4252    // arguments. We use the bitwidth and signedness of the template
4253    // parameter.
4254    if (Arg->isValueDependent()) {
4255      // The argument is value-dependent. Create a new
4256      // TemplateArgument with the converted expression.
4257      Converted = TemplateArgument(Arg);
4258      return Owned(Arg);
4259    }
4260
4261    QualType IntegerType = Context.getCanonicalType(ParamType);
4262    if (const EnumType *Enum = IntegerType->getAs<EnumType>())
4263      IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
4264
4265    if (ParamType->isBooleanType()) {
4266      // Value must be zero or one.
4267      Value = Value != 0;
4268      unsigned AllowedBits = Context.getTypeSize(IntegerType);
4269      if (Value.getBitWidth() != AllowedBits)
4270        Value = Value.extOrTrunc(AllowedBits);
4271      Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
4272    } else {
4273      llvm::APSInt OldValue = Value;
4274
4275      // Coerce the template argument's value to the value it will have
4276      // based on the template parameter's type.
4277      unsigned AllowedBits = Context.getTypeSize(IntegerType);
4278      if (Value.getBitWidth() != AllowedBits)
4279        Value = Value.extOrTrunc(AllowedBits);
4280      Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
4281
4282      // Complain if an unsigned parameter received a negative value.
4283      if (IntegerType->isUnsignedIntegerOrEnumerationType()
4284               && (OldValue.isSigned() && OldValue.isNegative())) {
4285        Diag(Arg->getLocStart(), diag::warn_template_arg_negative)
4286          << OldValue.toString(10) << Value.toString(10) << Param->getType()
4287          << Arg->getSourceRange();
4288        Diag(Param->getLocation(), diag::note_template_param_here);
4289      }
4290
4291      // Complain if we overflowed the template parameter's type.
4292      unsigned RequiredBits;
4293      if (IntegerType->isUnsignedIntegerOrEnumerationType())
4294        RequiredBits = OldValue.getActiveBits();
4295      else if (OldValue.isUnsigned())
4296        RequiredBits = OldValue.getActiveBits() + 1;
4297      else
4298        RequiredBits = OldValue.getMinSignedBits();
4299      if (RequiredBits > AllowedBits) {
4300        Diag(Arg->getLocStart(),
4301             diag::warn_template_arg_too_large)
4302          << OldValue.toString(10) << Value.toString(10) << Param->getType()
4303          << Arg->getSourceRange();
4304        Diag(Param->getLocation(), diag::note_template_param_here);
4305      }
4306    }
4307
4308    Converted = TemplateArgument(Context, Value,
4309                                 ParamType->isEnumeralType()
4310                                   ? Context.getCanonicalType(ParamType)
4311                                   : IntegerType);
4312    return Owned(Arg);
4313  }
4314
4315  QualType ArgType = Arg->getType();
4316  DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
4317
4318  // Handle pointer-to-function, reference-to-function, and
4319  // pointer-to-member-function all in (roughly) the same way.
4320  if (// -- For a non-type template-parameter of type pointer to
4321      //    function, only the function-to-pointer conversion (4.3) is
4322      //    applied. If the template-argument represents a set of
4323      //    overloaded functions (or a pointer to such), the matching
4324      //    function is selected from the set (13.4).
4325      (ParamType->isPointerType() &&
4326       ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
4327      // -- For a non-type template-parameter of type reference to
4328      //    function, no conversions apply. If the template-argument
4329      //    represents a set of overloaded functions, the matching
4330      //    function is selected from the set (13.4).
4331      (ParamType->isReferenceType() &&
4332       ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
4333      // -- For a non-type template-parameter of type pointer to
4334      //    member function, no conversions apply. If the
4335      //    template-argument represents a set of overloaded member
4336      //    functions, the matching member function is selected from
4337      //    the set (13.4).
4338      (ParamType->isMemberPointerType() &&
4339       ParamType->getAs<MemberPointerType>()->getPointeeType()
4340         ->isFunctionType())) {
4341
4342    if (Arg->getType() == Context.OverloadTy) {
4343      if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType,
4344                                                                true,
4345                                                                FoundResult)) {
4346        if (DiagnoseUseOfDecl(Fn, Arg->getLocStart()))
4347          return ExprError();
4348
4349        Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
4350        ArgType = Arg->getType();
4351      } else
4352        return ExprError();
4353    }
4354
4355    if (!ParamType->isMemberPointerType()) {
4356      if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
4357                                                         ParamType,
4358                                                         Arg, Converted))
4359        return ExprError();
4360      return Owned(Arg);
4361    }
4362
4363    if (CheckTemplateArgumentPointerToMember(*this, Param, ParamType, Arg,
4364                                             Converted))
4365      return ExprError();
4366    return Owned(Arg);
4367  }
4368
4369  if (ParamType->isPointerType()) {
4370    //   -- for a non-type template-parameter of type pointer to
4371    //      object, qualification conversions (4.4) and the
4372    //      array-to-pointer conversion (4.2) are applied.
4373    // C++0x also allows a value of std::nullptr_t.
4374    assert(ParamType->getPointeeType()->isIncompleteOrObjectType() &&
4375           "Only object pointers allowed here");
4376
4377    if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
4378                                                       ParamType,
4379                                                       Arg, Converted))
4380      return ExprError();
4381    return Owned(Arg);
4382  }
4383
4384  if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
4385    //   -- For a non-type template-parameter of type reference to
4386    //      object, no conversions apply. The type referred to by the
4387    //      reference may be more cv-qualified than the (otherwise
4388    //      identical) type of the template-argument. The
4389    //      template-parameter is bound directly to the
4390    //      template-argument, which must be an lvalue.
4391    assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() &&
4392           "Only object references allowed here");
4393
4394    if (Arg->getType() == Context.OverloadTy) {
4395      if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg,
4396                                                 ParamRefType->getPointeeType(),
4397                                                                true,
4398                                                                FoundResult)) {
4399        if (DiagnoseUseOfDecl(Fn, Arg->getLocStart()))
4400          return ExprError();
4401
4402        Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
4403        ArgType = Arg->getType();
4404      } else
4405        return ExprError();
4406    }
4407
4408    if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
4409                                                       ParamType,
4410                                                       Arg, Converted))
4411      return ExprError();
4412    return Owned(Arg);
4413  }
4414
4415  // Deal with parameters of type std::nullptr_t.
4416  if (ParamType->isNullPtrType()) {
4417    if (Arg->isTypeDependent() || Arg->isValueDependent()) {
4418      Converted = TemplateArgument(Arg);
4419      return Owned(Arg);
4420    }
4421
4422    switch (isNullPointerValueTemplateArgument(*this, Param, ParamType, Arg)) {
4423    case NPV_NotNullPointer:
4424      Diag(Arg->getExprLoc(), diag::err_template_arg_not_convertible)
4425        << Arg->getType() << ParamType;
4426      Diag(Param->getLocation(), diag::note_template_param_here);
4427      return ExprError();
4428
4429    case NPV_Error:
4430      return ExprError();
4431
4432    case NPV_NullPointer:
4433      Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
4434      Converted = TemplateArgument(ParamType, /*isNullPtr*/true);
4435      return Owned(Arg);
4436    }
4437  }
4438
4439  //     -- For a non-type template-parameter of type pointer to data
4440  //        member, qualification conversions (4.4) are applied.
4441  assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
4442
4443  if (CheckTemplateArgumentPointerToMember(*this, Param, ParamType, Arg,
4444                                           Converted))
4445    return ExprError();
4446  return Owned(Arg);
4447}
4448
4449/// \brief Check a template argument against its corresponding
4450/// template template parameter.
4451///
4452/// This routine implements the semantics of C++ [temp.arg.template].
4453/// It returns true if an error occurred, and false otherwise.
4454bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
4455                                 const TemplateArgumentLoc &Arg,
4456                                 unsigned ArgumentPackIndex) {
4457  TemplateName Name = Arg.getArgument().getAsTemplateOrTemplatePattern();
4458  TemplateDecl *Template = Name.getAsTemplateDecl();
4459  if (!Template) {
4460    // Any dependent template name is fine.
4461    assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
4462    return false;
4463  }
4464
4465  // C++0x [temp.arg.template]p1:
4466  //   A template-argument for a template template-parameter shall be
4467  //   the name of a class template or an alias template, expressed as an
4468  //   id-expression. When the template-argument names a class template, only
4469  //   primary class templates are considered when matching the
4470  //   template template argument with the corresponding parameter;
4471  //   partial specializations are not considered even if their
4472  //   parameter lists match that of the template template parameter.
4473  //
4474  // Note that we also allow template template parameters here, which
4475  // will happen when we are dealing with, e.g., class template
4476  // partial specializations.
4477  if (!isa<ClassTemplateDecl>(Template) &&
4478      !isa<TemplateTemplateParmDecl>(Template) &&
4479      !isa<TypeAliasTemplateDecl>(Template)) {
4480    assert(isa<FunctionTemplateDecl>(Template) &&
4481           "Only function templates are possible here");
4482    Diag(Arg.getLocation(), diag::err_template_arg_not_class_template);
4483    Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
4484      << Template;
4485  }
4486
4487  TemplateParameterList *Params = Param->getTemplateParameters();
4488  if (Param->isExpandedParameterPack())
4489    Params = Param->getExpansionTemplateParameters(ArgumentPackIndex);
4490
4491  return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
4492                                         Params,
4493                                         true,
4494                                         TPL_TemplateTemplateArgumentMatch,
4495                                         Arg.getLocation());
4496}
4497
4498/// \brief Given a non-type template argument that refers to a
4499/// declaration and the type of its corresponding non-type template
4500/// parameter, produce an expression that properly refers to that
4501/// declaration.
4502ExprResult
4503Sema::BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
4504                                              QualType ParamType,
4505                                              SourceLocation Loc) {
4506  // C++ [temp.param]p8:
4507  //
4508  //   A non-type template-parameter of type "array of T" or
4509  //   "function returning T" is adjusted to be of type "pointer to
4510  //   T" or "pointer to function returning T", respectively.
4511  if (ParamType->isArrayType())
4512    ParamType = Context.getArrayDecayedType(ParamType);
4513  else if (ParamType->isFunctionType())
4514    ParamType = Context.getPointerType(ParamType);
4515
4516  // For a NULL non-type template argument, return nullptr casted to the
4517  // parameter's type.
4518  if (Arg.getKind() == TemplateArgument::NullPtr) {
4519    return ImpCastExprToType(
4520             new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc),
4521                             ParamType,
4522                             ParamType->getAs<MemberPointerType>()
4523                               ? CK_NullToMemberPointer
4524                               : CK_NullToPointer);
4525  }
4526  assert(Arg.getKind() == TemplateArgument::Declaration &&
4527         "Only declaration template arguments permitted here");
4528
4529  ValueDecl *VD = cast<ValueDecl>(Arg.getAsDecl());
4530
4531  if (VD->getDeclContext()->isRecord() &&
4532      (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD))) {
4533    // If the value is a class member, we might have a pointer-to-member.
4534    // Determine whether the non-type template template parameter is of
4535    // pointer-to-member type. If so, we need to build an appropriate
4536    // expression for a pointer-to-member, since a "normal" DeclRefExpr
4537    // would refer to the member itself.
4538    if (ParamType->isMemberPointerType()) {
4539      QualType ClassType
4540        = Context.getTypeDeclType(cast<RecordDecl>(VD->getDeclContext()));
4541      NestedNameSpecifier *Qualifier
4542        = NestedNameSpecifier::Create(Context, 0, false,
4543                                      ClassType.getTypePtr());
4544      CXXScopeSpec SS;
4545      SS.MakeTrivial(Context, Qualifier, Loc);
4546
4547      // The actual value-ness of this is unimportant, but for
4548      // internal consistency's sake, references to instance methods
4549      // are r-values.
4550      ExprValueKind VK = VK_LValue;
4551      if (isa<CXXMethodDecl>(VD) && cast<CXXMethodDecl>(VD)->isInstance())
4552        VK = VK_RValue;
4553
4554      ExprResult RefExpr = BuildDeclRefExpr(VD,
4555                                            VD->getType().getNonReferenceType(),
4556                                            VK,
4557                                            Loc,
4558                                            &SS);
4559      if (RefExpr.isInvalid())
4560        return ExprError();
4561
4562      RefExpr = CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
4563
4564      // We might need to perform a trailing qualification conversion, since
4565      // the element type on the parameter could be more qualified than the
4566      // element type in the expression we constructed.
4567      bool ObjCLifetimeConversion;
4568      if (IsQualificationConversion(((Expr*) RefExpr.get())->getType(),
4569                                    ParamType.getUnqualifiedType(), false,
4570                                    ObjCLifetimeConversion))
4571        RefExpr = ImpCastExprToType(RefExpr.take(), ParamType.getUnqualifiedType(), CK_NoOp);
4572
4573      assert(!RefExpr.isInvalid() &&
4574             Context.hasSameType(((Expr*) RefExpr.get())->getType(),
4575                                 ParamType.getUnqualifiedType()));
4576      return RefExpr;
4577    }
4578  }
4579
4580  QualType T = VD->getType().getNonReferenceType();
4581
4582  if (ParamType->isPointerType()) {
4583    // When the non-type template parameter is a pointer, take the
4584    // address of the declaration.
4585    ExprResult RefExpr = BuildDeclRefExpr(VD, T, VK_LValue, Loc);
4586    if (RefExpr.isInvalid())
4587      return ExprError();
4588
4589    if (T->isFunctionType() || T->isArrayType()) {
4590      // Decay functions and arrays.
4591      RefExpr = DefaultFunctionArrayConversion(RefExpr.take());
4592      if (RefExpr.isInvalid())
4593        return ExprError();
4594
4595      return RefExpr;
4596    }
4597
4598    // Take the address of everything else
4599    return CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
4600  }
4601
4602  ExprValueKind VK = VK_RValue;
4603
4604  // If the non-type template parameter has reference type, qualify the
4605  // resulting declaration reference with the extra qualifiers on the
4606  // type that the reference refers to.
4607  if (const ReferenceType *TargetRef = ParamType->getAs<ReferenceType>()) {
4608    VK = VK_LValue;
4609    T = Context.getQualifiedType(T,
4610                              TargetRef->getPointeeType().getQualifiers());
4611  } else if (isa<FunctionDecl>(VD)) {
4612    // References to functions are always lvalues.
4613    VK = VK_LValue;
4614  }
4615
4616  return BuildDeclRefExpr(VD, T, VK, Loc);
4617}
4618
4619/// \brief Construct a new expression that refers to the given
4620/// integral template argument with the given source-location
4621/// information.
4622///
4623/// This routine takes care of the mapping from an integral template
4624/// argument (which may have any integral type) to the appropriate
4625/// literal value.
4626ExprResult
4627Sema::BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
4628                                                  SourceLocation Loc) {
4629  assert(Arg.getKind() == TemplateArgument::Integral &&
4630         "Operation is only valid for integral template arguments");
4631  QualType OrigT = Arg.getIntegralType();
4632
4633  // If this is an enum type that we're instantiating, we need to use an integer
4634  // type the same size as the enumerator.  We don't want to build an
4635  // IntegerLiteral with enum type.  The integer type of an enum type can be of
4636  // any integral type with C++11 enum classes, make sure we create the right
4637  // type of literal for it.
4638  QualType T = OrigT;
4639  if (const EnumType *ET = OrigT->getAs<EnumType>())
4640    T = ET->getDecl()->getIntegerType();
4641
4642  Expr *E;
4643  if (T->isAnyCharacterType()) {
4644    CharacterLiteral::CharacterKind Kind;
4645    if (T->isWideCharType())
4646      Kind = CharacterLiteral::Wide;
4647    else if (T->isChar16Type())
4648      Kind = CharacterLiteral::UTF16;
4649    else if (T->isChar32Type())
4650      Kind = CharacterLiteral::UTF32;
4651    else
4652      Kind = CharacterLiteral::Ascii;
4653
4654    E = new (Context) CharacterLiteral(Arg.getAsIntegral().getZExtValue(),
4655                                       Kind, T, Loc);
4656  } else if (T->isBooleanType()) {
4657    E = new (Context) CXXBoolLiteralExpr(Arg.getAsIntegral().getBoolValue(),
4658                                         T, Loc);
4659  } else if (T->isNullPtrType()) {
4660    E = new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc);
4661  } else {
4662    E = IntegerLiteral::Create(Context, Arg.getAsIntegral(), T, Loc);
4663  }
4664
4665  if (OrigT->isEnumeralType()) {
4666    // FIXME: This is a hack. We need a better way to handle substituted
4667    // non-type template parameters.
4668    E = CStyleCastExpr::Create(Context, OrigT, VK_RValue, CK_IntegralCast, E, 0,
4669                               Context.getTrivialTypeSourceInfo(OrigT, Loc),
4670                               Loc, Loc);
4671  }
4672
4673  return Owned(E);
4674}
4675
4676/// \brief Match two template parameters within template parameter lists.
4677static bool MatchTemplateParameterKind(Sema &S, NamedDecl *New, NamedDecl *Old,
4678                                       bool Complain,
4679                                     Sema::TemplateParameterListEqualKind Kind,
4680                                       SourceLocation TemplateArgLoc) {
4681  // Check the actual kind (type, non-type, template).
4682  if (Old->getKind() != New->getKind()) {
4683    if (Complain) {
4684      unsigned NextDiag = diag::err_template_param_different_kind;
4685      if (TemplateArgLoc.isValid()) {
4686        S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
4687        NextDiag = diag::note_template_param_different_kind;
4688      }
4689      S.Diag(New->getLocation(), NextDiag)
4690        << (Kind != Sema::TPL_TemplateMatch);
4691      S.Diag(Old->getLocation(), diag::note_template_prev_declaration)
4692        << (Kind != Sema::TPL_TemplateMatch);
4693    }
4694
4695    return false;
4696  }
4697
4698  // Check that both are parameter packs are neither are parameter packs.
4699  // However, if we are matching a template template argument to a
4700  // template template parameter, the template template parameter can have
4701  // a parameter pack where the template template argument does not.
4702  if (Old->isTemplateParameterPack() != New->isTemplateParameterPack() &&
4703      !(Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
4704        Old->isTemplateParameterPack())) {
4705    if (Complain) {
4706      unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
4707      if (TemplateArgLoc.isValid()) {
4708        S.Diag(TemplateArgLoc,
4709             diag::err_template_arg_template_params_mismatch);
4710        NextDiag = diag::note_template_parameter_pack_non_pack;
4711      }
4712
4713      unsigned ParamKind = isa<TemplateTypeParmDecl>(New)? 0
4714                      : isa<NonTypeTemplateParmDecl>(New)? 1
4715                      : 2;
4716      S.Diag(New->getLocation(), NextDiag)
4717        << ParamKind << New->isParameterPack();
4718      S.Diag(Old->getLocation(), diag::note_template_parameter_pack_here)
4719        << ParamKind << Old->isParameterPack();
4720    }
4721
4722    return false;
4723  }
4724
4725  // For non-type template parameters, check the type of the parameter.
4726  if (NonTypeTemplateParmDecl *OldNTTP
4727                                    = dyn_cast<NonTypeTemplateParmDecl>(Old)) {
4728    NonTypeTemplateParmDecl *NewNTTP = cast<NonTypeTemplateParmDecl>(New);
4729
4730    // If we are matching a template template argument to a template
4731    // template parameter and one of the non-type template parameter types
4732    // is dependent, then we must wait until template instantiation time
4733    // to actually compare the arguments.
4734    if (Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
4735        (OldNTTP->getType()->isDependentType() ||
4736         NewNTTP->getType()->isDependentType()))
4737      return true;
4738
4739    if (!S.Context.hasSameType(OldNTTP->getType(), NewNTTP->getType())) {
4740      if (Complain) {
4741        unsigned NextDiag = diag::err_template_nontype_parm_different_type;
4742        if (TemplateArgLoc.isValid()) {
4743          S.Diag(TemplateArgLoc,
4744                 diag::err_template_arg_template_params_mismatch);
4745          NextDiag = diag::note_template_nontype_parm_different_type;
4746        }
4747        S.Diag(NewNTTP->getLocation(), NextDiag)
4748          << NewNTTP->getType()
4749          << (Kind != Sema::TPL_TemplateMatch);
4750        S.Diag(OldNTTP->getLocation(),
4751               diag::note_template_nontype_parm_prev_declaration)
4752          << OldNTTP->getType();
4753      }
4754
4755      return false;
4756    }
4757
4758    return true;
4759  }
4760
4761  // For template template parameters, check the template parameter types.
4762  // The template parameter lists of template template
4763  // parameters must agree.
4764  if (TemplateTemplateParmDecl *OldTTP
4765                                    = dyn_cast<TemplateTemplateParmDecl>(Old)) {
4766    TemplateTemplateParmDecl *NewTTP = cast<TemplateTemplateParmDecl>(New);
4767    return S.TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
4768                                            OldTTP->getTemplateParameters(),
4769                                            Complain,
4770                                        (Kind == Sema::TPL_TemplateMatch
4771                                           ? Sema::TPL_TemplateTemplateParmMatch
4772                                           : Kind),
4773                                            TemplateArgLoc);
4774  }
4775
4776  return true;
4777}
4778
4779/// \brief Diagnose a known arity mismatch when comparing template argument
4780/// lists.
4781static
4782void DiagnoseTemplateParameterListArityMismatch(Sema &S,
4783                                                TemplateParameterList *New,
4784                                                TemplateParameterList *Old,
4785                                      Sema::TemplateParameterListEqualKind Kind,
4786                                                SourceLocation TemplateArgLoc) {
4787  unsigned NextDiag = diag::err_template_param_list_different_arity;
4788  if (TemplateArgLoc.isValid()) {
4789    S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
4790    NextDiag = diag::note_template_param_list_different_arity;
4791  }
4792  S.Diag(New->getTemplateLoc(), NextDiag)
4793    << (New->size() > Old->size())
4794    << (Kind != Sema::TPL_TemplateMatch)
4795    << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
4796  S.Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
4797    << (Kind != Sema::TPL_TemplateMatch)
4798    << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
4799}
4800
4801/// \brief Determine whether the given template parameter lists are
4802/// equivalent.
4803///
4804/// \param New  The new template parameter list, typically written in the
4805/// source code as part of a new template declaration.
4806///
4807/// \param Old  The old template parameter list, typically found via
4808/// name lookup of the template declared with this template parameter
4809/// list.
4810///
4811/// \param Complain  If true, this routine will produce a diagnostic if
4812/// the template parameter lists are not equivalent.
4813///
4814/// \param Kind describes how we are to match the template parameter lists.
4815///
4816/// \param TemplateArgLoc If this source location is valid, then we
4817/// are actually checking the template parameter list of a template
4818/// argument (New) against the template parameter list of its
4819/// corresponding template template parameter (Old). We produce
4820/// slightly different diagnostics in this scenario.
4821///
4822/// \returns True if the template parameter lists are equal, false
4823/// otherwise.
4824bool
4825Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
4826                                     TemplateParameterList *Old,
4827                                     bool Complain,
4828                                     TemplateParameterListEqualKind Kind,
4829                                     SourceLocation TemplateArgLoc) {
4830  if (Old->size() != New->size() && Kind != TPL_TemplateTemplateArgumentMatch) {
4831    if (Complain)
4832      DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
4833                                                 TemplateArgLoc);
4834
4835    return false;
4836  }
4837
4838  // C++0x [temp.arg.template]p3:
4839  //   A template-argument matches a template template-parameter (call it P)
4840  //   when each of the template parameters in the template-parameter-list of
4841  //   the template-argument's corresponding class template or alias template
4842  //   (call it A) matches the corresponding template parameter in the
4843  //   template-parameter-list of P. [...]
4844  TemplateParameterList::iterator NewParm = New->begin();
4845  TemplateParameterList::iterator NewParmEnd = New->end();
4846  for (TemplateParameterList::iterator OldParm = Old->begin(),
4847                                    OldParmEnd = Old->end();
4848       OldParm != OldParmEnd; ++OldParm) {
4849    if (Kind != TPL_TemplateTemplateArgumentMatch ||
4850        !(*OldParm)->isTemplateParameterPack()) {
4851      if (NewParm == NewParmEnd) {
4852        if (Complain)
4853          DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
4854                                                     TemplateArgLoc);
4855
4856        return false;
4857      }
4858
4859      if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
4860                                      Kind, TemplateArgLoc))
4861        return false;
4862
4863      ++NewParm;
4864      continue;
4865    }
4866
4867    // C++0x [temp.arg.template]p3:
4868    //   [...] When P's template- parameter-list contains a template parameter
4869    //   pack (14.5.3), the template parameter pack will match zero or more
4870    //   template parameters or template parameter packs in the
4871    //   template-parameter-list of A with the same type and form as the
4872    //   template parameter pack in P (ignoring whether those template
4873    //   parameters are template parameter packs).
4874    for (; NewParm != NewParmEnd; ++NewParm) {
4875      if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
4876                                      Kind, TemplateArgLoc))
4877        return false;
4878    }
4879  }
4880
4881  // Make sure we exhausted all of the arguments.
4882  if (NewParm != NewParmEnd) {
4883    if (Complain)
4884      DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
4885                                                 TemplateArgLoc);
4886
4887    return false;
4888  }
4889
4890  return true;
4891}
4892
4893/// \brief Check whether a template can be declared within this scope.
4894///
4895/// If the template declaration is valid in this scope, returns
4896/// false. Otherwise, issues a diagnostic and returns true.
4897bool
4898Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
4899  if (!S)
4900    return false;
4901
4902  // Find the nearest enclosing declaration scope.
4903  while ((S->getFlags() & Scope::DeclScope) == 0 ||
4904         (S->getFlags() & Scope::TemplateParamScope) != 0)
4905    S = S->getParent();
4906
4907  // C++ [temp]p2:
4908  //   A template-declaration can appear only as a namespace scope or
4909  //   class scope declaration.
4910  DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
4911  if (Ctx && isa<LinkageSpecDecl>(Ctx) &&
4912      cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx)
4913    return Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
4914             << TemplateParams->getSourceRange();
4915
4916  while (Ctx && isa<LinkageSpecDecl>(Ctx))
4917    Ctx = Ctx->getParent();
4918
4919  if (Ctx && (Ctx->isFileContext() || Ctx->isRecord()))
4920    return false;
4921
4922  return Diag(TemplateParams->getTemplateLoc(),
4923              diag::err_template_outside_namespace_or_class_scope)
4924    << TemplateParams->getSourceRange();
4925}
4926
4927/// \brief Determine what kind of template specialization the given declaration
4928/// is.
4929static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D) {
4930  if (!D)
4931    return TSK_Undeclared;
4932
4933  if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
4934    return Record->getTemplateSpecializationKind();
4935  if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
4936    return Function->getTemplateSpecializationKind();
4937  if (VarDecl *Var = dyn_cast<VarDecl>(D))
4938    return Var->getTemplateSpecializationKind();
4939
4940  return TSK_Undeclared;
4941}
4942
4943/// \brief Check whether a specialization is well-formed in the current
4944/// context.
4945///
4946/// This routine determines whether a template specialization can be declared
4947/// in the current context (C++ [temp.expl.spec]p2).
4948///
4949/// \param S the semantic analysis object for which this check is being
4950/// performed.
4951///
4952/// \param Specialized the entity being specialized or instantiated, which
4953/// may be a kind of template (class template, function template, etc.) or
4954/// a member of a class template (member function, static data member,
4955/// member class).
4956///
4957/// \param PrevDecl the previous declaration of this entity, if any.
4958///
4959/// \param Loc the location of the explicit specialization or instantiation of
4960/// this entity.
4961///
4962/// \param IsPartialSpecialization whether this is a partial specialization of
4963/// a class template.
4964///
4965/// \returns true if there was an error that we cannot recover from, false
4966/// otherwise.
4967static bool CheckTemplateSpecializationScope(Sema &S,
4968                                             NamedDecl *Specialized,
4969                                             NamedDecl *PrevDecl,
4970                                             SourceLocation Loc,
4971                                             bool IsPartialSpecialization) {
4972  // Keep these "kind" numbers in sync with the %select statements in the
4973  // various diagnostics emitted by this routine.
4974  int EntityKind = 0;
4975  if (isa<ClassTemplateDecl>(Specialized))
4976    EntityKind = IsPartialSpecialization? 1 : 0;
4977  else if (isa<FunctionTemplateDecl>(Specialized))
4978    EntityKind = 2;
4979  else if (isa<CXXMethodDecl>(Specialized))
4980    EntityKind = 3;
4981  else if (isa<VarDecl>(Specialized))
4982    EntityKind = 4;
4983  else if (isa<RecordDecl>(Specialized))
4984    EntityKind = 5;
4985  else if (isa<EnumDecl>(Specialized) && S.getLangOpts().CPlusPlus11)
4986    EntityKind = 6;
4987  else {
4988    S.Diag(Loc, diag::err_template_spec_unknown_kind)
4989      << S.getLangOpts().CPlusPlus11;
4990    S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
4991    return true;
4992  }
4993
4994  // C++ [temp.expl.spec]p2:
4995  //   An explicit specialization shall be declared in the namespace
4996  //   of which the template is a member, or, for member templates, in
4997  //   the namespace of which the enclosing class or enclosing class
4998  //   template is a member. An explicit specialization of a member
4999  //   function, member class or static data member of a class
5000  //   template shall be declared in the namespace of which the class
5001  //   template is a member. Such a declaration may also be a
5002  //   definition. If the declaration is not a definition, the
5003  //   specialization may be defined later in the name- space in which
5004  //   the explicit specialization was declared, or in a namespace
5005  //   that encloses the one in which the explicit specialization was
5006  //   declared.
5007  if (S.CurContext->getRedeclContext()->isFunctionOrMethod()) {
5008    S.Diag(Loc, diag::err_template_spec_decl_function_scope)
5009      << Specialized;
5010    return true;
5011  }
5012
5013  if (S.CurContext->isRecord() && !IsPartialSpecialization) {
5014    if (S.getLangOpts().MicrosoftExt) {
5015      // Do not warn for class scope explicit specialization during
5016      // instantiation, warning was already emitted during pattern
5017      // semantic analysis.
5018      if (!S.ActiveTemplateInstantiations.size())
5019        S.Diag(Loc, diag::ext_function_specialization_in_class)
5020          << Specialized;
5021    } else {
5022      S.Diag(Loc, diag::err_template_spec_decl_class_scope)
5023        << Specialized;
5024      return true;
5025    }
5026  }
5027
5028  if (S.CurContext->isRecord() &&
5029      !S.CurContext->Equals(Specialized->getDeclContext())) {
5030    // Make sure that we're specializing in the right record context.
5031    // Otherwise, things can go horribly wrong.
5032    S.Diag(Loc, diag::err_template_spec_decl_class_scope)
5033      << Specialized;
5034    return true;
5035  }
5036
5037  // C++ [temp.class.spec]p6:
5038  //   A class template partial specialization may be declared or redeclared
5039  //   in any namespace scope in which its definition may be defined (14.5.1
5040  //   and 14.5.2).
5041  bool ComplainedAboutScope = false;
5042  DeclContext *SpecializedContext
5043    = Specialized->getDeclContext()->getEnclosingNamespaceContext();
5044  DeclContext *DC = S.CurContext->getEnclosingNamespaceContext();
5045  if ((!PrevDecl ||
5046       getTemplateSpecializationKind(PrevDecl) == TSK_Undeclared ||
5047       getTemplateSpecializationKind(PrevDecl) == TSK_ImplicitInstantiation)){
5048    // C++ [temp.exp.spec]p2:
5049    //   An explicit specialization shall be declared in the namespace of which
5050    //   the template is a member, or, for member templates, in the namespace
5051    //   of which the enclosing class or enclosing class template is a member.
5052    //   An explicit specialization of a member function, member class or
5053    //   static data member of a class template shall be declared in the
5054    //   namespace of which the class template is a member.
5055    //
5056    // C++0x [temp.expl.spec]p2:
5057    //   An explicit specialization shall be declared in a namespace enclosing
5058    //   the specialized template.
5059    if (!DC->InEnclosingNamespaceSetOf(SpecializedContext)) {
5060      bool IsCPlusPlus11Extension = DC->Encloses(SpecializedContext);
5061      if (isa<TranslationUnitDecl>(SpecializedContext)) {
5062        assert(!IsCPlusPlus11Extension &&
5063               "DC encloses TU but isn't in enclosing namespace set");
5064        S.Diag(Loc, diag::err_template_spec_decl_out_of_scope_global)
5065          << EntityKind << Specialized;
5066      } else if (isa<NamespaceDecl>(SpecializedContext)) {
5067        int Diag;
5068        if (!IsCPlusPlus11Extension)
5069          Diag = diag::err_template_spec_decl_out_of_scope;
5070        else if (!S.getLangOpts().CPlusPlus11)
5071          Diag = diag::ext_template_spec_decl_out_of_scope;
5072        else
5073          Diag = diag::warn_cxx98_compat_template_spec_decl_out_of_scope;
5074        S.Diag(Loc, Diag)
5075          << EntityKind << Specialized << cast<NamedDecl>(SpecializedContext);
5076      }
5077
5078      S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
5079      ComplainedAboutScope =
5080        !(IsCPlusPlus11Extension && S.getLangOpts().CPlusPlus11);
5081    }
5082  }
5083
5084  // Make sure that this redeclaration (or definition) occurs in an enclosing
5085  // namespace.
5086  // Note that HandleDeclarator() performs this check for explicit
5087  // specializations of function templates, static data members, and member
5088  // functions, so we skip the check here for those kinds of entities.
5089  // FIXME: HandleDeclarator's diagnostics aren't quite as good, though.
5090  // Should we refactor that check, so that it occurs later?
5091  if (!ComplainedAboutScope && !DC->Encloses(SpecializedContext) &&
5092      !(isa<FunctionTemplateDecl>(Specialized) || isa<VarDecl>(Specialized) ||
5093        isa<FunctionDecl>(Specialized))) {
5094    if (isa<TranslationUnitDecl>(SpecializedContext))
5095      S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
5096        << EntityKind << Specialized;
5097    else if (isa<NamespaceDecl>(SpecializedContext))
5098      S.Diag(Loc, diag::err_template_spec_redecl_out_of_scope)
5099        << EntityKind << Specialized
5100        << cast<NamedDecl>(SpecializedContext);
5101
5102    S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
5103  }
5104
5105  // FIXME: check for specialization-after-instantiation errors and such.
5106
5107  return false;
5108}
5109
5110/// \brief Subroutine of Sema::CheckClassTemplatePartialSpecializationArgs
5111/// that checks non-type template partial specialization arguments.
5112static bool CheckNonTypeClassTemplatePartialSpecializationArgs(Sema &S,
5113                                                NonTypeTemplateParmDecl *Param,
5114                                                  const TemplateArgument *Args,
5115                                                        unsigned NumArgs) {
5116  for (unsigned I = 0; I != NumArgs; ++I) {
5117    if (Args[I].getKind() == TemplateArgument::Pack) {
5118      if (CheckNonTypeClassTemplatePartialSpecializationArgs(S, Param,
5119                                                           Args[I].pack_begin(),
5120                                                           Args[I].pack_size()))
5121        return true;
5122
5123      continue;
5124    }
5125
5126    if (Args[I].getKind() != TemplateArgument::Expression)
5127      continue;
5128
5129    Expr *ArgExpr = Args[I].getAsExpr();
5130
5131    // We can have a pack expansion of any of the bullets below.
5132    if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(ArgExpr))
5133      ArgExpr = Expansion->getPattern();
5134
5135    // Strip off any implicit casts we added as part of type checking.
5136    while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
5137      ArgExpr = ICE->getSubExpr();
5138
5139    // C++ [temp.class.spec]p8:
5140    //   A non-type argument is non-specialized if it is the name of a
5141    //   non-type parameter. All other non-type arguments are
5142    //   specialized.
5143    //
5144    // Below, we check the two conditions that only apply to
5145    // specialized non-type arguments, so skip any non-specialized
5146    // arguments.
5147    if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
5148      if (isa<NonTypeTemplateParmDecl>(DRE->getDecl()))
5149        continue;
5150
5151    // C++ [temp.class.spec]p9:
5152    //   Within the argument list of a class template partial
5153    //   specialization, the following restrictions apply:
5154    //     -- A partially specialized non-type argument expression
5155    //        shall not involve a template parameter of the partial
5156    //        specialization except when the argument expression is a
5157    //        simple identifier.
5158    if (ArgExpr->isTypeDependent() || ArgExpr->isValueDependent()) {
5159      S.Diag(ArgExpr->getLocStart(),
5160           diag::err_dependent_non_type_arg_in_partial_spec)
5161        << ArgExpr->getSourceRange();
5162      return true;
5163    }
5164
5165    //     -- The type of a template parameter corresponding to a
5166    //        specialized non-type argument shall not be dependent on a
5167    //        parameter of the specialization.
5168    if (Param->getType()->isDependentType()) {
5169      S.Diag(ArgExpr->getLocStart(),
5170           diag::err_dependent_typed_non_type_arg_in_partial_spec)
5171        << Param->getType()
5172        << ArgExpr->getSourceRange();
5173      S.Diag(Param->getLocation(), diag::note_template_param_here);
5174      return true;
5175    }
5176  }
5177
5178  return false;
5179}
5180
5181/// \brief Check the non-type template arguments of a class template
5182/// partial specialization according to C++ [temp.class.spec]p9.
5183///
5184/// \param TemplateParams the template parameters of the primary class
5185/// template.
5186///
5187/// \param TemplateArgs the template arguments of the class template
5188/// partial specialization.
5189///
5190/// \returns true if there was an error, false otherwise.
5191static bool CheckClassTemplatePartialSpecializationArgs(Sema &S,
5192                                        TemplateParameterList *TemplateParams,
5193                       SmallVectorImpl<TemplateArgument> &TemplateArgs) {
5194  const TemplateArgument *ArgList = TemplateArgs.data();
5195
5196  for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
5197    NonTypeTemplateParmDecl *Param
5198      = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
5199    if (!Param)
5200      continue;
5201
5202    if (CheckNonTypeClassTemplatePartialSpecializationArgs(S, Param,
5203                                                           &ArgList[I], 1))
5204      return true;
5205  }
5206
5207  return false;
5208}
5209
5210DeclResult
5211Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec,
5212                                       TagUseKind TUK,
5213                                       SourceLocation KWLoc,
5214                                       SourceLocation ModulePrivateLoc,
5215                                       CXXScopeSpec &SS,
5216                                       TemplateTy TemplateD,
5217                                       SourceLocation TemplateNameLoc,
5218                                       SourceLocation LAngleLoc,
5219                                       ASTTemplateArgsPtr TemplateArgsIn,
5220                                       SourceLocation RAngleLoc,
5221                                       AttributeList *Attr,
5222                               MultiTemplateParamsArg TemplateParameterLists) {
5223  assert(TUK != TUK_Reference && "References are not specializations");
5224
5225  // NOTE: KWLoc is the location of the tag keyword. This will instead
5226  // store the location of the outermost template keyword in the declaration.
5227  SourceLocation TemplateKWLoc = TemplateParameterLists.size() > 0
5228    ? TemplateParameterLists[0]->getTemplateLoc() : SourceLocation();
5229
5230  // Find the class template we're specializing
5231  TemplateName Name = TemplateD.getAsVal<TemplateName>();
5232  ClassTemplateDecl *ClassTemplate
5233    = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
5234
5235  if (!ClassTemplate) {
5236    Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
5237      << (Name.getAsTemplateDecl() &&
5238          isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
5239    return true;
5240  }
5241
5242  bool isExplicitSpecialization = false;
5243  bool isPartialSpecialization = false;
5244
5245  // Check the validity of the template headers that introduce this
5246  // template.
5247  // FIXME: We probably shouldn't complain about these headers for
5248  // friend declarations.
5249  bool Invalid = false;
5250  TemplateParameterList *TemplateParams
5251    = MatchTemplateParametersToScopeSpecifier(TemplateNameLoc,
5252                                              TemplateNameLoc,
5253                                              SS,
5254                                              TemplateParameterLists.data(),
5255                                              TemplateParameterLists.size(),
5256                                              TUK == TUK_Friend,
5257                                              isExplicitSpecialization,
5258                                              Invalid);
5259  if (Invalid)
5260    return true;
5261
5262  if (TemplateParams && TemplateParams->size() > 0) {
5263    isPartialSpecialization = true;
5264
5265    if (TUK == TUK_Friend) {
5266      Diag(KWLoc, diag::err_partial_specialization_friend)
5267        << SourceRange(LAngleLoc, RAngleLoc);
5268      return true;
5269    }
5270
5271    // C++ [temp.class.spec]p10:
5272    //   The template parameter list of a specialization shall not
5273    //   contain default template argument values.
5274    for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
5275      Decl *Param = TemplateParams->getParam(I);
5276      if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
5277        if (TTP->hasDefaultArgument()) {
5278          Diag(TTP->getDefaultArgumentLoc(),
5279               diag::err_default_arg_in_partial_spec);
5280          TTP->removeDefaultArgument();
5281        }
5282      } else if (NonTypeTemplateParmDecl *NTTP
5283                   = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
5284        if (Expr *DefArg = NTTP->getDefaultArgument()) {
5285          Diag(NTTP->getDefaultArgumentLoc(),
5286               diag::err_default_arg_in_partial_spec)
5287            << DefArg->getSourceRange();
5288          NTTP->removeDefaultArgument();
5289        }
5290      } else {
5291        TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
5292        if (TTP->hasDefaultArgument()) {
5293          Diag(TTP->getDefaultArgument().getLocation(),
5294               diag::err_default_arg_in_partial_spec)
5295            << TTP->getDefaultArgument().getSourceRange();
5296          TTP->removeDefaultArgument();
5297        }
5298      }
5299    }
5300  } else if (TemplateParams) {
5301    if (TUK == TUK_Friend)
5302      Diag(KWLoc, diag::err_template_spec_friend)
5303        << FixItHint::CreateRemoval(
5304                                SourceRange(TemplateParams->getTemplateLoc(),
5305                                            TemplateParams->getRAngleLoc()))
5306        << SourceRange(LAngleLoc, RAngleLoc);
5307    else
5308      isExplicitSpecialization = true;
5309  } else if (TUK != TUK_Friend) {
5310    Diag(KWLoc, diag::err_template_spec_needs_header)
5311      << FixItHint::CreateInsertion(KWLoc, "template<> ");
5312    TemplateKWLoc = KWLoc;
5313    isExplicitSpecialization = true;
5314  }
5315
5316  // Check that the specialization uses the same tag kind as the
5317  // original template.
5318  TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
5319  assert(Kind != TTK_Enum && "Invalid enum tag in class template spec!");
5320  if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
5321                                    Kind, TUK == TUK_Definition, KWLoc,
5322                                    *ClassTemplate->getIdentifier())) {
5323    Diag(KWLoc, diag::err_use_with_wrong_tag)
5324      << ClassTemplate
5325      << FixItHint::CreateReplacement(KWLoc,
5326                            ClassTemplate->getTemplatedDecl()->getKindName());
5327    Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
5328         diag::note_previous_use);
5329    Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
5330  }
5331
5332  // Translate the parser's template argument list in our AST format.
5333  TemplateArgumentListInfo TemplateArgs;
5334  TemplateArgs.setLAngleLoc(LAngleLoc);
5335  TemplateArgs.setRAngleLoc(RAngleLoc);
5336  translateTemplateArguments(TemplateArgsIn, TemplateArgs);
5337
5338  // Check for unexpanded parameter packs in any of the template arguments.
5339  for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
5340    if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
5341                                        UPPC_PartialSpecialization))
5342      return true;
5343
5344  // Check that the template argument list is well-formed for this
5345  // template.
5346  SmallVector<TemplateArgument, 4> Converted;
5347  if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
5348                                TemplateArgs, false, Converted))
5349    return true;
5350
5351  // Find the class template (partial) specialization declaration that
5352  // corresponds to these arguments.
5353  if (isPartialSpecialization) {
5354    if (CheckClassTemplatePartialSpecializationArgs(*this,
5355                                         ClassTemplate->getTemplateParameters(),
5356                                         Converted))
5357      return true;
5358
5359    bool InstantiationDependent;
5360    if (!Name.isDependent() &&
5361        !TemplateSpecializationType::anyDependentTemplateArguments(
5362                                             TemplateArgs.getArgumentArray(),
5363                                                         TemplateArgs.size(),
5364                                                     InstantiationDependent)) {
5365      Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
5366        << ClassTemplate->getDeclName();
5367      isPartialSpecialization = false;
5368    }
5369  }
5370
5371  void *InsertPos = 0;
5372  ClassTemplateSpecializationDecl *PrevDecl = 0;
5373
5374  if (isPartialSpecialization)
5375    // FIXME: Template parameter list matters, too
5376    PrevDecl
5377      = ClassTemplate->findPartialSpecialization(Converted.data(),
5378                                                 Converted.size(),
5379                                                 InsertPos);
5380  else
5381    PrevDecl
5382      = ClassTemplate->findSpecialization(Converted.data(),
5383                                          Converted.size(), InsertPos);
5384
5385  ClassTemplateSpecializationDecl *Specialization = 0;
5386
5387  // Check whether we can declare a class template specialization in
5388  // the current scope.
5389  if (TUK != TUK_Friend &&
5390      CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
5391                                       TemplateNameLoc,
5392                                       isPartialSpecialization))
5393    return true;
5394
5395  // The canonical type
5396  QualType CanonType;
5397  if (PrevDecl &&
5398      (PrevDecl->getSpecializationKind() == TSK_Undeclared ||
5399               TUK == TUK_Friend)) {
5400    // Since the only prior class template specialization with these
5401    // arguments was referenced but not declared, or we're only
5402    // referencing this specialization as a friend, reuse that
5403    // declaration node as our own, updating its source location and
5404    // the list of outer template parameters to reflect our new declaration.
5405    Specialization = PrevDecl;
5406    Specialization->setLocation(TemplateNameLoc);
5407    if (TemplateParameterLists.size() > 0) {
5408      Specialization->setTemplateParameterListsInfo(Context,
5409                                              TemplateParameterLists.size(),
5410                                              TemplateParameterLists.data());
5411    }
5412    PrevDecl = 0;
5413    CanonType = Context.getTypeDeclType(Specialization);
5414  } else if (isPartialSpecialization) {
5415    // Build the canonical type that describes the converted template
5416    // arguments of the class template partial specialization.
5417    TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
5418    CanonType = Context.getTemplateSpecializationType(CanonTemplate,
5419                                                      Converted.data(),
5420                                                      Converted.size());
5421
5422    if (Context.hasSameType(CanonType,
5423                        ClassTemplate->getInjectedClassNameSpecialization())) {
5424      // C++ [temp.class.spec]p9b3:
5425      //
5426      //   -- The argument list of the specialization shall not be identical
5427      //      to the implicit argument list of the primary template.
5428      Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
5429        << (TUK == TUK_Definition)
5430        << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
5431      return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
5432                                ClassTemplate->getIdentifier(),
5433                                TemplateNameLoc,
5434                                Attr,
5435                                TemplateParams,
5436                                AS_none, /*ModulePrivateLoc=*/SourceLocation(),
5437                                TemplateParameterLists.size() - 1,
5438                                TemplateParameterLists.data());
5439    }
5440
5441    // Create a new class template partial specialization declaration node.
5442    ClassTemplatePartialSpecializationDecl *PrevPartial
5443      = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
5444    unsigned SequenceNumber = PrevPartial? PrevPartial->getSequenceNumber()
5445                            : ClassTemplate->getNextPartialSpecSequenceNumber();
5446    ClassTemplatePartialSpecializationDecl *Partial
5447      = ClassTemplatePartialSpecializationDecl::Create(Context, Kind,
5448                                             ClassTemplate->getDeclContext(),
5449                                                       KWLoc, TemplateNameLoc,
5450                                                       TemplateParams,
5451                                                       ClassTemplate,
5452                                                       Converted.data(),
5453                                                       Converted.size(),
5454                                                       TemplateArgs,
5455                                                       CanonType,
5456                                                       PrevPartial,
5457                                                       SequenceNumber);
5458    SetNestedNameSpecifier(Partial, SS);
5459    if (TemplateParameterLists.size() > 1 && SS.isSet()) {
5460      Partial->setTemplateParameterListsInfo(Context,
5461                                             TemplateParameterLists.size() - 1,
5462                                             TemplateParameterLists.data());
5463    }
5464
5465    if (!PrevPartial)
5466      ClassTemplate->AddPartialSpecialization(Partial, InsertPos);
5467    Specialization = Partial;
5468
5469    // If we are providing an explicit specialization of a member class
5470    // template specialization, make a note of that.
5471    if (PrevPartial && PrevPartial->getInstantiatedFromMember())
5472      PrevPartial->setMemberSpecialization();
5473
5474    // Check that all of the template parameters of the class template
5475    // partial specialization are deducible from the template
5476    // arguments. If not, this class template partial specialization
5477    // will never be used.
5478    llvm::SmallBitVector DeducibleParams(TemplateParams->size());
5479    MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
5480                               TemplateParams->getDepth(),
5481                               DeducibleParams);
5482
5483    if (!DeducibleParams.all()) {
5484      unsigned NumNonDeducible = DeducibleParams.size()-DeducibleParams.count();
5485      Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
5486        << (NumNonDeducible > 1)
5487        << SourceRange(TemplateNameLoc, RAngleLoc);
5488      for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
5489        if (!DeducibleParams[I]) {
5490          NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
5491          if (Param->getDeclName())
5492            Diag(Param->getLocation(),
5493                 diag::note_partial_spec_unused_parameter)
5494              << Param->getDeclName();
5495          else
5496            Diag(Param->getLocation(),
5497                 diag::note_partial_spec_unused_parameter)
5498              << "<anonymous>";
5499        }
5500      }
5501    }
5502  } else {
5503    // Create a new class template specialization declaration node for
5504    // this explicit specialization or friend declaration.
5505    Specialization
5506      = ClassTemplateSpecializationDecl::Create(Context, Kind,
5507                                             ClassTemplate->getDeclContext(),
5508                                                KWLoc, TemplateNameLoc,
5509                                                ClassTemplate,
5510                                                Converted.data(),
5511                                                Converted.size(),
5512                                                PrevDecl);
5513    SetNestedNameSpecifier(Specialization, SS);
5514    if (TemplateParameterLists.size() > 0) {
5515      Specialization->setTemplateParameterListsInfo(Context,
5516                                              TemplateParameterLists.size(),
5517                                              TemplateParameterLists.data());
5518    }
5519
5520    if (!PrevDecl)
5521      ClassTemplate->AddSpecialization(Specialization, InsertPos);
5522
5523    CanonType = Context.getTypeDeclType(Specialization);
5524  }
5525
5526  // C++ [temp.expl.spec]p6:
5527  //   If a template, a member template or the member of a class template is
5528  //   explicitly specialized then that specialization shall be declared
5529  //   before the first use of that specialization that would cause an implicit
5530  //   instantiation to take place, in every translation unit in which such a
5531  //   use occurs; no diagnostic is required.
5532  if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
5533    bool Okay = false;
5534    for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
5535      // Is there any previous explicit specialization declaration?
5536      if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
5537        Okay = true;
5538        break;
5539      }
5540    }
5541
5542    if (!Okay) {
5543      SourceRange Range(TemplateNameLoc, RAngleLoc);
5544      Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
5545        << Context.getTypeDeclType(Specialization) << Range;
5546
5547      Diag(PrevDecl->getPointOfInstantiation(),
5548           diag::note_instantiation_required_here)
5549        << (PrevDecl->getTemplateSpecializationKind()
5550                                                != TSK_ImplicitInstantiation);
5551      return true;
5552    }
5553  }
5554
5555  // If this is not a friend, note that this is an explicit specialization.
5556  if (TUK != TUK_Friend)
5557    Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
5558
5559  // Check that this isn't a redefinition of this specialization.
5560  if (TUK == TUK_Definition) {
5561    if (RecordDecl *Def = Specialization->getDefinition()) {
5562      SourceRange Range(TemplateNameLoc, RAngleLoc);
5563      Diag(TemplateNameLoc, diag::err_redefinition)
5564        << Context.getTypeDeclType(Specialization) << Range;
5565      Diag(Def->getLocation(), diag::note_previous_definition);
5566      Specialization->setInvalidDecl();
5567      return true;
5568    }
5569  }
5570
5571  if (Attr)
5572    ProcessDeclAttributeList(S, Specialization, Attr);
5573
5574  // Add alignment attributes if necessary; these attributes are checked when
5575  // the ASTContext lays out the structure.
5576  if (TUK == TUK_Definition) {
5577    AddAlignmentAttributesForRecord(Specialization);
5578    AddMsStructLayoutForRecord(Specialization);
5579  }
5580
5581  if (ModulePrivateLoc.isValid())
5582    Diag(Specialization->getLocation(), diag::err_module_private_specialization)
5583      << (isPartialSpecialization? 1 : 0)
5584      << FixItHint::CreateRemoval(ModulePrivateLoc);
5585
5586  // Build the fully-sugared type for this class template
5587  // specialization as the user wrote in the specialization
5588  // itself. This means that we'll pretty-print the type retrieved
5589  // from the specialization's declaration the way that the user
5590  // actually wrote the specialization, rather than formatting the
5591  // name based on the "canonical" representation used to store the
5592  // template arguments in the specialization.
5593  TypeSourceInfo *WrittenTy
5594    = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
5595                                                TemplateArgs, CanonType);
5596  if (TUK != TUK_Friend) {
5597    Specialization->setTypeAsWritten(WrittenTy);
5598    Specialization->setTemplateKeywordLoc(TemplateKWLoc);
5599  }
5600
5601  // C++ [temp.expl.spec]p9:
5602  //   A template explicit specialization is in the scope of the
5603  //   namespace in which the template was defined.
5604  //
5605  // We actually implement this paragraph where we set the semantic
5606  // context (in the creation of the ClassTemplateSpecializationDecl),
5607  // but we also maintain the lexical context where the actual
5608  // definition occurs.
5609  Specialization->setLexicalDeclContext(CurContext);
5610
5611  // We may be starting the definition of this specialization.
5612  if (TUK == TUK_Definition)
5613    Specialization->startDefinition();
5614
5615  if (TUK == TUK_Friend) {
5616    FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
5617                                            TemplateNameLoc,
5618                                            WrittenTy,
5619                                            /*FIXME:*/KWLoc);
5620    Friend->setAccess(AS_public);
5621    CurContext->addDecl(Friend);
5622  } else {
5623    // Add the specialization into its lexical context, so that it can
5624    // be seen when iterating through the list of declarations in that
5625    // context. However, specializations are not found by name lookup.
5626    CurContext->addDecl(Specialization);
5627  }
5628  return Specialization;
5629}
5630
5631Decl *Sema::ActOnTemplateDeclarator(Scope *S,
5632                              MultiTemplateParamsArg TemplateParameterLists,
5633                                    Declarator &D) {
5634  Decl *NewDecl = HandleDeclarator(S, D, TemplateParameterLists);
5635  ActOnDocumentableDecl(NewDecl);
5636  return NewDecl;
5637}
5638
5639Decl *Sema::ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope,
5640                               MultiTemplateParamsArg TemplateParameterLists,
5641                                            Declarator &D) {
5642  assert(getCurFunctionDecl() == 0 && "Function parsing confused");
5643  DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
5644
5645  if (FTI.hasPrototype) {
5646    // FIXME: Diagnose arguments without names in C.
5647  }
5648
5649  Scope *ParentScope = FnBodyScope->getParent();
5650
5651  D.setFunctionDefinitionKind(FDK_Definition);
5652  Decl *DP = HandleDeclarator(ParentScope, D,
5653                              TemplateParameterLists);
5654  return ActOnStartOfFunctionDef(FnBodyScope, DP);
5655}
5656
5657/// \brief Strips various properties off an implicit instantiation
5658/// that has just been explicitly specialized.
5659static void StripImplicitInstantiation(NamedDecl *D) {
5660  D->dropAttrs();
5661
5662  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
5663    FD->setInlineSpecified(false);
5664
5665    for (FunctionDecl::param_iterator I = FD->param_begin(),
5666                                      E = FD->param_end();
5667         I != E; ++I)
5668      (*I)->dropAttrs();
5669  }
5670}
5671
5672/// \brief Compute the diagnostic location for an explicit instantiation
5673//  declaration or definition.
5674static SourceLocation DiagLocForExplicitInstantiation(
5675    NamedDecl* D, SourceLocation PointOfInstantiation) {
5676  // Explicit instantiations following a specialization have no effect and
5677  // hence no PointOfInstantiation. In that case, walk decl backwards
5678  // until a valid name loc is found.
5679  SourceLocation PrevDiagLoc = PointOfInstantiation;
5680  for (Decl *Prev = D; Prev && !PrevDiagLoc.isValid();
5681       Prev = Prev->getPreviousDecl()) {
5682    PrevDiagLoc = Prev->getLocation();
5683  }
5684  assert(PrevDiagLoc.isValid() &&
5685         "Explicit instantiation without point of instantiation?");
5686  return PrevDiagLoc;
5687}
5688
5689/// \brief Diagnose cases where we have an explicit template specialization
5690/// before/after an explicit template instantiation, producing diagnostics
5691/// for those cases where they are required and determining whether the
5692/// new specialization/instantiation will have any effect.
5693///
5694/// \param NewLoc the location of the new explicit specialization or
5695/// instantiation.
5696///
5697/// \param NewTSK the kind of the new explicit specialization or instantiation.
5698///
5699/// \param PrevDecl the previous declaration of the entity.
5700///
5701/// \param PrevTSK the kind of the old explicit specialization or instantiatin.
5702///
5703/// \param PrevPointOfInstantiation if valid, indicates where the previus
5704/// declaration was instantiated (either implicitly or explicitly).
5705///
5706/// \param HasNoEffect will be set to true to indicate that the new
5707/// specialization or instantiation has no effect and should be ignored.
5708///
5709/// \returns true if there was an error that should prevent the introduction of
5710/// the new declaration into the AST, false otherwise.
5711bool
5712Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
5713                                             TemplateSpecializationKind NewTSK,
5714                                             NamedDecl *PrevDecl,
5715                                             TemplateSpecializationKind PrevTSK,
5716                                        SourceLocation PrevPointOfInstantiation,
5717                                             bool &HasNoEffect) {
5718  HasNoEffect = false;
5719
5720  switch (NewTSK) {
5721  case TSK_Undeclared:
5722  case TSK_ImplicitInstantiation:
5723    llvm_unreachable("Don't check implicit instantiations here");
5724
5725  case TSK_ExplicitSpecialization:
5726    switch (PrevTSK) {
5727    case TSK_Undeclared:
5728    case TSK_ExplicitSpecialization:
5729      // Okay, we're just specializing something that is either already
5730      // explicitly specialized or has merely been mentioned without any
5731      // instantiation.
5732      return false;
5733
5734    case TSK_ImplicitInstantiation:
5735      if (PrevPointOfInstantiation.isInvalid()) {
5736        // The declaration itself has not actually been instantiated, so it is
5737        // still okay to specialize it.
5738        StripImplicitInstantiation(PrevDecl);
5739        return false;
5740      }
5741      // Fall through
5742
5743    case TSK_ExplicitInstantiationDeclaration:
5744    case TSK_ExplicitInstantiationDefinition:
5745      assert((PrevTSK == TSK_ImplicitInstantiation ||
5746              PrevPointOfInstantiation.isValid()) &&
5747             "Explicit instantiation without point of instantiation?");
5748
5749      // C++ [temp.expl.spec]p6:
5750      //   If a template, a member template or the member of a class template
5751      //   is explicitly specialized then that specialization shall be declared
5752      //   before the first use of that specialization that would cause an
5753      //   implicit instantiation to take place, in every translation unit in
5754      //   which such a use occurs; no diagnostic is required.
5755      for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
5756        // Is there any previous explicit specialization declaration?
5757        if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization)
5758          return false;
5759      }
5760
5761      Diag(NewLoc, diag::err_specialization_after_instantiation)
5762        << PrevDecl;
5763      Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
5764        << (PrevTSK != TSK_ImplicitInstantiation);
5765
5766      return true;
5767    }
5768
5769  case TSK_ExplicitInstantiationDeclaration:
5770    switch (PrevTSK) {
5771    case TSK_ExplicitInstantiationDeclaration:
5772      // This explicit instantiation declaration is redundant (that's okay).
5773      HasNoEffect = true;
5774      return false;
5775
5776    case TSK_Undeclared:
5777    case TSK_ImplicitInstantiation:
5778      // We're explicitly instantiating something that may have already been
5779      // implicitly instantiated; that's fine.
5780      return false;
5781
5782    case TSK_ExplicitSpecialization:
5783      // C++0x [temp.explicit]p4:
5784      //   For a given set of template parameters, if an explicit instantiation
5785      //   of a template appears after a declaration of an explicit
5786      //   specialization for that template, the explicit instantiation has no
5787      //   effect.
5788      HasNoEffect = true;
5789      return false;
5790
5791    case TSK_ExplicitInstantiationDefinition:
5792      // C++0x [temp.explicit]p10:
5793      //   If an entity is the subject of both an explicit instantiation
5794      //   declaration and an explicit instantiation definition in the same
5795      //   translation unit, the definition shall follow the declaration.
5796      Diag(NewLoc,
5797           diag::err_explicit_instantiation_declaration_after_definition);
5798
5799      // Explicit instantiations following a specialization have no effect and
5800      // hence no PrevPointOfInstantiation. In that case, walk decl backwards
5801      // until a valid name loc is found.
5802      Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
5803           diag::note_explicit_instantiation_definition_here);
5804      HasNoEffect = true;
5805      return false;
5806    }
5807
5808  case TSK_ExplicitInstantiationDefinition:
5809    switch (PrevTSK) {
5810    case TSK_Undeclared:
5811    case TSK_ImplicitInstantiation:
5812      // We're explicitly instantiating something that may have already been
5813      // implicitly instantiated; that's fine.
5814      return false;
5815
5816    case TSK_ExplicitSpecialization:
5817      // C++ DR 259, C++0x [temp.explicit]p4:
5818      //   For a given set of template parameters, if an explicit
5819      //   instantiation of a template appears after a declaration of
5820      //   an explicit specialization for that template, the explicit
5821      //   instantiation has no effect.
5822      //
5823      // In C++98/03 mode, we only give an extension warning here, because it
5824      // is not harmful to try to explicitly instantiate something that
5825      // has been explicitly specialized.
5826      Diag(NewLoc, getLangOpts().CPlusPlus11 ?
5827           diag::warn_cxx98_compat_explicit_instantiation_after_specialization :
5828           diag::ext_explicit_instantiation_after_specialization)
5829        << PrevDecl;
5830      Diag(PrevDecl->getLocation(),
5831           diag::note_previous_template_specialization);
5832      HasNoEffect = true;
5833      return false;
5834
5835    case TSK_ExplicitInstantiationDeclaration:
5836      // We're explicity instantiating a definition for something for which we
5837      // were previously asked to suppress instantiations. That's fine.
5838
5839      // C++0x [temp.explicit]p4:
5840      //   For a given set of template parameters, if an explicit instantiation
5841      //   of a template appears after a declaration of an explicit
5842      //   specialization for that template, the explicit instantiation has no
5843      //   effect.
5844      for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
5845        // Is there any previous explicit specialization declaration?
5846        if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
5847          HasNoEffect = true;
5848          break;
5849        }
5850      }
5851
5852      return false;
5853
5854    case TSK_ExplicitInstantiationDefinition:
5855      // C++0x [temp.spec]p5:
5856      //   For a given template and a given set of template-arguments,
5857      //     - an explicit instantiation definition shall appear at most once
5858      //       in a program,
5859      Diag(NewLoc, diag::err_explicit_instantiation_duplicate)
5860        << PrevDecl;
5861      Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
5862           diag::note_previous_explicit_instantiation);
5863      HasNoEffect = true;
5864      return false;
5865    }
5866  }
5867
5868  llvm_unreachable("Missing specialization/instantiation case?");
5869}
5870
5871/// \brief Perform semantic analysis for the given dependent function
5872/// template specialization.
5873///
5874/// The only possible way to get a dependent function template specialization
5875/// is with a friend declaration, like so:
5876///
5877/// \code
5878///   template \<class T> void foo(T);
5879///   template \<class T> class A {
5880///     friend void foo<>(T);
5881///   };
5882/// \endcode
5883///
5884/// There really isn't any useful analysis we can do here, so we
5885/// just store the information.
5886bool
5887Sema::CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
5888                   const TemplateArgumentListInfo &ExplicitTemplateArgs,
5889                                                   LookupResult &Previous) {
5890  // Remove anything from Previous that isn't a function template in
5891  // the correct context.
5892  DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
5893  LookupResult::Filter F = Previous.makeFilter();
5894  while (F.hasNext()) {
5895    NamedDecl *D = F.next()->getUnderlyingDecl();
5896    if (!isa<FunctionTemplateDecl>(D) ||
5897        !FDLookupContext->InEnclosingNamespaceSetOf(
5898                              D->getDeclContext()->getRedeclContext()))
5899      F.erase();
5900  }
5901  F.done();
5902
5903  // Should this be diagnosed here?
5904  if (Previous.empty()) return true;
5905
5906  FD->setDependentTemplateSpecialization(Context, Previous.asUnresolvedSet(),
5907                                         ExplicitTemplateArgs);
5908  return false;
5909}
5910
5911/// \brief Perform semantic analysis for the given function template
5912/// specialization.
5913///
5914/// This routine performs all of the semantic analysis required for an
5915/// explicit function template specialization. On successful completion,
5916/// the function declaration \p FD will become a function template
5917/// specialization.
5918///
5919/// \param FD the function declaration, which will be updated to become a
5920/// function template specialization.
5921///
5922/// \param ExplicitTemplateArgs the explicitly-provided template arguments,
5923/// if any. Note that this may be valid info even when 0 arguments are
5924/// explicitly provided as in, e.g., \c void sort<>(char*, char*);
5925/// as it anyway contains info on the angle brackets locations.
5926///
5927/// \param Previous the set of declarations that may be specialized by
5928/// this function specialization.
5929bool
5930Sema::CheckFunctionTemplateSpecialization(FunctionDecl *FD,
5931                                 TemplateArgumentListInfo *ExplicitTemplateArgs,
5932                                          LookupResult &Previous) {
5933  // The set of function template specializations that could match this
5934  // explicit function template specialization.
5935  UnresolvedSet<8> Candidates;
5936
5937  DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
5938  for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
5939         I != E; ++I) {
5940    NamedDecl *Ovl = (*I)->getUnderlyingDecl();
5941    if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
5942      // Only consider templates found within the same semantic lookup scope as
5943      // FD.
5944      if (!FDLookupContext->InEnclosingNamespaceSetOf(
5945                                Ovl->getDeclContext()->getRedeclContext()))
5946        continue;
5947
5948      // When matching a constexpr member function template specialization
5949      // against the primary template, we don't yet know whether the
5950      // specialization has an implicit 'const' (because we don't know whether
5951      // it will be a static member function until we know which template it
5952      // specializes), so adjust it now assuming it specializes this template.
5953      QualType FT = FD->getType();
5954      if (FD->isConstexpr()) {
5955        CXXMethodDecl *OldMD =
5956          dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
5957        if (OldMD && OldMD->isConst()) {
5958          const FunctionProtoType *FPT = FT->castAs<FunctionProtoType>();
5959          FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
5960          EPI.TypeQuals |= Qualifiers::Const;
5961          FT = Context.getFunctionType(FPT->getResultType(), FPT->getArgTypes(),
5962                                       EPI);
5963        }
5964      }
5965
5966      // C++ [temp.expl.spec]p11:
5967      //   A trailing template-argument can be left unspecified in the
5968      //   template-id naming an explicit function template specialization
5969      //   provided it can be deduced from the function argument type.
5970      // Perform template argument deduction to determine whether we may be
5971      // specializing this template.
5972      // FIXME: It is somewhat wasteful to build
5973      TemplateDeductionInfo Info(FD->getLocation());
5974      FunctionDecl *Specialization = 0;
5975      if (TemplateDeductionResult TDK
5976            = DeduceTemplateArguments(FunTmpl, ExplicitTemplateArgs, FT,
5977                                      Specialization, Info)) {
5978        // FIXME: Template argument deduction failed; record why it failed, so
5979        // that we can provide nifty diagnostics.
5980        (void)TDK;
5981        continue;
5982      }
5983
5984      // Record this candidate.
5985      Candidates.addDecl(Specialization, I.getAccess());
5986    }
5987  }
5988
5989  // Find the most specialized function template.
5990  UnresolvedSetIterator Result
5991    = getMostSpecialized(Candidates.begin(), Candidates.end(),
5992                         TPOC_Other, 0, FD->getLocation(),
5993                  PDiag(diag::err_function_template_spec_no_match)
5994                    << FD->getDeclName(),
5995                  PDiag(diag::err_function_template_spec_ambiguous)
5996                    << FD->getDeclName() << (ExplicitTemplateArgs != 0),
5997                  PDiag(diag::note_function_template_spec_matched));
5998  if (Result == Candidates.end())
5999    return true;
6000
6001  // Ignore access information;  it doesn't figure into redeclaration checking.
6002  FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
6003
6004  FunctionTemplateSpecializationInfo *SpecInfo
6005    = Specialization->getTemplateSpecializationInfo();
6006  assert(SpecInfo && "Function template specialization info missing?");
6007
6008  // Note: do not overwrite location info if previous template
6009  // specialization kind was explicit.
6010  TemplateSpecializationKind TSK = SpecInfo->getTemplateSpecializationKind();
6011  if (TSK == TSK_Undeclared || TSK == TSK_ImplicitInstantiation) {
6012    Specialization->setLocation(FD->getLocation());
6013    // C++11 [dcl.constexpr]p1: An explicit specialization of a constexpr
6014    // function can differ from the template declaration with respect to
6015    // the constexpr specifier.
6016    Specialization->setConstexpr(FD->isConstexpr());
6017  }
6018
6019  // FIXME: Check if the prior specialization has a point of instantiation.
6020  // If so, we have run afoul of .
6021
6022  // If this is a friend declaration, then we're not really declaring
6023  // an explicit specialization.
6024  bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
6025
6026  // Check the scope of this explicit specialization.
6027  if (!isFriend &&
6028      CheckTemplateSpecializationScope(*this,
6029                                       Specialization->getPrimaryTemplate(),
6030                                       Specialization, FD->getLocation(),
6031                                       false))
6032    return true;
6033
6034  // C++ [temp.expl.spec]p6:
6035  //   If a template, a member template or the member of a class template is
6036  //   explicitly specialized then that specialization shall be declared
6037  //   before the first use of that specialization that would cause an implicit
6038  //   instantiation to take place, in every translation unit in which such a
6039  //   use occurs; no diagnostic is required.
6040  bool HasNoEffect = false;
6041  if (!isFriend &&
6042      CheckSpecializationInstantiationRedecl(FD->getLocation(),
6043                                             TSK_ExplicitSpecialization,
6044                                             Specialization,
6045                                   SpecInfo->getTemplateSpecializationKind(),
6046                                         SpecInfo->getPointOfInstantiation(),
6047                                             HasNoEffect))
6048    return true;
6049
6050  // Mark the prior declaration as an explicit specialization, so that later
6051  // clients know that this is an explicit specialization.
6052  if (!isFriend) {
6053    SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
6054    MarkUnusedFileScopedDecl(Specialization);
6055  }
6056
6057  // Turn the given function declaration into a function template
6058  // specialization, with the template arguments from the previous
6059  // specialization.
6060  // Take copies of (semantic and syntactic) template argument lists.
6061  const TemplateArgumentList* TemplArgs = new (Context)
6062    TemplateArgumentList(Specialization->getTemplateSpecializationArgs());
6063  FD->setFunctionTemplateSpecialization(Specialization->getPrimaryTemplate(),
6064                                        TemplArgs, /*InsertPos=*/0,
6065                                    SpecInfo->getTemplateSpecializationKind(),
6066                                        ExplicitTemplateArgs);
6067
6068  // The "previous declaration" for this function template specialization is
6069  // the prior function template specialization.
6070  Previous.clear();
6071  Previous.addDecl(Specialization);
6072  return false;
6073}
6074
6075/// \brief Perform semantic analysis for the given non-template member
6076/// specialization.
6077///
6078/// This routine performs all of the semantic analysis required for an
6079/// explicit member function specialization. On successful completion,
6080/// the function declaration \p FD will become a member function
6081/// specialization.
6082///
6083/// \param Member the member declaration, which will be updated to become a
6084/// specialization.
6085///
6086/// \param Previous the set of declarations, one of which may be specialized
6087/// by this function specialization;  the set will be modified to contain the
6088/// redeclared member.
6089bool
6090Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
6091  assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
6092
6093  // Try to find the member we are instantiating.
6094  NamedDecl *Instantiation = 0;
6095  NamedDecl *InstantiatedFrom = 0;
6096  MemberSpecializationInfo *MSInfo = 0;
6097
6098  if (Previous.empty()) {
6099    // Nowhere to look anyway.
6100  } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
6101    for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6102           I != E; ++I) {
6103      NamedDecl *D = (*I)->getUnderlyingDecl();
6104      if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
6105        if (Context.hasSameType(Function->getType(), Method->getType())) {
6106          Instantiation = Method;
6107          InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
6108          MSInfo = Method->getMemberSpecializationInfo();
6109          break;
6110        }
6111      }
6112    }
6113  } else if (isa<VarDecl>(Member)) {
6114    VarDecl *PrevVar;
6115    if (Previous.isSingleResult() &&
6116        (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
6117      if (PrevVar->isStaticDataMember()) {
6118        Instantiation = PrevVar;
6119        InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
6120        MSInfo = PrevVar->getMemberSpecializationInfo();
6121      }
6122  } else if (isa<RecordDecl>(Member)) {
6123    CXXRecordDecl *PrevRecord;
6124    if (Previous.isSingleResult() &&
6125        (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
6126      Instantiation = PrevRecord;
6127      InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
6128      MSInfo = PrevRecord->getMemberSpecializationInfo();
6129    }
6130  } else if (isa<EnumDecl>(Member)) {
6131    EnumDecl *PrevEnum;
6132    if (Previous.isSingleResult() &&
6133        (PrevEnum = dyn_cast<EnumDecl>(Previous.getFoundDecl()))) {
6134      Instantiation = PrevEnum;
6135      InstantiatedFrom = PrevEnum->getInstantiatedFromMemberEnum();
6136      MSInfo = PrevEnum->getMemberSpecializationInfo();
6137    }
6138  }
6139
6140  if (!Instantiation) {
6141    // There is no previous declaration that matches. Since member
6142    // specializations are always out-of-line, the caller will complain about
6143    // this mismatch later.
6144    return false;
6145  }
6146
6147  // If this is a friend, just bail out here before we start turning
6148  // things into explicit specializations.
6149  if (Member->getFriendObjectKind() != Decl::FOK_None) {
6150    // Preserve instantiation information.
6151    if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) {
6152      cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction(
6153                                      cast<CXXMethodDecl>(InstantiatedFrom),
6154        cast<CXXMethodDecl>(Instantiation)->getTemplateSpecializationKind());
6155    } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) {
6156      cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
6157                                      cast<CXXRecordDecl>(InstantiatedFrom),
6158        cast<CXXRecordDecl>(Instantiation)->getTemplateSpecializationKind());
6159    }
6160
6161    Previous.clear();
6162    Previous.addDecl(Instantiation);
6163    return false;
6164  }
6165
6166  // Make sure that this is a specialization of a member.
6167  if (!InstantiatedFrom) {
6168    Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
6169      << Member;
6170    Diag(Instantiation->getLocation(), diag::note_specialized_decl);
6171    return true;
6172  }
6173
6174  // C++ [temp.expl.spec]p6:
6175  //   If a template, a member template or the member of a class template is
6176  //   explicitly specialized then that specialization shall be declared
6177  //   before the first use of that specialization that would cause an implicit
6178  //   instantiation to take place, in every translation unit in which such a
6179  //   use occurs; no diagnostic is required.
6180  assert(MSInfo && "Member specialization info missing?");
6181
6182  bool HasNoEffect = false;
6183  if (CheckSpecializationInstantiationRedecl(Member->getLocation(),
6184                                             TSK_ExplicitSpecialization,
6185                                             Instantiation,
6186                                     MSInfo->getTemplateSpecializationKind(),
6187                                           MSInfo->getPointOfInstantiation(),
6188                                             HasNoEffect))
6189    return true;
6190
6191  // Check the scope of this explicit specialization.
6192  if (CheckTemplateSpecializationScope(*this,
6193                                       InstantiatedFrom,
6194                                       Instantiation, Member->getLocation(),
6195                                       false))
6196    return true;
6197
6198  // Note that this is an explicit instantiation of a member.
6199  // the original declaration to note that it is an explicit specialization
6200  // (if it was previously an implicit instantiation). This latter step
6201  // makes bookkeeping easier.
6202  if (isa<FunctionDecl>(Member)) {
6203    FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
6204    if (InstantiationFunction->getTemplateSpecializationKind() ==
6205          TSK_ImplicitInstantiation) {
6206      InstantiationFunction->setTemplateSpecializationKind(
6207                                                  TSK_ExplicitSpecialization);
6208      InstantiationFunction->setLocation(Member->getLocation());
6209    }
6210
6211    cast<FunctionDecl>(Member)->setInstantiationOfMemberFunction(
6212                                        cast<CXXMethodDecl>(InstantiatedFrom),
6213                                                  TSK_ExplicitSpecialization);
6214    MarkUnusedFileScopedDecl(InstantiationFunction);
6215  } else if (isa<VarDecl>(Member)) {
6216    VarDecl *InstantiationVar = cast<VarDecl>(Instantiation);
6217    if (InstantiationVar->getTemplateSpecializationKind() ==
6218          TSK_ImplicitInstantiation) {
6219      InstantiationVar->setTemplateSpecializationKind(
6220                                                  TSK_ExplicitSpecialization);
6221      InstantiationVar->setLocation(Member->getLocation());
6222    }
6223
6224    Context.setInstantiatedFromStaticDataMember(cast<VarDecl>(Member),
6225                                                cast<VarDecl>(InstantiatedFrom),
6226                                                TSK_ExplicitSpecialization);
6227    MarkUnusedFileScopedDecl(InstantiationVar);
6228  } else if (isa<CXXRecordDecl>(Member)) {
6229    CXXRecordDecl *InstantiationClass = cast<CXXRecordDecl>(Instantiation);
6230    if (InstantiationClass->getTemplateSpecializationKind() ==
6231          TSK_ImplicitInstantiation) {
6232      InstantiationClass->setTemplateSpecializationKind(
6233                                                   TSK_ExplicitSpecialization);
6234      InstantiationClass->setLocation(Member->getLocation());
6235    }
6236
6237    cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
6238                                        cast<CXXRecordDecl>(InstantiatedFrom),
6239                                                   TSK_ExplicitSpecialization);
6240  } else {
6241    assert(isa<EnumDecl>(Member) && "Only member enums remain");
6242    EnumDecl *InstantiationEnum = cast<EnumDecl>(Instantiation);
6243    if (InstantiationEnum->getTemplateSpecializationKind() ==
6244          TSK_ImplicitInstantiation) {
6245      InstantiationEnum->setTemplateSpecializationKind(
6246                                                   TSK_ExplicitSpecialization);
6247      InstantiationEnum->setLocation(Member->getLocation());
6248    }
6249
6250    cast<EnumDecl>(Member)->setInstantiationOfMemberEnum(
6251        cast<EnumDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
6252  }
6253
6254  // Save the caller the trouble of having to figure out which declaration
6255  // this specialization matches.
6256  Previous.clear();
6257  Previous.addDecl(Instantiation);
6258  return false;
6259}
6260
6261/// \brief Check the scope of an explicit instantiation.
6262///
6263/// \returns true if a serious error occurs, false otherwise.
6264static bool CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
6265                                            SourceLocation InstLoc,
6266                                            bool WasQualifiedName) {
6267  DeclContext *OrigContext= D->getDeclContext()->getEnclosingNamespaceContext();
6268  DeclContext *CurContext = S.CurContext->getRedeclContext();
6269
6270  if (CurContext->isRecord()) {
6271    S.Diag(InstLoc, diag::err_explicit_instantiation_in_class)
6272      << D;
6273    return true;
6274  }
6275
6276  // C++11 [temp.explicit]p3:
6277  //   An explicit instantiation shall appear in an enclosing namespace of its
6278  //   template. If the name declared in the explicit instantiation is an
6279  //   unqualified name, the explicit instantiation shall appear in the
6280  //   namespace where its template is declared or, if that namespace is inline
6281  //   (7.3.1), any namespace from its enclosing namespace set.
6282  //
6283  // This is DR275, which we do not retroactively apply to C++98/03.
6284  if (WasQualifiedName) {
6285    if (CurContext->Encloses(OrigContext))
6286      return false;
6287  } else {
6288    if (CurContext->InEnclosingNamespaceSetOf(OrigContext))
6289      return false;
6290  }
6291
6292  if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(OrigContext)) {
6293    if (WasQualifiedName)
6294      S.Diag(InstLoc,
6295             S.getLangOpts().CPlusPlus11?
6296               diag::err_explicit_instantiation_out_of_scope :
6297               diag::warn_explicit_instantiation_out_of_scope_0x)
6298        << D << NS;
6299    else
6300      S.Diag(InstLoc,
6301             S.getLangOpts().CPlusPlus11?
6302               diag::err_explicit_instantiation_unqualified_wrong_namespace :
6303               diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
6304        << D << NS;
6305  } else
6306    S.Diag(InstLoc,
6307           S.getLangOpts().CPlusPlus11?
6308             diag::err_explicit_instantiation_must_be_global :
6309             diag::warn_explicit_instantiation_must_be_global_0x)
6310      << D;
6311  S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
6312  return false;
6313}
6314
6315/// \brief Determine whether the given scope specifier has a template-id in it.
6316static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
6317  if (!SS.isSet())
6318    return false;
6319
6320  // C++11 [temp.explicit]p3:
6321  //   If the explicit instantiation is for a member function, a member class
6322  //   or a static data member of a class template specialization, the name of
6323  //   the class template specialization in the qualified-id for the member
6324  //   name shall be a simple-template-id.
6325  //
6326  // C++98 has the same restriction, just worded differently.
6327  for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
6328       NNS; NNS = NNS->getPrefix())
6329    if (const Type *T = NNS->getAsType())
6330      if (isa<TemplateSpecializationType>(T))
6331        return true;
6332
6333  return false;
6334}
6335
6336// Explicit instantiation of a class template specialization
6337DeclResult
6338Sema::ActOnExplicitInstantiation(Scope *S,
6339                                 SourceLocation ExternLoc,
6340                                 SourceLocation TemplateLoc,
6341                                 unsigned TagSpec,
6342                                 SourceLocation KWLoc,
6343                                 const CXXScopeSpec &SS,
6344                                 TemplateTy TemplateD,
6345                                 SourceLocation TemplateNameLoc,
6346                                 SourceLocation LAngleLoc,
6347                                 ASTTemplateArgsPtr TemplateArgsIn,
6348                                 SourceLocation RAngleLoc,
6349                                 AttributeList *Attr) {
6350  // Find the class template we're specializing
6351  TemplateName Name = TemplateD.getAsVal<TemplateName>();
6352  TemplateDecl *TD = Name.getAsTemplateDecl();
6353  // Check that the specialization uses the same tag kind as the
6354  // original template.
6355  TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
6356  assert(Kind != TTK_Enum &&
6357         "Invalid enum tag in class template explicit instantiation!");
6358
6359  if (isa<TypeAliasTemplateDecl>(TD)) {
6360      Diag(KWLoc, diag::err_tag_reference_non_tag) << Kind;
6361      Diag(TD->getTemplatedDecl()->getLocation(),
6362           diag::note_previous_use);
6363    return true;
6364  }
6365
6366  ClassTemplateDecl *ClassTemplate = cast<ClassTemplateDecl>(TD);
6367
6368  if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
6369                                    Kind, /*isDefinition*/false, KWLoc,
6370                                    *ClassTemplate->getIdentifier())) {
6371    Diag(KWLoc, diag::err_use_with_wrong_tag)
6372      << ClassTemplate
6373      << FixItHint::CreateReplacement(KWLoc,
6374                            ClassTemplate->getTemplatedDecl()->getKindName());
6375    Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
6376         diag::note_previous_use);
6377    Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
6378  }
6379
6380  // C++0x [temp.explicit]p2:
6381  //   There are two forms of explicit instantiation: an explicit instantiation
6382  //   definition and an explicit instantiation declaration. An explicit
6383  //   instantiation declaration begins with the extern keyword. [...]
6384  TemplateSpecializationKind TSK
6385    = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
6386                           : TSK_ExplicitInstantiationDeclaration;
6387
6388  // Translate the parser's template argument list in our AST format.
6389  TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
6390  translateTemplateArguments(TemplateArgsIn, TemplateArgs);
6391
6392  // Check that the template argument list is well-formed for this
6393  // template.
6394  SmallVector<TemplateArgument, 4> Converted;
6395  if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
6396                                TemplateArgs, false, Converted))
6397    return true;
6398
6399  // Find the class template specialization declaration that
6400  // corresponds to these arguments.
6401  void *InsertPos = 0;
6402  ClassTemplateSpecializationDecl *PrevDecl
6403    = ClassTemplate->findSpecialization(Converted.data(),
6404                                        Converted.size(), InsertPos);
6405
6406  TemplateSpecializationKind PrevDecl_TSK
6407    = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared;
6408
6409  // C++0x [temp.explicit]p2:
6410  //   [...] An explicit instantiation shall appear in an enclosing
6411  //   namespace of its template. [...]
6412  //
6413  // This is C++ DR 275.
6414  if (CheckExplicitInstantiationScope(*this, ClassTemplate, TemplateNameLoc,
6415                                      SS.isSet()))
6416    return true;
6417
6418  ClassTemplateSpecializationDecl *Specialization = 0;
6419
6420  bool HasNoEffect = false;
6421  if (PrevDecl) {
6422    if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
6423                                               PrevDecl, PrevDecl_TSK,
6424                                            PrevDecl->getPointOfInstantiation(),
6425                                               HasNoEffect))
6426      return PrevDecl;
6427
6428    // Even though HasNoEffect == true means that this explicit instantiation
6429    // has no effect on semantics, we go on to put its syntax in the AST.
6430
6431    if (PrevDecl_TSK == TSK_ImplicitInstantiation ||
6432        PrevDecl_TSK == TSK_Undeclared) {
6433      // Since the only prior class template specialization with these
6434      // arguments was referenced but not declared, reuse that
6435      // declaration node as our own, updating the source location
6436      // for the template name to reflect our new declaration.
6437      // (Other source locations will be updated later.)
6438      Specialization = PrevDecl;
6439      Specialization->setLocation(TemplateNameLoc);
6440      PrevDecl = 0;
6441    }
6442  }
6443
6444  if (!Specialization) {
6445    // Create a new class template specialization declaration node for
6446    // this explicit specialization.
6447    Specialization
6448      = ClassTemplateSpecializationDecl::Create(Context, Kind,
6449                                             ClassTemplate->getDeclContext(),
6450                                                KWLoc, TemplateNameLoc,
6451                                                ClassTemplate,
6452                                                Converted.data(),
6453                                                Converted.size(),
6454                                                PrevDecl);
6455    SetNestedNameSpecifier(Specialization, SS);
6456
6457    if (!HasNoEffect && !PrevDecl) {
6458      // Insert the new specialization.
6459      ClassTemplate->AddSpecialization(Specialization, InsertPos);
6460    }
6461  }
6462
6463  // Build the fully-sugared type for this explicit instantiation as
6464  // the user wrote in the explicit instantiation itself. This means
6465  // that we'll pretty-print the type retrieved from the
6466  // specialization's declaration the way that the user actually wrote
6467  // the explicit instantiation, rather than formatting the name based
6468  // on the "canonical" representation used to store the template
6469  // arguments in the specialization.
6470  TypeSourceInfo *WrittenTy
6471    = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
6472                                                TemplateArgs,
6473                                  Context.getTypeDeclType(Specialization));
6474  Specialization->setTypeAsWritten(WrittenTy);
6475
6476  // Set source locations for keywords.
6477  Specialization->setExternLoc(ExternLoc);
6478  Specialization->setTemplateKeywordLoc(TemplateLoc);
6479  Specialization->setRBraceLoc(SourceLocation());
6480
6481  if (Attr)
6482    ProcessDeclAttributeList(S, Specialization, Attr);
6483
6484  // Add the explicit instantiation into its lexical context. However,
6485  // since explicit instantiations are never found by name lookup, we
6486  // just put it into the declaration context directly.
6487  Specialization->setLexicalDeclContext(CurContext);
6488  CurContext->addDecl(Specialization);
6489
6490  // Syntax is now OK, so return if it has no other effect on semantics.
6491  if (HasNoEffect) {
6492    // Set the template specialization kind.
6493    Specialization->setTemplateSpecializationKind(TSK);
6494    return Specialization;
6495  }
6496
6497  // C++ [temp.explicit]p3:
6498  //   A definition of a class template or class member template
6499  //   shall be in scope at the point of the explicit instantiation of
6500  //   the class template or class member template.
6501  //
6502  // This check comes when we actually try to perform the
6503  // instantiation.
6504  ClassTemplateSpecializationDecl *Def
6505    = cast_or_null<ClassTemplateSpecializationDecl>(
6506                                              Specialization->getDefinition());
6507  if (!Def)
6508    InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK);
6509  else if (TSK == TSK_ExplicitInstantiationDefinition) {
6510    MarkVTableUsed(TemplateNameLoc, Specialization, true);
6511    Specialization->setPointOfInstantiation(Def->getPointOfInstantiation());
6512  }
6513
6514  // Instantiate the members of this class template specialization.
6515  Def = cast_or_null<ClassTemplateSpecializationDecl>(
6516                                       Specialization->getDefinition());
6517  if (Def) {
6518    TemplateSpecializationKind Old_TSK = Def->getTemplateSpecializationKind();
6519
6520    // Fix a TSK_ExplicitInstantiationDeclaration followed by a
6521    // TSK_ExplicitInstantiationDefinition
6522    if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
6523        TSK == TSK_ExplicitInstantiationDefinition)
6524      Def->setTemplateSpecializationKind(TSK);
6525
6526    InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
6527  }
6528
6529  // Set the template specialization kind.
6530  Specialization->setTemplateSpecializationKind(TSK);
6531  return Specialization;
6532}
6533
6534// Explicit instantiation of a member class of a class template.
6535DeclResult
6536Sema::ActOnExplicitInstantiation(Scope *S,
6537                                 SourceLocation ExternLoc,
6538                                 SourceLocation TemplateLoc,
6539                                 unsigned TagSpec,
6540                                 SourceLocation KWLoc,
6541                                 CXXScopeSpec &SS,
6542                                 IdentifierInfo *Name,
6543                                 SourceLocation NameLoc,
6544                                 AttributeList *Attr) {
6545
6546  bool Owned = false;
6547  bool IsDependent = false;
6548  Decl *TagD = ActOnTag(S, TagSpec, Sema::TUK_Reference,
6549                        KWLoc, SS, Name, NameLoc, Attr, AS_none,
6550                        /*ModulePrivateLoc=*/SourceLocation(),
6551                        MultiTemplateParamsArg(), Owned, IsDependent,
6552                        SourceLocation(), false, TypeResult());
6553  assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
6554
6555  if (!TagD)
6556    return true;
6557
6558  TagDecl *Tag = cast<TagDecl>(TagD);
6559  assert(!Tag->isEnum() && "shouldn't see enumerations here");
6560
6561  if (Tag->isInvalidDecl())
6562    return true;
6563
6564  CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
6565  CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
6566  if (!Pattern) {
6567    Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
6568      << Context.getTypeDeclType(Record);
6569    Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
6570    return true;
6571  }
6572
6573  // C++0x [temp.explicit]p2:
6574  //   If the explicit instantiation is for a class or member class, the
6575  //   elaborated-type-specifier in the declaration shall include a
6576  //   simple-template-id.
6577  //
6578  // C++98 has the same restriction, just worded differently.
6579  if (!ScopeSpecifierHasTemplateId(SS))
6580    Diag(TemplateLoc, diag::ext_explicit_instantiation_without_qualified_id)
6581      << Record << SS.getRange();
6582
6583  // C++0x [temp.explicit]p2:
6584  //   There are two forms of explicit instantiation: an explicit instantiation
6585  //   definition and an explicit instantiation declaration. An explicit
6586  //   instantiation declaration begins with the extern keyword. [...]
6587  TemplateSpecializationKind TSK
6588    = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
6589                           : TSK_ExplicitInstantiationDeclaration;
6590
6591  // C++0x [temp.explicit]p2:
6592  //   [...] An explicit instantiation shall appear in an enclosing
6593  //   namespace of its template. [...]
6594  //
6595  // This is C++ DR 275.
6596  CheckExplicitInstantiationScope(*this, Record, NameLoc, true);
6597
6598  // Verify that it is okay to explicitly instantiate here.
6599  CXXRecordDecl *PrevDecl
6600    = cast_or_null<CXXRecordDecl>(Record->getPreviousDecl());
6601  if (!PrevDecl && Record->getDefinition())
6602    PrevDecl = Record;
6603  if (PrevDecl) {
6604    MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
6605    bool HasNoEffect = false;
6606    assert(MSInfo && "No member specialization information?");
6607    if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
6608                                               PrevDecl,
6609                                        MSInfo->getTemplateSpecializationKind(),
6610                                             MSInfo->getPointOfInstantiation(),
6611                                               HasNoEffect))
6612      return true;
6613    if (HasNoEffect)
6614      return TagD;
6615  }
6616
6617  CXXRecordDecl *RecordDef
6618    = cast_or_null<CXXRecordDecl>(Record->getDefinition());
6619  if (!RecordDef) {
6620    // C++ [temp.explicit]p3:
6621    //   A definition of a member class of a class template shall be in scope
6622    //   at the point of an explicit instantiation of the member class.
6623    CXXRecordDecl *Def
6624      = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
6625    if (!Def) {
6626      Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
6627        << 0 << Record->getDeclName() << Record->getDeclContext();
6628      Diag(Pattern->getLocation(), diag::note_forward_declaration)
6629        << Pattern;
6630      return true;
6631    } else {
6632      if (InstantiateClass(NameLoc, Record, Def,
6633                           getTemplateInstantiationArgs(Record),
6634                           TSK))
6635        return true;
6636
6637      RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition());
6638      if (!RecordDef)
6639        return true;
6640    }
6641  }
6642
6643  // Instantiate all of the members of the class.
6644  InstantiateClassMembers(NameLoc, RecordDef,
6645                          getTemplateInstantiationArgs(Record), TSK);
6646
6647  if (TSK == TSK_ExplicitInstantiationDefinition)
6648    MarkVTableUsed(NameLoc, RecordDef, true);
6649
6650  // FIXME: We don't have any representation for explicit instantiations of
6651  // member classes. Such a representation is not needed for compilation, but it
6652  // should be available for clients that want to see all of the declarations in
6653  // the source code.
6654  return TagD;
6655}
6656
6657DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
6658                                            SourceLocation ExternLoc,
6659                                            SourceLocation TemplateLoc,
6660                                            Declarator &D) {
6661  // Explicit instantiations always require a name.
6662  // TODO: check if/when DNInfo should replace Name.
6663  DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
6664  DeclarationName Name = NameInfo.getName();
6665  if (!Name) {
6666    if (!D.isInvalidType())
6667      Diag(D.getDeclSpec().getLocStart(),
6668           diag::err_explicit_instantiation_requires_name)
6669        << D.getDeclSpec().getSourceRange()
6670        << D.getSourceRange();
6671
6672    return true;
6673  }
6674
6675  // The scope passed in may not be a decl scope.  Zip up the scope tree until
6676  // we find one that is.
6677  while ((S->getFlags() & Scope::DeclScope) == 0 ||
6678         (S->getFlags() & Scope::TemplateParamScope) != 0)
6679    S = S->getParent();
6680
6681  // Determine the type of the declaration.
6682  TypeSourceInfo *T = GetTypeForDeclarator(D, S);
6683  QualType R = T->getType();
6684  if (R.isNull())
6685    return true;
6686
6687  // C++ [dcl.stc]p1:
6688  //   A storage-class-specifier shall not be specified in [...] an explicit
6689  //   instantiation (14.7.2) directive.
6690  if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
6691    Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
6692      << Name;
6693    return true;
6694  } else if (D.getDeclSpec().getStorageClassSpec()
6695                                                != DeclSpec::SCS_unspecified) {
6696    // Complain about then remove the storage class specifier.
6697    Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_storage_class)
6698      << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6699
6700    D.getMutableDeclSpec().ClearStorageClassSpecs();
6701  }
6702
6703  // C++0x [temp.explicit]p1:
6704  //   [...] An explicit instantiation of a function template shall not use the
6705  //   inline or constexpr specifiers.
6706  // Presumably, this also applies to member functions of class templates as
6707  // well.
6708  if (D.getDeclSpec().isInlineSpecified())
6709    Diag(D.getDeclSpec().getInlineSpecLoc(),
6710         getLangOpts().CPlusPlus11 ?
6711           diag::err_explicit_instantiation_inline :
6712           diag::warn_explicit_instantiation_inline_0x)
6713      << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
6714  if (D.getDeclSpec().isConstexprSpecified())
6715    // FIXME: Add a fix-it to remove the 'constexpr' and add a 'const' if one is
6716    // not already specified.
6717    Diag(D.getDeclSpec().getConstexprSpecLoc(),
6718         diag::err_explicit_instantiation_constexpr);
6719
6720  // C++0x [temp.explicit]p2:
6721  //   There are two forms of explicit instantiation: an explicit instantiation
6722  //   definition and an explicit instantiation declaration. An explicit
6723  //   instantiation declaration begins with the extern keyword. [...]
6724  TemplateSpecializationKind TSK
6725    = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
6726                           : TSK_ExplicitInstantiationDeclaration;
6727
6728  LookupResult Previous(*this, NameInfo, LookupOrdinaryName);
6729  LookupParsedName(Previous, S, &D.getCXXScopeSpec());
6730
6731  if (!R->isFunctionType()) {
6732    // C++ [temp.explicit]p1:
6733    //   A [...] static data member of a class template can be explicitly
6734    //   instantiated from the member definition associated with its class
6735    //   template.
6736    if (Previous.isAmbiguous())
6737      return true;
6738
6739    VarDecl *Prev = Previous.getAsSingle<VarDecl>();
6740    if (!Prev || !Prev->isStaticDataMember()) {
6741      // We expect to see a data data member here.
6742      Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
6743        << Name;
6744      for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
6745           P != PEnd; ++P)
6746        Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
6747      return true;
6748    }
6749
6750    if (!Prev->getInstantiatedFromStaticDataMember()) {
6751      // FIXME: Check for explicit specialization?
6752      Diag(D.getIdentifierLoc(),
6753           diag::err_explicit_instantiation_data_member_not_instantiated)
6754        << Prev;
6755      Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
6756      // FIXME: Can we provide a note showing where this was declared?
6757      return true;
6758    }
6759
6760    // C++0x [temp.explicit]p2:
6761    //   If the explicit instantiation is for a member function, a member class
6762    //   or a static data member of a class template specialization, the name of
6763    //   the class template specialization in the qualified-id for the member
6764    //   name shall be a simple-template-id.
6765    //
6766    // C++98 has the same restriction, just worded differently.
6767    if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
6768      Diag(D.getIdentifierLoc(),
6769           diag::ext_explicit_instantiation_without_qualified_id)
6770        << Prev << D.getCXXScopeSpec().getRange();
6771
6772    // Check the scope of this explicit instantiation.
6773    CheckExplicitInstantiationScope(*this, Prev, D.getIdentifierLoc(), true);
6774
6775    // Verify that it is okay to explicitly instantiate here.
6776    MemberSpecializationInfo *MSInfo = Prev->getMemberSpecializationInfo();
6777    assert(MSInfo && "Missing static data member specialization info?");
6778    bool HasNoEffect = false;
6779    if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
6780                                        MSInfo->getTemplateSpecializationKind(),
6781                                              MSInfo->getPointOfInstantiation(),
6782                                               HasNoEffect))
6783      return true;
6784    if (HasNoEffect)
6785      return (Decl*) 0;
6786
6787    // Instantiate static data member.
6788    Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
6789    if (TSK == TSK_ExplicitInstantiationDefinition)
6790      InstantiateStaticDataMemberDefinition(D.getIdentifierLoc(), Prev);
6791
6792    // FIXME: Create an ExplicitInstantiation node?
6793    return (Decl*) 0;
6794  }
6795
6796  // If the declarator is a template-id, translate the parser's template
6797  // argument list into our AST format.
6798  bool HasExplicitTemplateArgs = false;
6799  TemplateArgumentListInfo TemplateArgs;
6800  if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
6801    TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
6802    TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
6803    TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
6804    ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
6805                                       TemplateId->NumArgs);
6806    translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
6807    HasExplicitTemplateArgs = true;
6808  }
6809
6810  // C++ [temp.explicit]p1:
6811  //   A [...] function [...] can be explicitly instantiated from its template.
6812  //   A member function [...] of a class template can be explicitly
6813  //  instantiated from the member definition associated with its class
6814  //  template.
6815  UnresolvedSet<8> Matches;
6816  for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
6817       P != PEnd; ++P) {
6818    NamedDecl *Prev = *P;
6819    if (!HasExplicitTemplateArgs) {
6820      if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
6821        if (Context.hasSameUnqualifiedType(Method->getType(), R)) {
6822          Matches.clear();
6823
6824          Matches.addDecl(Method, P.getAccess());
6825          if (Method->getTemplateSpecializationKind() == TSK_Undeclared)
6826            break;
6827        }
6828      }
6829    }
6830
6831    FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
6832    if (!FunTmpl)
6833      continue;
6834
6835    TemplateDeductionInfo Info(D.getIdentifierLoc());
6836    FunctionDecl *Specialization = 0;
6837    if (TemplateDeductionResult TDK
6838          = DeduceTemplateArguments(FunTmpl,
6839                               (HasExplicitTemplateArgs ? &TemplateArgs : 0),
6840                                    R, Specialization, Info)) {
6841      // FIXME: Keep track of almost-matches?
6842      (void)TDK;
6843      continue;
6844    }
6845
6846    Matches.addDecl(Specialization, P.getAccess());
6847  }
6848
6849  // Find the most specialized function template specialization.
6850  UnresolvedSetIterator Result
6851    = getMostSpecialized(Matches.begin(), Matches.end(), TPOC_Other, 0,
6852                         D.getIdentifierLoc(),
6853                     PDiag(diag::err_explicit_instantiation_not_known) << Name,
6854                     PDiag(diag::err_explicit_instantiation_ambiguous) << Name,
6855                         PDiag(diag::note_explicit_instantiation_candidate));
6856
6857  if (Result == Matches.end())
6858    return true;
6859
6860  // Ignore access control bits, we don't need them for redeclaration checking.
6861  FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
6862
6863  if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
6864    Diag(D.getIdentifierLoc(),
6865         diag::err_explicit_instantiation_member_function_not_instantiated)
6866      << Specialization
6867      << (Specialization->getTemplateSpecializationKind() ==
6868          TSK_ExplicitSpecialization);
6869    Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
6870    return true;
6871  }
6872
6873  FunctionDecl *PrevDecl = Specialization->getPreviousDecl();
6874  if (!PrevDecl && Specialization->isThisDeclarationADefinition())
6875    PrevDecl = Specialization;
6876
6877  if (PrevDecl) {
6878    bool HasNoEffect = false;
6879    if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
6880                                               PrevDecl,
6881                                     PrevDecl->getTemplateSpecializationKind(),
6882                                          PrevDecl->getPointOfInstantiation(),
6883                                               HasNoEffect))
6884      return true;
6885
6886    // FIXME: We may still want to build some representation of this
6887    // explicit specialization.
6888    if (HasNoEffect)
6889      return (Decl*) 0;
6890  }
6891
6892  Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
6893  AttributeList *Attr = D.getDeclSpec().getAttributes().getList();
6894  if (Attr)
6895    ProcessDeclAttributeList(S, Specialization, Attr);
6896
6897  if (TSK == TSK_ExplicitInstantiationDefinition)
6898    InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization);
6899
6900  // C++0x [temp.explicit]p2:
6901  //   If the explicit instantiation is for a member function, a member class
6902  //   or a static data member of a class template specialization, the name of
6903  //   the class template specialization in the qualified-id for the member
6904  //   name shall be a simple-template-id.
6905  //
6906  // C++98 has the same restriction, just worded differently.
6907  FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
6908  if (D.getName().getKind() != UnqualifiedId::IK_TemplateId && !FunTmpl &&
6909      D.getCXXScopeSpec().isSet() &&
6910      !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
6911    Diag(D.getIdentifierLoc(),
6912         diag::ext_explicit_instantiation_without_qualified_id)
6913    << Specialization << D.getCXXScopeSpec().getRange();
6914
6915  CheckExplicitInstantiationScope(*this,
6916                   FunTmpl? (NamedDecl *)FunTmpl
6917                          : Specialization->getInstantiatedFromMemberFunction(),
6918                                  D.getIdentifierLoc(),
6919                                  D.getCXXScopeSpec().isSet());
6920
6921  // FIXME: Create some kind of ExplicitInstantiationDecl here.
6922  return (Decl*) 0;
6923}
6924
6925TypeResult
6926Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
6927                        const CXXScopeSpec &SS, IdentifierInfo *Name,
6928                        SourceLocation TagLoc, SourceLocation NameLoc) {
6929  // This has to hold, because SS is expected to be defined.
6930  assert(Name && "Expected a name in a dependent tag");
6931
6932  NestedNameSpecifier *NNS
6933    = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
6934  if (!NNS)
6935    return true;
6936
6937  TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
6938
6939  if (TUK == TUK_Declaration || TUK == TUK_Definition) {
6940    Diag(NameLoc, diag::err_dependent_tag_decl)
6941      << (TUK == TUK_Definition) << Kind << SS.getRange();
6942    return true;
6943  }
6944
6945  // Create the resulting type.
6946  ElaboratedTypeKeyword Kwd = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
6947  QualType Result = Context.getDependentNameType(Kwd, NNS, Name);
6948
6949  // Create type-source location information for this type.
6950  TypeLocBuilder TLB;
6951  DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(Result);
6952  TL.setElaboratedKeywordLoc(TagLoc);
6953  TL.setQualifierLoc(SS.getWithLocInContext(Context));
6954  TL.setNameLoc(NameLoc);
6955  return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
6956}
6957
6958TypeResult
6959Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
6960                        const CXXScopeSpec &SS, const IdentifierInfo &II,
6961                        SourceLocation IdLoc) {
6962  if (SS.isInvalid())
6963    return true;
6964
6965  if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
6966    Diag(TypenameLoc,
6967         getLangOpts().CPlusPlus11 ?
6968           diag::warn_cxx98_compat_typename_outside_of_template :
6969           diag::ext_typename_outside_of_template)
6970      << FixItHint::CreateRemoval(TypenameLoc);
6971
6972  NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
6973  QualType T = CheckTypenameType(TypenameLoc.isValid()? ETK_Typename : ETK_None,
6974                                 TypenameLoc, QualifierLoc, II, IdLoc);
6975  if (T.isNull())
6976    return true;
6977
6978  TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
6979  if (isa<DependentNameType>(T)) {
6980    DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
6981    TL.setElaboratedKeywordLoc(TypenameLoc);
6982    TL.setQualifierLoc(QualifierLoc);
6983    TL.setNameLoc(IdLoc);
6984  } else {
6985    ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
6986    TL.setElaboratedKeywordLoc(TypenameLoc);
6987    TL.setQualifierLoc(QualifierLoc);
6988    TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
6989  }
6990
6991  return CreateParsedType(T, TSI);
6992}
6993
6994TypeResult
6995Sema::ActOnTypenameType(Scope *S,
6996                        SourceLocation TypenameLoc,
6997                        const CXXScopeSpec &SS,
6998                        SourceLocation TemplateKWLoc,
6999                        TemplateTy TemplateIn,
7000                        SourceLocation TemplateNameLoc,
7001                        SourceLocation LAngleLoc,
7002                        ASTTemplateArgsPtr TemplateArgsIn,
7003                        SourceLocation RAngleLoc) {
7004  if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
7005    Diag(TypenameLoc,
7006         getLangOpts().CPlusPlus11 ?
7007           diag::warn_cxx98_compat_typename_outside_of_template :
7008           diag::ext_typename_outside_of_template)
7009      << FixItHint::CreateRemoval(TypenameLoc);
7010
7011  // Translate the parser's template argument list in our AST format.
7012  TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
7013  translateTemplateArguments(TemplateArgsIn, TemplateArgs);
7014
7015  TemplateName Template = TemplateIn.get();
7016  if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
7017    // Construct a dependent template specialization type.
7018    assert(DTN && "dependent template has non-dependent name?");
7019    assert(DTN->getQualifier()
7020           == static_cast<NestedNameSpecifier*>(SS.getScopeRep()));
7021    QualType T = Context.getDependentTemplateSpecializationType(ETK_Typename,
7022                                                          DTN->getQualifier(),
7023                                                          DTN->getIdentifier(),
7024                                                                TemplateArgs);
7025
7026    // Create source-location information for this type.
7027    TypeLocBuilder Builder;
7028    DependentTemplateSpecializationTypeLoc SpecTL
7029    = Builder.push<DependentTemplateSpecializationTypeLoc>(T);
7030    SpecTL.setElaboratedKeywordLoc(TypenameLoc);
7031    SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
7032    SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
7033    SpecTL.setTemplateNameLoc(TemplateNameLoc);
7034    SpecTL.setLAngleLoc(LAngleLoc);
7035    SpecTL.setRAngleLoc(RAngleLoc);
7036    for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
7037      SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
7038    return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
7039  }
7040
7041  QualType T = CheckTemplateIdType(Template, TemplateNameLoc, TemplateArgs);
7042  if (T.isNull())
7043    return true;
7044
7045  // Provide source-location information for the template specialization type.
7046  TypeLocBuilder Builder;
7047  TemplateSpecializationTypeLoc SpecTL
7048    = Builder.push<TemplateSpecializationTypeLoc>(T);
7049  SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
7050  SpecTL.setTemplateNameLoc(TemplateNameLoc);
7051  SpecTL.setLAngleLoc(LAngleLoc);
7052  SpecTL.setRAngleLoc(RAngleLoc);
7053  for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
7054    SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
7055
7056  T = Context.getElaboratedType(ETK_Typename, SS.getScopeRep(), T);
7057  ElaboratedTypeLoc TL = Builder.push<ElaboratedTypeLoc>(T);
7058  TL.setElaboratedKeywordLoc(TypenameLoc);
7059  TL.setQualifierLoc(SS.getWithLocInContext(Context));
7060
7061  TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T);
7062  return CreateParsedType(T, TSI);
7063}
7064
7065
7066/// Determine whether this failed name lookup should be treated as being
7067/// disabled by a usage of std::enable_if.
7068static bool isEnableIf(NestedNameSpecifierLoc NNS, const IdentifierInfo &II,
7069                       SourceRange &CondRange) {
7070  // We must be looking for a ::type...
7071  if (!II.isStr("type"))
7072    return false;
7073
7074  // ... within an explicitly-written template specialization...
7075  if (!NNS || !NNS.getNestedNameSpecifier()->getAsType())
7076    return false;
7077  TypeLoc EnableIfTy = NNS.getTypeLoc();
7078  TemplateSpecializationTypeLoc EnableIfTSTLoc =
7079      EnableIfTy.getAs<TemplateSpecializationTypeLoc>();
7080  if (!EnableIfTSTLoc || EnableIfTSTLoc.getNumArgs() == 0)
7081    return false;
7082  const TemplateSpecializationType *EnableIfTST =
7083    cast<TemplateSpecializationType>(EnableIfTSTLoc.getTypePtr());
7084
7085  // ... which names a complete class template declaration...
7086  const TemplateDecl *EnableIfDecl =
7087    EnableIfTST->getTemplateName().getAsTemplateDecl();
7088  if (!EnableIfDecl || EnableIfTST->isIncompleteType())
7089    return false;
7090
7091  // ... called "enable_if".
7092  const IdentifierInfo *EnableIfII =
7093    EnableIfDecl->getDeclName().getAsIdentifierInfo();
7094  if (!EnableIfII || !EnableIfII->isStr("enable_if"))
7095    return false;
7096
7097  // Assume the first template argument is the condition.
7098  CondRange = EnableIfTSTLoc.getArgLoc(0).getSourceRange();
7099  return true;
7100}
7101
7102/// \brief Build the type that describes a C++ typename specifier,
7103/// e.g., "typename T::type".
7104QualType
7105Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword,
7106                        SourceLocation KeywordLoc,
7107                        NestedNameSpecifierLoc QualifierLoc,
7108                        const IdentifierInfo &II,
7109                        SourceLocation IILoc) {
7110  CXXScopeSpec SS;
7111  SS.Adopt(QualifierLoc);
7112
7113  DeclContext *Ctx = computeDeclContext(SS);
7114  if (!Ctx) {
7115    // If the nested-name-specifier is dependent and couldn't be
7116    // resolved to a type, build a typename type.
7117    assert(QualifierLoc.getNestedNameSpecifier()->isDependent());
7118    return Context.getDependentNameType(Keyword,
7119                                        QualifierLoc.getNestedNameSpecifier(),
7120                                        &II);
7121  }
7122
7123  // If the nested-name-specifier refers to the current instantiation,
7124  // the "typename" keyword itself is superfluous. In C++03, the
7125  // program is actually ill-formed. However, DR 382 (in C++0x CD1)
7126  // allows such extraneous "typename" keywords, and we retroactively
7127  // apply this DR to C++03 code with only a warning. In any case we continue.
7128
7129  if (RequireCompleteDeclContext(SS, Ctx))
7130    return QualType();
7131
7132  DeclarationName Name(&II);
7133  LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
7134  LookupQualifiedName(Result, Ctx);
7135  unsigned DiagID = 0;
7136  Decl *Referenced = 0;
7137  switch (Result.getResultKind()) {
7138  case LookupResult::NotFound: {
7139    // If we're looking up 'type' within a template named 'enable_if', produce
7140    // a more specific diagnostic.
7141    SourceRange CondRange;
7142    if (isEnableIf(QualifierLoc, II, CondRange)) {
7143      Diag(CondRange.getBegin(), diag::err_typename_nested_not_found_enable_if)
7144        << Ctx << CondRange;
7145      return QualType();
7146    }
7147
7148    DiagID = diag::err_typename_nested_not_found;
7149    break;
7150  }
7151
7152  case LookupResult::FoundUnresolvedValue: {
7153    // We found a using declaration that is a value. Most likely, the using
7154    // declaration itself is meant to have the 'typename' keyword.
7155    SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
7156                          IILoc);
7157    Diag(IILoc, diag::err_typename_refers_to_using_value_decl)
7158      << Name << Ctx << FullRange;
7159    if (UnresolvedUsingValueDecl *Using
7160          = dyn_cast<UnresolvedUsingValueDecl>(Result.getRepresentativeDecl())){
7161      SourceLocation Loc = Using->getQualifierLoc().getBeginLoc();
7162      Diag(Loc, diag::note_using_value_decl_missing_typename)
7163        << FixItHint::CreateInsertion(Loc, "typename ");
7164    }
7165  }
7166  // Fall through to create a dependent typename type, from which we can recover
7167  // better.
7168
7169  case LookupResult::NotFoundInCurrentInstantiation:
7170    // Okay, it's a member of an unknown instantiation.
7171    return Context.getDependentNameType(Keyword,
7172                                        QualifierLoc.getNestedNameSpecifier(),
7173                                        &II);
7174
7175  case LookupResult::Found:
7176    if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
7177      // We found a type. Build an ElaboratedType, since the
7178      // typename-specifier was just sugar.
7179      return Context.getElaboratedType(ETK_Typename,
7180                                       QualifierLoc.getNestedNameSpecifier(),
7181                                       Context.getTypeDeclType(Type));
7182    }
7183
7184    DiagID = diag::err_typename_nested_not_type;
7185    Referenced = Result.getFoundDecl();
7186    break;
7187
7188  case LookupResult::FoundOverloaded:
7189    DiagID = diag::err_typename_nested_not_type;
7190    Referenced = *Result.begin();
7191    break;
7192
7193  case LookupResult::Ambiguous:
7194    return QualType();
7195  }
7196
7197  // If we get here, it's because name lookup did not find a
7198  // type. Emit an appropriate diagnostic and return an error.
7199  SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
7200                        IILoc);
7201  Diag(IILoc, DiagID) << FullRange << Name << Ctx;
7202  if (Referenced)
7203    Diag(Referenced->getLocation(), diag::note_typename_refers_here)
7204      << Name;
7205  return QualType();
7206}
7207
7208namespace {
7209  // See Sema::RebuildTypeInCurrentInstantiation
7210  class CurrentInstantiationRebuilder
7211    : public TreeTransform<CurrentInstantiationRebuilder> {
7212    SourceLocation Loc;
7213    DeclarationName Entity;
7214
7215  public:
7216    typedef TreeTransform<CurrentInstantiationRebuilder> inherited;
7217
7218    CurrentInstantiationRebuilder(Sema &SemaRef,
7219                                  SourceLocation Loc,
7220                                  DeclarationName Entity)
7221    : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
7222      Loc(Loc), Entity(Entity) { }
7223
7224    /// \brief Determine whether the given type \p T has already been
7225    /// transformed.
7226    ///
7227    /// For the purposes of type reconstruction, a type has already been
7228    /// transformed if it is NULL or if it is not dependent.
7229    bool AlreadyTransformed(QualType T) {
7230      return T.isNull() || !T->isDependentType();
7231    }
7232
7233    /// \brief Returns the location of the entity whose type is being
7234    /// rebuilt.
7235    SourceLocation getBaseLocation() { return Loc; }
7236
7237    /// \brief Returns the name of the entity whose type is being rebuilt.
7238    DeclarationName getBaseEntity() { return Entity; }
7239
7240    /// \brief Sets the "base" location and entity when that
7241    /// information is known based on another transformation.
7242    void setBase(SourceLocation Loc, DeclarationName Entity) {
7243      this->Loc = Loc;
7244      this->Entity = Entity;
7245    }
7246
7247    ExprResult TransformLambdaExpr(LambdaExpr *E) {
7248      // Lambdas never need to be transformed.
7249      return E;
7250    }
7251  };
7252}
7253
7254/// \brief Rebuilds a type within the context of the current instantiation.
7255///
7256/// The type \p T is part of the type of an out-of-line member definition of
7257/// a class template (or class template partial specialization) that was parsed
7258/// and constructed before we entered the scope of the class template (or
7259/// partial specialization thereof). This routine will rebuild that type now
7260/// that we have entered the declarator's scope, which may produce different
7261/// canonical types, e.g.,
7262///
7263/// \code
7264/// template<typename T>
7265/// struct X {
7266///   typedef T* pointer;
7267///   pointer data();
7268/// };
7269///
7270/// template<typename T>
7271/// typename X<T>::pointer X<T>::data() { ... }
7272/// \endcode
7273///
7274/// Here, the type "typename X<T>::pointer" will be created as a DependentNameType,
7275/// since we do not know that we can look into X<T> when we parsed the type.
7276/// This function will rebuild the type, performing the lookup of "pointer"
7277/// in X<T> and returning an ElaboratedType whose canonical type is the same
7278/// as the canonical type of T*, allowing the return types of the out-of-line
7279/// definition and the declaration to match.
7280TypeSourceInfo *Sema::RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
7281                                                        SourceLocation Loc,
7282                                                        DeclarationName Name) {
7283  if (!T || !T->getType()->isDependentType())
7284    return T;
7285
7286  CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
7287  return Rebuilder.TransformType(T);
7288}
7289
7290ExprResult Sema::RebuildExprInCurrentInstantiation(Expr *E) {
7291  CurrentInstantiationRebuilder Rebuilder(*this, E->getExprLoc(),
7292                                          DeclarationName());
7293  return Rebuilder.TransformExpr(E);
7294}
7295
7296bool Sema::RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS) {
7297  if (SS.isInvalid())
7298    return true;
7299
7300  NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
7301  CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
7302                                          DeclarationName());
7303  NestedNameSpecifierLoc Rebuilt
7304    = Rebuilder.TransformNestedNameSpecifierLoc(QualifierLoc);
7305  if (!Rebuilt)
7306    return true;
7307
7308  SS.Adopt(Rebuilt);
7309  return false;
7310}
7311
7312/// \brief Rebuild the template parameters now that we know we're in a current
7313/// instantiation.
7314bool Sema::RebuildTemplateParamsInCurrentInstantiation(
7315                                               TemplateParameterList *Params) {
7316  for (unsigned I = 0, N = Params->size(); I != N; ++I) {
7317    Decl *Param = Params->getParam(I);
7318
7319    // There is nothing to rebuild in a type parameter.
7320    if (isa<TemplateTypeParmDecl>(Param))
7321      continue;
7322
7323    // Rebuild the template parameter list of a template template parameter.
7324    if (TemplateTemplateParmDecl *TTP
7325        = dyn_cast<TemplateTemplateParmDecl>(Param)) {
7326      if (RebuildTemplateParamsInCurrentInstantiation(
7327            TTP->getTemplateParameters()))
7328        return true;
7329
7330      continue;
7331    }
7332
7333    // Rebuild the type of a non-type template parameter.
7334    NonTypeTemplateParmDecl *NTTP = cast<NonTypeTemplateParmDecl>(Param);
7335    TypeSourceInfo *NewTSI
7336      = RebuildTypeInCurrentInstantiation(NTTP->getTypeSourceInfo(),
7337                                          NTTP->getLocation(),
7338                                          NTTP->getDeclName());
7339    if (!NewTSI)
7340      return true;
7341
7342    if (NewTSI != NTTP->getTypeSourceInfo()) {
7343      NTTP->setTypeSourceInfo(NewTSI);
7344      NTTP->setType(NewTSI->getType());
7345    }
7346  }
7347
7348  return false;
7349}
7350
7351/// \brief Produces a formatted string that describes the binding of
7352/// template parameters to template arguments.
7353std::string
7354Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
7355                                      const TemplateArgumentList &Args) {
7356  return getTemplateArgumentBindingsText(Params, Args.data(), Args.size());
7357}
7358
7359std::string
7360Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
7361                                      const TemplateArgument *Args,
7362                                      unsigned NumArgs) {
7363  SmallString<128> Str;
7364  llvm::raw_svector_ostream Out(Str);
7365
7366  if (!Params || Params->size() == 0 || NumArgs == 0)
7367    return std::string();
7368
7369  for (unsigned I = 0, N = Params->size(); I != N; ++I) {
7370    if (I >= NumArgs)
7371      break;
7372
7373    if (I == 0)
7374      Out << "[with ";
7375    else
7376      Out << ", ";
7377
7378    if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
7379      Out << Id->getName();
7380    } else {
7381      Out << '$' << I;
7382    }
7383
7384    Out << " = ";
7385    Args[I].print(getPrintingPolicy(), Out);
7386  }
7387
7388  Out << ']';
7389  return Out.str();
7390}
7391
7392void Sema::MarkAsLateParsedTemplate(FunctionDecl *FD, bool Flag) {
7393  if (!FD)
7394    return;
7395  FD->setLateTemplateParsed(Flag);
7396}
7397
7398bool Sema::IsInsideALocalClassWithinATemplateFunction() {
7399  DeclContext *DC = CurContext;
7400
7401  while (DC) {
7402    if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(CurContext)) {
7403      const FunctionDecl *FD = RD->isLocalClass();
7404      return (FD && FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate);
7405    } else if (DC->isTranslationUnit() || DC->isNamespace())
7406      return false;
7407
7408    DC = DC->getParent();
7409  }
7410  return false;
7411}
7412