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