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