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