clang API Documentation

SemaTemplate.cpp
Go to the documentation of this file.
00001 //===------- SemaTemplate.cpp - Semantic Analysis for C++ Templates -------===/
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //===----------------------------------------------------------------------===/
00008 //
00009 //  This file implements semantic analysis for C++ templates.
00010 //===----------------------------------------------------------------------===/
00011 
00012 #include "TreeTransform.h"
00013 #include "clang/AST/ASTConsumer.h"
00014 #include "clang/AST/ASTContext.h"
00015 #include "clang/AST/DeclFriend.h"
00016 #include "clang/AST/DeclTemplate.h"
00017 #include "clang/AST/Expr.h"
00018 #include "clang/AST/ExprCXX.h"
00019 #include "clang/AST/RecursiveASTVisitor.h"
00020 #include "clang/AST/TypeVisitor.h"
00021 #include "clang/Basic/LangOptions.h"
00022 #include "clang/Basic/PartialDiagnostic.h"
00023 #include "clang/Basic/TargetInfo.h"
00024 #include "clang/Sema/DeclSpec.h"
00025 #include "clang/Sema/Lookup.h"
00026 #include "clang/Sema/ParsedTemplate.h"
00027 #include "clang/Sema/Scope.h"
00028 #include "clang/Sema/SemaInternal.h"
00029 #include "clang/Sema/Template.h"
00030 #include "clang/Sema/TemplateDeduction.h"
00031 #include "llvm/ADT/SmallBitVector.h"
00032 #include "llvm/ADT/SmallString.h"
00033 #include "llvm/ADT/StringExtras.h"
00034 using namespace clang;
00035 using namespace sema;
00036 
00037 // Exported for use by Parser.
00038 SourceRange
00039 clang::getTemplateParamsRange(TemplateParameterList const * const *Ps,
00040                               unsigned N) {
00041   if (!N) return SourceRange();
00042   return SourceRange(Ps[0]->getTemplateLoc(), Ps[N-1]->getRAngleLoc());
00043 }
00044 
00045 /// \brief Determine whether the declaration found is acceptable as the name
00046 /// of a template and, if so, return that template declaration. Otherwise,
00047 /// returns NULL.
00048 static NamedDecl *isAcceptableTemplateName(ASTContext &Context,
00049                                            NamedDecl *Orig,
00050                                            bool AllowFunctionTemplates) {
00051   NamedDecl *D = Orig->getUnderlyingDecl();
00052 
00053   if (isa<TemplateDecl>(D)) {
00054     if (!AllowFunctionTemplates && isa<FunctionTemplateDecl>(D))
00055       return nullptr;
00056 
00057     return Orig;
00058   }
00059 
00060   if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
00061     // C++ [temp.local]p1:
00062     //   Like normal (non-template) classes, class templates have an
00063     //   injected-class-name (Clause 9). The injected-class-name
00064     //   can be used with or without a template-argument-list. When
00065     //   it is used without a template-argument-list, it is
00066     //   equivalent to the injected-class-name followed by the
00067     //   template-parameters of the class template enclosed in
00068     //   <>. When it is used with a template-argument-list, it
00069     //   refers to the specified class template specialization,
00070     //   which could be the current specialization or another
00071     //   specialization.
00072     if (Record->isInjectedClassName()) {
00073       Record = cast<CXXRecordDecl>(Record->getDeclContext());
00074       if (Record->getDescribedClassTemplate())
00075         return Record->getDescribedClassTemplate();
00076 
00077       if (ClassTemplateSpecializationDecl *Spec
00078             = dyn_cast<ClassTemplateSpecializationDecl>(Record))
00079         return Spec->getSpecializedTemplate();
00080     }
00081 
00082     return nullptr;
00083   }
00084 
00085   return nullptr;
00086 }
00087 
00088 void Sema::FilterAcceptableTemplateNames(LookupResult &R, 
00089                                          bool AllowFunctionTemplates) {
00090   // The set of class templates we've already seen.
00091   llvm::SmallPtrSet<ClassTemplateDecl *, 8> ClassTemplates;
00092   LookupResult::Filter filter = R.makeFilter();
00093   while (filter.hasNext()) {
00094     NamedDecl *Orig = filter.next();
00095     NamedDecl *Repl = isAcceptableTemplateName(Context, Orig, 
00096                                                AllowFunctionTemplates);
00097     if (!Repl)
00098       filter.erase();
00099     else if (Repl != Orig) {
00100 
00101       // C++ [temp.local]p3:
00102       //   A lookup that finds an injected-class-name (10.2) can result in an
00103       //   ambiguity in certain cases (for example, if it is found in more than
00104       //   one base class). If all of the injected-class-names that are found
00105       //   refer to specializations of the same class template, and if the name
00106       //   is used as a template-name, the reference refers to the class
00107       //   template itself and not a specialization thereof, and is not
00108       //   ambiguous.
00109       if (ClassTemplateDecl *ClassTmpl = dyn_cast<ClassTemplateDecl>(Repl))
00110         if (!ClassTemplates.insert(ClassTmpl)) {
00111           filter.erase();
00112           continue;
00113         }
00114 
00115       // FIXME: we promote access to public here as a workaround to
00116       // the fact that LookupResult doesn't let us remember that we
00117       // found this template through a particular injected class name,
00118       // which means we end up doing nasty things to the invariants.
00119       // Pretending that access is public is *much* safer.
00120       filter.replace(Repl, AS_public);
00121     }
00122   }
00123   filter.done();
00124 }
00125 
00126 bool Sema::hasAnyAcceptableTemplateNames(LookupResult &R,
00127                                          bool AllowFunctionTemplates) {
00128   for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I)
00129     if (isAcceptableTemplateName(Context, *I, AllowFunctionTemplates))
00130       return true;
00131   
00132   return false;
00133 }
00134 
00135 TemplateNameKind Sema::isTemplateName(Scope *S,
00136                                       CXXScopeSpec &SS,
00137                                       bool hasTemplateKeyword,
00138                                       UnqualifiedId &Name,
00139                                       ParsedType ObjectTypePtr,
00140                                       bool EnteringContext,
00141                                       TemplateTy &TemplateResult,
00142                                       bool &MemberOfUnknownSpecialization) {
00143   assert(getLangOpts().CPlusPlus && "No template names in C!");
00144 
00145   DeclarationName TName;
00146   MemberOfUnknownSpecialization = false;
00147 
00148   switch (Name.getKind()) {
00149   case UnqualifiedId::IK_Identifier:
00150     TName = DeclarationName(Name.Identifier);
00151     break;
00152 
00153   case UnqualifiedId::IK_OperatorFunctionId:
00154     TName = Context.DeclarationNames.getCXXOperatorName(
00155                                               Name.OperatorFunctionId.Operator);
00156     break;
00157 
00158   case UnqualifiedId::IK_LiteralOperatorId:
00159     TName = Context.DeclarationNames.getCXXLiteralOperatorName(Name.Identifier);
00160     break;
00161 
00162   default:
00163     return TNK_Non_template;
00164   }
00165 
00166   QualType ObjectType = ObjectTypePtr.get();
00167 
00168   LookupResult R(*this, TName, Name.getLocStart(), LookupOrdinaryName);
00169   LookupTemplateName(R, S, SS, ObjectType, EnteringContext,
00170                      MemberOfUnknownSpecialization);
00171   if (R.empty()) return TNK_Non_template;
00172   if (R.isAmbiguous()) {
00173     // Suppress diagnostics;  we'll redo this lookup later.
00174     R.suppressDiagnostics();
00175 
00176     // FIXME: we might have ambiguous templates, in which case we
00177     // should at least parse them properly!
00178     return TNK_Non_template;
00179   }
00180 
00181   TemplateName Template;
00182   TemplateNameKind TemplateKind;
00183 
00184   unsigned ResultCount = R.end() - R.begin();
00185   if (ResultCount > 1) {
00186     // We assume that we'll preserve the qualifier from a function
00187     // template name in other ways.
00188     Template = Context.getOverloadedTemplateName(R.begin(), R.end());
00189     TemplateKind = TNK_Function_template;
00190 
00191     // We'll do this lookup again later.
00192     R.suppressDiagnostics();
00193   } else {
00194     TemplateDecl *TD = cast<TemplateDecl>((*R.begin())->getUnderlyingDecl());
00195 
00196     if (SS.isSet() && !SS.isInvalid()) {
00197       NestedNameSpecifier *Qualifier = SS.getScopeRep();
00198       Template = Context.getQualifiedTemplateName(Qualifier,
00199                                                   hasTemplateKeyword, TD);
00200     } else {
00201       Template = TemplateName(TD);
00202     }
00203 
00204     if (isa<FunctionTemplateDecl>(TD)) {
00205       TemplateKind = TNK_Function_template;
00206 
00207       // We'll do this lookup again later.
00208       R.suppressDiagnostics();
00209     } else {
00210       assert(isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD) ||
00211              isa<TypeAliasTemplateDecl>(TD) || isa<VarTemplateDecl>(TD));
00212       TemplateKind =
00213           isa<VarTemplateDecl>(TD) ? TNK_Var_template : TNK_Type_template;
00214     }
00215   }
00216 
00217   TemplateResult = TemplateTy::make(Template);
00218   return TemplateKind;
00219 }
00220 
00221 bool Sema::DiagnoseUnknownTemplateName(const IdentifierInfo &II,
00222                                        SourceLocation IILoc,
00223                                        Scope *S,
00224                                        const CXXScopeSpec *SS,
00225                                        TemplateTy &SuggestedTemplate,
00226                                        TemplateNameKind &SuggestedKind) {
00227   // We can't recover unless there's a dependent scope specifier preceding the
00228   // template name.
00229   // FIXME: Typo correction?
00230   if (!SS || !SS->isSet() || !isDependentScopeSpecifier(*SS) ||
00231       computeDeclContext(*SS))
00232     return false;
00233 
00234   // The code is missing a 'template' keyword prior to the dependent template
00235   // name.
00236   NestedNameSpecifier *Qualifier = (NestedNameSpecifier*)SS->getScopeRep();
00237   Diag(IILoc, diag::err_template_kw_missing)
00238     << Qualifier << II.getName()
00239     << FixItHint::CreateInsertion(IILoc, "template ");
00240   SuggestedTemplate
00241     = TemplateTy::make(Context.getDependentTemplateName(Qualifier, &II));
00242   SuggestedKind = TNK_Dependent_template_name;
00243   return true;
00244 }
00245 
00246 void Sema::LookupTemplateName(LookupResult &Found,
00247                               Scope *S, CXXScopeSpec &SS,
00248                               QualType ObjectType,
00249                               bool EnteringContext,
00250                               bool &MemberOfUnknownSpecialization) {
00251   // Determine where to perform name lookup
00252   MemberOfUnknownSpecialization = false;
00253   DeclContext *LookupCtx = nullptr;
00254   bool isDependent = false;
00255   if (!ObjectType.isNull()) {
00256     // This nested-name-specifier occurs in a member access expression, e.g.,
00257     // x->B::f, and we are looking into the type of the object.
00258     assert(!SS.isSet() && "ObjectType and scope specifier cannot coexist");
00259     LookupCtx = computeDeclContext(ObjectType);
00260     isDependent = ObjectType->isDependentType();
00261     assert((isDependent || !ObjectType->isIncompleteType() ||
00262             ObjectType->castAs<TagType>()->isBeingDefined()) &&
00263            "Caller should have completed object type");
00264     
00265     // Template names cannot appear inside an Objective-C class or object type.
00266     if (ObjectType->isObjCObjectOrInterfaceType()) {
00267       Found.clear();
00268       return;
00269     }
00270   } else if (SS.isSet()) {
00271     // This nested-name-specifier occurs after another nested-name-specifier,
00272     // so long into the context associated with the prior nested-name-specifier.
00273     LookupCtx = computeDeclContext(SS, EnteringContext);
00274     isDependent = isDependentScopeSpecifier(SS);
00275 
00276     // The declaration context must be complete.
00277     if (LookupCtx && RequireCompleteDeclContext(SS, LookupCtx))
00278       return;
00279   }
00280 
00281   bool ObjectTypeSearchedInScope = false;
00282   bool AllowFunctionTemplatesInLookup = true;
00283   if (LookupCtx) {
00284     // Perform "qualified" name lookup into the declaration context we
00285     // computed, which is either the type of the base of a member access
00286     // expression or the declaration context associated with a prior
00287     // nested-name-specifier.
00288     LookupQualifiedName(Found, LookupCtx);
00289     if (!ObjectType.isNull() && Found.empty()) {
00290       // C++ [basic.lookup.classref]p1:
00291       //   In a class member access expression (5.2.5), if the . or -> token is
00292       //   immediately followed by an identifier followed by a <, the
00293       //   identifier must be looked up to determine whether the < is the
00294       //   beginning of a template argument list (14.2) or a less-than operator.
00295       //   The identifier is first looked up in the class of the object
00296       //   expression. If the identifier is not found, it is then looked up in
00297       //   the context of the entire postfix-expression and shall name a class
00298       //   or function template.
00299       if (S) LookupName(Found, S);
00300       ObjectTypeSearchedInScope = true;
00301       AllowFunctionTemplatesInLookup = false;
00302     }
00303   } else if (isDependent && (!S || ObjectType.isNull())) {
00304     // We cannot look into a dependent object type or nested nme
00305     // specifier.
00306     MemberOfUnknownSpecialization = true;
00307     return;
00308   } else {
00309     // Perform unqualified name lookup in the current scope.
00310     LookupName(Found, S);
00311     
00312     if (!ObjectType.isNull())
00313       AllowFunctionTemplatesInLookup = false;
00314   }
00315 
00316   if (Found.empty() && !isDependent) {
00317     // If we did not find any names, attempt to correct any typos.
00318     DeclarationName Name = Found.getLookupName();
00319     Found.clear();
00320     // Simple filter callback that, for keywords, only accepts the C++ *_cast
00321     auto FilterCCC = llvm::make_unique<CorrectionCandidateCallback>();
00322     FilterCCC->WantTypeSpecifiers = false;
00323     FilterCCC->WantExpressionKeywords = false;
00324     FilterCCC->WantRemainingKeywords = false;
00325     FilterCCC->WantCXXNamedCasts = true;
00326     if (TypoCorrection Corrected = CorrectTypo(
00327             Found.getLookupNameInfo(), Found.getLookupKind(), S, &SS,
00328             std::move(FilterCCC), CTK_ErrorRecovery, LookupCtx)) {
00329       Found.setLookupName(Corrected.getCorrection());
00330       if (Corrected.getCorrectionDecl())
00331         Found.addDecl(Corrected.getCorrectionDecl());
00332       FilterAcceptableTemplateNames(Found);
00333       if (!Found.empty()) {
00334         if (LookupCtx) {
00335           std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
00336           bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
00337                                   Name.getAsString() == CorrectedStr;
00338           diagnoseTypo(Corrected, PDiag(diag::err_no_member_template_suggest)
00339                                     << Name << LookupCtx << DroppedSpecifier
00340                                     << SS.getRange());
00341         } else {
00342           diagnoseTypo(Corrected, PDiag(diag::err_no_template_suggest) << Name);
00343         }
00344       }
00345     } else {
00346       Found.setLookupName(Name);
00347     }
00348   }
00349 
00350   FilterAcceptableTemplateNames(Found, AllowFunctionTemplatesInLookup);
00351   if (Found.empty()) {
00352     if (isDependent)
00353       MemberOfUnknownSpecialization = true;
00354     return;
00355   }
00356 
00357   if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope &&
00358       !getLangOpts().CPlusPlus11) {
00359     // C++03 [basic.lookup.classref]p1:
00360     //   [...] If the lookup in the class of the object expression finds a
00361     //   template, the name is also looked up in the context of the entire
00362     //   postfix-expression and [...]
00363     //
00364     // Note: C++11 does not perform this second lookup.
00365     LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(),
00366                             LookupOrdinaryName);
00367     LookupName(FoundOuter, S);
00368     FilterAcceptableTemplateNames(FoundOuter, /*AllowFunctionTemplates=*/false);
00369 
00370     if (FoundOuter.empty()) {
00371       //   - if the name is not found, the name found in the class of the
00372       //     object expression is used, otherwise
00373     } else if (!FoundOuter.getAsSingle<ClassTemplateDecl>() ||
00374                FoundOuter.isAmbiguous()) {
00375       //   - if the name is found in the context of the entire
00376       //     postfix-expression and does not name a class template, the name
00377       //     found in the class of the object expression is used, otherwise
00378       FoundOuter.clear();
00379     } else if (!Found.isSuppressingDiagnostics()) {
00380       //   - if the name found is a class template, it must refer to the same
00381       //     entity as the one found in the class of the object expression,
00382       //     otherwise the program is ill-formed.
00383       if (!Found.isSingleResult() ||
00384           Found.getFoundDecl()->getCanonicalDecl()
00385             != FoundOuter.getFoundDecl()->getCanonicalDecl()) {
00386         Diag(Found.getNameLoc(),
00387              diag::ext_nested_name_member_ref_lookup_ambiguous)
00388           << Found.getLookupName()
00389           << ObjectType;
00390         Diag(Found.getRepresentativeDecl()->getLocation(),
00391              diag::note_ambig_member_ref_object_type)
00392           << ObjectType;
00393         Diag(FoundOuter.getFoundDecl()->getLocation(),
00394              diag::note_ambig_member_ref_scope);
00395 
00396         // Recover by taking the template that we found in the object
00397         // expression's type.
00398       }
00399     }
00400   }
00401 }
00402 
00403 /// ActOnDependentIdExpression - Handle a dependent id-expression that
00404 /// was just parsed.  This is only possible with an explicit scope
00405 /// specifier naming a dependent type.
00406 ExprResult
00407 Sema::ActOnDependentIdExpression(const CXXScopeSpec &SS,
00408                                  SourceLocation TemplateKWLoc,
00409                                  const DeclarationNameInfo &NameInfo,
00410                                  bool isAddressOfOperand,
00411                            const TemplateArgumentListInfo *TemplateArgs) {
00412   DeclContext *DC = getFunctionLevelDeclContext();
00413 
00414   if (!isAddressOfOperand &&
00415       isa<CXXMethodDecl>(DC) &&
00416       cast<CXXMethodDecl>(DC)->isInstance()) {
00417     QualType ThisType = cast<CXXMethodDecl>(DC)->getThisType(Context);
00418 
00419     // Since the 'this' expression is synthesized, we don't need to
00420     // perform the double-lookup check.
00421     NamedDecl *FirstQualifierInScope = nullptr;
00422 
00423     return CXXDependentScopeMemberExpr::Create(
00424         Context, /*This*/ nullptr, ThisType, /*IsArrow*/ true,
00425         /*Op*/ SourceLocation(), SS.getWithLocInContext(Context), TemplateKWLoc,
00426         FirstQualifierInScope, NameInfo, TemplateArgs);
00427   }
00428 
00429   return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
00430 }
00431 
00432 ExprResult
00433 Sema::BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
00434                                 SourceLocation TemplateKWLoc,
00435                                 const DeclarationNameInfo &NameInfo,
00436                                 const TemplateArgumentListInfo *TemplateArgs) {
00437   return DependentScopeDeclRefExpr::Create(
00438       Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
00439       TemplateArgs);
00440 }
00441 
00442 /// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
00443 /// that the template parameter 'PrevDecl' is being shadowed by a new
00444 /// declaration at location Loc. Returns true to indicate that this is
00445 /// an error, and false otherwise.
00446 void Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
00447   assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
00448 
00449   // Microsoft Visual C++ permits template parameters to be shadowed.
00450   if (getLangOpts().MicrosoftExt)
00451     return;
00452 
00453   // C++ [temp.local]p4:
00454   //   A template-parameter shall not be redeclared within its
00455   //   scope (including nested scopes).
00456   Diag(Loc, diag::err_template_param_shadow)
00457     << cast<NamedDecl>(PrevDecl)->getDeclName();
00458   Diag(PrevDecl->getLocation(), diag::note_template_param_here);
00459   return;
00460 }
00461 
00462 /// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
00463 /// the parameter D to reference the templated declaration and return a pointer
00464 /// to the template declaration. Otherwise, do nothing to D and return null.
00465 TemplateDecl *Sema::AdjustDeclIfTemplate(Decl *&D) {
00466   if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D)) {
00467     D = Temp->getTemplatedDecl();
00468     return Temp;
00469   }
00470   return nullptr;
00471 }
00472 
00473 ParsedTemplateArgument ParsedTemplateArgument::getTemplatePackExpansion(
00474                                              SourceLocation EllipsisLoc) const {
00475   assert(Kind == Template &&
00476          "Only template template arguments can be pack expansions here");
00477   assert(getAsTemplate().get().containsUnexpandedParameterPack() &&
00478          "Template template argument pack expansion without packs");
00479   ParsedTemplateArgument Result(*this);
00480   Result.EllipsisLoc = EllipsisLoc;
00481   return Result;
00482 }
00483 
00484 static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef,
00485                                             const ParsedTemplateArgument &Arg) {
00486 
00487   switch (Arg.getKind()) {
00488   case ParsedTemplateArgument::Type: {
00489     TypeSourceInfo *DI;
00490     QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI);
00491     if (!DI)
00492       DI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getLocation());
00493     return TemplateArgumentLoc(TemplateArgument(T), DI);
00494   }
00495 
00496   case ParsedTemplateArgument::NonType: {
00497     Expr *E = static_cast<Expr *>(Arg.getAsExpr());
00498     return TemplateArgumentLoc(TemplateArgument(E), E);
00499   }
00500 
00501   case ParsedTemplateArgument::Template: {
00502     TemplateName Template = Arg.getAsTemplate().get();
00503     TemplateArgument TArg;
00504     if (Arg.getEllipsisLoc().isValid())
00505       TArg = TemplateArgument(Template, Optional<unsigned int>());
00506     else
00507       TArg = Template;
00508     return TemplateArgumentLoc(TArg,
00509                                Arg.getScopeSpec().getWithLocInContext(
00510                                                               SemaRef.Context),
00511                                Arg.getLocation(),
00512                                Arg.getEllipsisLoc());
00513   }
00514   }
00515 
00516   llvm_unreachable("Unhandled parsed template argument");
00517 }
00518 
00519 /// \brief Translates template arguments as provided by the parser
00520 /// into template arguments used by semantic analysis.
00521 void Sema::translateTemplateArguments(const ASTTemplateArgsPtr &TemplateArgsIn,
00522                                       TemplateArgumentListInfo &TemplateArgs) {
00523  for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
00524    TemplateArgs.addArgument(translateTemplateArgument(*this,
00525                                                       TemplateArgsIn[I]));
00526 }
00527 
00528 static void maybeDiagnoseTemplateParameterShadow(Sema &SemaRef, Scope *S,
00529                                                  SourceLocation Loc,
00530                                                  IdentifierInfo *Name) {
00531   NamedDecl *PrevDecl = SemaRef.LookupSingleName(
00532       S, Name, Loc, Sema::LookupOrdinaryName, Sema::ForRedeclaration);
00533   if (PrevDecl && PrevDecl->isTemplateParameter())
00534     SemaRef.DiagnoseTemplateParameterShadow(Loc, PrevDecl);
00535 }
00536 
00537 /// ActOnTypeParameter - Called when a C++ template type parameter
00538 /// (e.g., "typename T") has been parsed. Typename specifies whether
00539 /// the keyword "typename" was used to declare the type parameter
00540 /// (otherwise, "class" was used), and KeyLoc is the location of the
00541 /// "class" or "typename" keyword. ParamName is the name of the
00542 /// parameter (NULL indicates an unnamed template parameter) and
00543 /// ParamNameLoc is the location of the parameter name (if any).
00544 /// If the type parameter has a default argument, it will be added
00545 /// later via ActOnTypeParameterDefault.
00546 Decl *Sema::ActOnTypeParameter(Scope *S, bool Typename,
00547                                SourceLocation EllipsisLoc,
00548                                SourceLocation KeyLoc,
00549                                IdentifierInfo *ParamName,
00550                                SourceLocation ParamNameLoc,
00551                                unsigned Depth, unsigned Position,
00552                                SourceLocation EqualLoc,
00553                                ParsedType DefaultArg) {
00554   assert(S->isTemplateParamScope() &&
00555          "Template type parameter not in template parameter scope!");
00556   bool Invalid = false;
00557 
00558   SourceLocation Loc = ParamNameLoc;
00559   if (!ParamName)
00560     Loc = KeyLoc;
00561 
00562   bool IsParameterPack = EllipsisLoc.isValid();
00563   TemplateTypeParmDecl *Param
00564     = TemplateTypeParmDecl::Create(Context, Context.getTranslationUnitDecl(),
00565                                    KeyLoc, Loc, Depth, Position, ParamName,
00566                                    Typename, IsParameterPack);
00567   Param->setAccess(AS_public);
00568   if (Invalid)
00569     Param->setInvalidDecl();
00570 
00571   if (ParamName) {
00572     maybeDiagnoseTemplateParameterShadow(*this, S, ParamNameLoc, ParamName);
00573 
00574     // Add the template parameter into the current scope.
00575     S->AddDecl(Param);
00576     IdResolver.AddDecl(Param);
00577   }
00578 
00579   // C++0x [temp.param]p9:
00580   //   A default template-argument may be specified for any kind of
00581   //   template-parameter that is not a template parameter pack.
00582   if (DefaultArg && IsParameterPack) {
00583     Diag(EqualLoc, diag::err_template_param_pack_default_arg);
00584     DefaultArg = ParsedType();
00585   }
00586 
00587   // Handle the default argument, if provided.
00588   if (DefaultArg) {
00589     TypeSourceInfo *DefaultTInfo;
00590     GetTypeFromParser(DefaultArg, &DefaultTInfo);
00591 
00592     assert(DefaultTInfo && "expected source information for type");
00593 
00594     // Check for unexpanded parameter packs.
00595     if (DiagnoseUnexpandedParameterPack(Loc, DefaultTInfo,
00596                                         UPPC_DefaultArgument))
00597       return Param;
00598 
00599     // Check the template argument itself.
00600     if (CheckTemplateArgument(Param, DefaultTInfo)) {
00601       Param->setInvalidDecl();
00602       return Param;
00603     }
00604 
00605     Param->setDefaultArgument(DefaultTInfo, false);
00606   }
00607 
00608   return Param;
00609 }
00610 
00611 /// \brief Check that the type of a non-type template parameter is
00612 /// well-formed.
00613 ///
00614 /// \returns the (possibly-promoted) parameter type if valid;
00615 /// otherwise, produces a diagnostic and returns a NULL type.
00616 QualType
00617 Sema::CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc) {
00618   // We don't allow variably-modified types as the type of non-type template
00619   // parameters.
00620   if (T->isVariablyModifiedType()) {
00621     Diag(Loc, diag::err_variably_modified_nontype_template_param)
00622       << T;
00623     return QualType();
00624   }
00625 
00626   // C++ [temp.param]p4:
00627   //
00628   // A non-type template-parameter shall have one of the following
00629   // (optionally cv-qualified) types:
00630   //
00631   //       -- integral or enumeration type,
00632   if (T->isIntegralOrEnumerationType() ||
00633       //   -- pointer to object or pointer to function,
00634       T->isPointerType() ||
00635       //   -- reference to object or reference to function,
00636       T->isReferenceType() ||
00637       //   -- pointer to member,
00638       T->isMemberPointerType() ||
00639       //   -- std::nullptr_t.
00640       T->isNullPtrType() ||
00641       // If T is a dependent type, we can't do the check now, so we
00642       // assume that it is well-formed.
00643       T->isDependentType()) {
00644     // C++ [temp.param]p5: The top-level cv-qualifiers on the template-parameter
00645     // are ignored when determining its type.
00646     return T.getUnqualifiedType();
00647   }
00648 
00649   // C++ [temp.param]p8:
00650   //
00651   //   A non-type template-parameter of type "array of T" or
00652   //   "function returning T" is adjusted to be of type "pointer to
00653   //   T" or "pointer to function returning T", respectively.
00654   else if (T->isArrayType())
00655     // FIXME: Keep the type prior to promotion?
00656     return Context.getArrayDecayedType(T);
00657   else if (T->isFunctionType())
00658     // FIXME: Keep the type prior to promotion?
00659     return Context.getPointerType(T);
00660 
00661   Diag(Loc, diag::err_template_nontype_parm_bad_type)
00662     << T;
00663 
00664   return QualType();
00665 }
00666 
00667 Decl *Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
00668                                           unsigned Depth,
00669                                           unsigned Position,
00670                                           SourceLocation EqualLoc,
00671                                           Expr *Default) {
00672   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
00673   QualType T = TInfo->getType();
00674 
00675   assert(S->isTemplateParamScope() &&
00676          "Non-type template parameter not in template parameter scope!");
00677   bool Invalid = false;
00678 
00679   T = CheckNonTypeTemplateParameterType(T, D.getIdentifierLoc());
00680   if (T.isNull()) {
00681     T = Context.IntTy; // Recover with an 'int' type.
00682     Invalid = true;
00683   }
00684 
00685   IdentifierInfo *ParamName = D.getIdentifier();
00686   bool IsParameterPack = D.hasEllipsis();
00687   NonTypeTemplateParmDecl *Param
00688     = NonTypeTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
00689                                       D.getLocStart(),
00690                                       D.getIdentifierLoc(),
00691                                       Depth, Position, ParamName, T,
00692                                       IsParameterPack, TInfo);
00693   Param->setAccess(AS_public);
00694 
00695   if (Invalid)
00696     Param->setInvalidDecl();
00697 
00698   if (ParamName) {
00699     maybeDiagnoseTemplateParameterShadow(*this, S, D.getIdentifierLoc(),
00700                                          ParamName);
00701 
00702     // Add the template parameter into the current scope.
00703     S->AddDecl(Param);
00704     IdResolver.AddDecl(Param);
00705   }
00706 
00707   // C++0x [temp.param]p9:
00708   //   A default template-argument may be specified for any kind of
00709   //   template-parameter that is not a template parameter pack.
00710   if (Default && IsParameterPack) {
00711     Diag(EqualLoc, diag::err_template_param_pack_default_arg);
00712     Default = nullptr;
00713   }
00714 
00715   // Check the well-formedness of the default template argument, if provided.
00716   if (Default) {
00717     // Check for unexpanded parameter packs.
00718     if (DiagnoseUnexpandedParameterPack(Default, UPPC_DefaultArgument))
00719       return Param;
00720 
00721     TemplateArgument Converted;
00722     ExprResult DefaultRes = CheckTemplateArgument(Param, Param->getType(), Default, Converted);
00723     if (DefaultRes.isInvalid()) {
00724       Param->setInvalidDecl();
00725       return Param;
00726     }
00727     Default = DefaultRes.get();
00728 
00729     Param->setDefaultArgument(Default, false);
00730   }
00731 
00732   return Param;
00733 }
00734 
00735 /// ActOnTemplateTemplateParameter - Called when a C++ template template
00736 /// parameter (e.g. T in template <template <typename> class T> class array)
00737 /// has been parsed. S is the current scope.
00738 Decl *Sema::ActOnTemplateTemplateParameter(Scope* S,
00739                                            SourceLocation TmpLoc,
00740                                            TemplateParameterList *Params,
00741                                            SourceLocation EllipsisLoc,
00742                                            IdentifierInfo *Name,
00743                                            SourceLocation NameLoc,
00744                                            unsigned Depth,
00745                                            unsigned Position,
00746                                            SourceLocation EqualLoc,
00747                                            ParsedTemplateArgument Default) {
00748   assert(S->isTemplateParamScope() &&
00749          "Template template parameter not in template parameter scope!");
00750 
00751   // Construct the parameter object.
00752   bool IsParameterPack = EllipsisLoc.isValid();
00753   TemplateTemplateParmDecl *Param =
00754     TemplateTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
00755                                      NameLoc.isInvalid()? TmpLoc : NameLoc,
00756                                      Depth, Position, IsParameterPack,
00757                                      Name, Params);
00758   Param->setAccess(AS_public);
00759   
00760   // If the template template parameter has a name, then link the identifier
00761   // into the scope and lookup mechanisms.
00762   if (Name) {
00763     maybeDiagnoseTemplateParameterShadow(*this, S, NameLoc, Name);
00764 
00765     S->AddDecl(Param);
00766     IdResolver.AddDecl(Param);
00767   }
00768 
00769   if (Params->size() == 0) {
00770     Diag(Param->getLocation(), diag::err_template_template_parm_no_parms)
00771     << SourceRange(Params->getLAngleLoc(), Params->getRAngleLoc());
00772     Param->setInvalidDecl();
00773   }
00774 
00775   // C++0x [temp.param]p9:
00776   //   A default template-argument may be specified for any kind of
00777   //   template-parameter that is not a template parameter pack.
00778   if (IsParameterPack && !Default.isInvalid()) {
00779     Diag(EqualLoc, diag::err_template_param_pack_default_arg);
00780     Default = ParsedTemplateArgument();
00781   }
00782 
00783   if (!Default.isInvalid()) {
00784     // Check only that we have a template template argument. We don't want to
00785     // try to check well-formedness now, because our template template parameter
00786     // might have dependent types in its template parameters, which we wouldn't
00787     // be able to match now.
00788     //
00789     // If none of the template template parameter's template arguments mention
00790     // other template parameters, we could actually perform more checking here.
00791     // However, it isn't worth doing.
00792     TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default);
00793     if (DefaultArg.getArgument().getAsTemplate().isNull()) {
00794       Diag(DefaultArg.getLocation(), diag::err_template_arg_not_class_template)
00795         << DefaultArg.getSourceRange();
00796       return Param;
00797     }
00798 
00799     // Check for unexpanded parameter packs.
00800     if (DiagnoseUnexpandedParameterPack(DefaultArg.getLocation(),
00801                                         DefaultArg.getArgument().getAsTemplate(),
00802                                         UPPC_DefaultArgument))
00803       return Param;
00804 
00805     Param->setDefaultArgument(DefaultArg, false);
00806   }
00807 
00808   return Param;
00809 }
00810 
00811 /// ActOnTemplateParameterList - Builds a TemplateParameterList that
00812 /// contains the template parameters in Params/NumParams.
00813 TemplateParameterList *
00814 Sema::ActOnTemplateParameterList(unsigned Depth,
00815                                  SourceLocation ExportLoc,
00816                                  SourceLocation TemplateLoc,
00817                                  SourceLocation LAngleLoc,
00818                                  Decl **Params, unsigned NumParams,
00819                                  SourceLocation RAngleLoc) {
00820   if (ExportLoc.isValid())
00821     Diag(ExportLoc, diag::warn_template_export_unsupported);
00822 
00823   return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
00824                                        (NamedDecl**)Params, NumParams,
00825                                        RAngleLoc);
00826 }
00827 
00828 static void SetNestedNameSpecifier(TagDecl *T, const CXXScopeSpec &SS) {
00829   if (SS.isSet())
00830     T->setQualifierInfo(SS.getWithLocInContext(T->getASTContext()));
00831 }
00832 
00833 DeclResult
00834 Sema::CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
00835                          SourceLocation KWLoc, CXXScopeSpec &SS,
00836                          IdentifierInfo *Name, SourceLocation NameLoc,
00837                          AttributeList *Attr,
00838                          TemplateParameterList *TemplateParams,
00839                          AccessSpecifier AS, SourceLocation ModulePrivateLoc,
00840                          SourceLocation FriendLoc,
00841                          unsigned NumOuterTemplateParamLists,
00842                          TemplateParameterList** OuterTemplateParamLists) {
00843   assert(TemplateParams && TemplateParams->size() > 0 &&
00844          "No template parameters");
00845   assert(TUK != TUK_Reference && "Can only declare or define class templates");
00846   bool Invalid = false;
00847 
00848   // Check that we can declare a template here.
00849   if (CheckTemplateDeclScope(S, TemplateParams))
00850     return true;
00851 
00852   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
00853   assert(Kind != TTK_Enum && "can't build template of enumerated type");
00854 
00855   // There is no such thing as an unnamed class template.
00856   if (!Name) {
00857     Diag(KWLoc, diag::err_template_unnamed_class);
00858     return true;
00859   }
00860 
00861   // Find any previous declaration with this name. For a friend with no
00862   // scope explicitly specified, we only look for tag declarations (per
00863   // C++11 [basic.lookup.elab]p2).
00864   DeclContext *SemanticContext;
00865   LookupResult Previous(*this, Name, NameLoc,
00866                         (SS.isEmpty() && TUK == TUK_Friend)
00867                           ? LookupTagName : LookupOrdinaryName,
00868                         ForRedeclaration);
00869   if (SS.isNotEmpty() && !SS.isInvalid()) {
00870     SemanticContext = computeDeclContext(SS, true);
00871     if (!SemanticContext) {
00872       // FIXME: Horrible, horrible hack! We can't currently represent this
00873       // in the AST, and historically we have just ignored such friend
00874       // class templates, so don't complain here.
00875       Diag(NameLoc, TUK == TUK_Friend
00876                         ? diag::warn_template_qualified_friend_ignored
00877                         : diag::err_template_qualified_declarator_no_match)
00878           << SS.getScopeRep() << SS.getRange();
00879       return TUK != TUK_Friend;
00880     }
00881 
00882     if (RequireCompleteDeclContext(SS, SemanticContext))
00883       return true;
00884 
00885     // If we're adding a template to a dependent context, we may need to 
00886     // rebuilding some of the types used within the template parameter list, 
00887     // now that we know what the current instantiation is.
00888     if (SemanticContext->isDependentContext()) {
00889       ContextRAII SavedContext(*this, SemanticContext);
00890       if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
00891         Invalid = true;
00892     } else if (TUK != TUK_Friend && TUK != TUK_Reference)
00893       diagnoseQualifiedDeclaration(SS, SemanticContext, Name, NameLoc);
00894 
00895     LookupQualifiedName(Previous, SemanticContext);
00896   } else {
00897     SemanticContext = CurContext;
00898     LookupName(Previous, S);
00899   }
00900 
00901   if (Previous.isAmbiguous())
00902     return true;
00903 
00904   NamedDecl *PrevDecl = nullptr;
00905   if (Previous.begin() != Previous.end())
00906     PrevDecl = (*Previous.begin())->getUnderlyingDecl();
00907 
00908   // If there is a previous declaration with the same name, check
00909   // whether this is a valid redeclaration.
00910   ClassTemplateDecl *PrevClassTemplate
00911     = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
00912 
00913   // We may have found the injected-class-name of a class template,
00914   // class template partial specialization, or class template specialization.
00915   // In these cases, grab the template that is being defined or specialized.
00916   if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) &&
00917       cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
00918     PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
00919     PrevClassTemplate
00920       = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
00921     if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
00922       PrevClassTemplate
00923         = cast<ClassTemplateSpecializationDecl>(PrevDecl)
00924             ->getSpecializedTemplate();
00925     }
00926   }
00927 
00928   if (TUK == TUK_Friend) {
00929     // C++ [namespace.memdef]p3:
00930     //   [...] When looking for a prior declaration of a class or a function
00931     //   declared as a friend, and when the name of the friend class or
00932     //   function is neither a qualified name nor a template-id, scopes outside
00933     //   the innermost enclosing namespace scope are not considered.
00934     if (!SS.isSet()) {
00935       DeclContext *OutermostContext = CurContext;
00936       while (!OutermostContext->isFileContext())
00937         OutermostContext = OutermostContext->getLookupParent();
00938 
00939       if (PrevDecl &&
00940           (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
00941            OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
00942         SemanticContext = PrevDecl->getDeclContext();
00943       } else {
00944         // Declarations in outer scopes don't matter. However, the outermost
00945         // context we computed is the semantic context for our new
00946         // declaration.
00947         PrevDecl = PrevClassTemplate = nullptr;
00948         SemanticContext = OutermostContext;
00949 
00950         // Check that the chosen semantic context doesn't already contain a
00951         // declaration of this name as a non-tag type.
00952         LookupResult Previous(*this, Name, NameLoc, LookupOrdinaryName,
00953                               ForRedeclaration);
00954         DeclContext *LookupContext = SemanticContext;
00955         while (LookupContext->isTransparentContext())
00956           LookupContext = LookupContext->getLookupParent();
00957         LookupQualifiedName(Previous, LookupContext);
00958 
00959         if (Previous.isAmbiguous())
00960           return true;
00961 
00962         if (Previous.begin() != Previous.end())
00963           PrevDecl = (*Previous.begin())->getUnderlyingDecl();
00964       }
00965     }
00966   } else if (PrevDecl &&
00967              !isDeclInScope(PrevDecl, SemanticContext, S, SS.isValid()))
00968     PrevDecl = PrevClassTemplate = nullptr;
00969 
00970   if (PrevClassTemplate) {
00971     // Ensure that the template parameter lists are compatible. Skip this check
00972     // for a friend in a dependent context: the template parameter list itself
00973     // could be dependent.
00974     if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
00975         !TemplateParameterListsAreEqual(TemplateParams,
00976                                    PrevClassTemplate->getTemplateParameters(),
00977                                         /*Complain=*/true,
00978                                         TPL_TemplateMatch))
00979       return true;
00980 
00981     // C++ [temp.class]p4:
00982     //   In a redeclaration, partial specialization, explicit
00983     //   specialization or explicit instantiation of a class template,
00984     //   the class-key shall agree in kind with the original class
00985     //   template declaration (7.1.5.3).
00986     RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
00987     if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind,
00988                                       TUK == TUK_Definition,  KWLoc, *Name)) {
00989       Diag(KWLoc, diag::err_use_with_wrong_tag)
00990         << Name
00991         << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName());
00992       Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
00993       Kind = PrevRecordDecl->getTagKind();
00994     }
00995 
00996     // Check for redefinition of this class template.
00997     if (TUK == TUK_Definition) {
00998       if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
00999         Diag(NameLoc, diag::err_redefinition) << Name;
01000         Diag(Def->getLocation(), diag::note_previous_definition);
01001         // FIXME: Would it make sense to try to "forget" the previous
01002         // definition, as part of error recovery?
01003         return true;
01004       }
01005     }    
01006   } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
01007     // Maybe we will complain about the shadowed template parameter.
01008     DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
01009     // Just pretend that we didn't see the previous declaration.
01010     PrevDecl = nullptr;
01011   } else if (PrevDecl) {
01012     // C++ [temp]p5:
01013     //   A class template shall not have the same name as any other
01014     //   template, class, function, object, enumeration, enumerator,
01015     //   namespace, or type in the same scope (3.3), except as specified
01016     //   in (14.5.4).
01017     Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
01018     Diag(PrevDecl->getLocation(), diag::note_previous_definition);
01019     return true;
01020   }
01021 
01022   // Check the template parameter list of this declaration, possibly
01023   // merging in the template parameter list from the previous class
01024   // template declaration. Skip this check for a friend in a dependent
01025   // context, because the template parameter list might be dependent.
01026   if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
01027       CheckTemplateParameterList(
01028           TemplateParams,
01029           PrevClassTemplate ? PrevClassTemplate->getTemplateParameters()
01030                             : nullptr,
01031           (SS.isSet() && SemanticContext && SemanticContext->isRecord() &&
01032            SemanticContext->isDependentContext())
01033               ? TPC_ClassTemplateMember
01034               : TUK == TUK_Friend ? TPC_FriendClassTemplate
01035                                   : TPC_ClassTemplate))
01036     Invalid = true;
01037 
01038   if (SS.isSet()) {
01039     // If the name of the template was qualified, we must be defining the
01040     // template out-of-line.
01041     if (!SS.isInvalid() && !Invalid && !PrevClassTemplate) {
01042       Diag(NameLoc, TUK == TUK_Friend ? diag::err_friend_decl_does_not_match
01043                                       : diag::err_member_decl_does_not_match)
01044         << Name << SemanticContext << /*IsDefinition*/true << SS.getRange();
01045       Invalid = true;
01046     }
01047   }
01048 
01049   CXXRecordDecl *NewClass =
01050     CXXRecordDecl::Create(Context, Kind, SemanticContext, KWLoc, NameLoc, Name,
01051                           PrevClassTemplate?
01052                             PrevClassTemplate->getTemplatedDecl() : nullptr,
01053                           /*DelayTypeCreation=*/true);
01054   SetNestedNameSpecifier(NewClass, SS);
01055   if (NumOuterTemplateParamLists > 0)
01056     NewClass->setTemplateParameterListsInfo(Context,
01057                                             NumOuterTemplateParamLists,
01058                                             OuterTemplateParamLists);
01059 
01060   // Add alignment attributes if necessary; these attributes are checked when
01061   // the ASTContext lays out the structure.
01062   if (TUK == TUK_Definition) {
01063     AddAlignmentAttributesForRecord(NewClass);
01064     AddMsStructLayoutForRecord(NewClass);
01065   }
01066 
01067   ClassTemplateDecl *NewTemplate
01068     = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
01069                                 DeclarationName(Name), TemplateParams,
01070                                 NewClass, PrevClassTemplate);
01071   NewClass->setDescribedClassTemplate(NewTemplate);
01072   
01073   if (ModulePrivateLoc.isValid())
01074     NewTemplate->setModulePrivate();
01075   
01076   // Build the type for the class template declaration now.
01077   QualType T = NewTemplate->getInjectedClassNameSpecialization();
01078   T = Context.getInjectedClassNameType(NewClass, T);
01079   assert(T->isDependentType() && "Class template type is not dependent?");
01080   (void)T;
01081 
01082   // If we are providing an explicit specialization of a member that is a
01083   // class template, make a note of that.
01084   if (PrevClassTemplate &&
01085       PrevClassTemplate->getInstantiatedFromMemberTemplate())
01086     PrevClassTemplate->setMemberSpecialization();
01087 
01088   // Set the access specifier.
01089   if (!Invalid && TUK != TUK_Friend && NewTemplate->getDeclContext()->isRecord())
01090     SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
01091 
01092   // Set the lexical context of these templates
01093   NewClass->setLexicalDeclContext(CurContext);
01094   NewTemplate->setLexicalDeclContext(CurContext);
01095 
01096   if (TUK == TUK_Definition)
01097     NewClass->startDefinition();
01098 
01099   if (Attr)
01100     ProcessDeclAttributeList(S, NewClass, Attr);
01101 
01102   if (PrevClassTemplate)
01103     mergeDeclAttributes(NewClass, PrevClassTemplate->getTemplatedDecl());
01104 
01105   AddPushedVisibilityAttribute(NewClass);
01106 
01107   if (TUK != TUK_Friend) {
01108     // Per C++ [basic.scope.temp]p2, skip the template parameter scopes.
01109     Scope *Outer = S;
01110     while ((Outer->getFlags() & Scope::TemplateParamScope) != 0)
01111       Outer = Outer->getParent();
01112     PushOnScopeChains(NewTemplate, Outer);
01113   } else {
01114     if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
01115       NewTemplate->setAccess(PrevClassTemplate->getAccess());
01116       NewClass->setAccess(PrevClassTemplate->getAccess());
01117     }
01118 
01119     NewTemplate->setObjectOfFriendDecl();
01120 
01121     // Friend templates are visible in fairly strange ways.
01122     if (!CurContext->isDependentContext()) {
01123       DeclContext *DC = SemanticContext->getRedeclContext();
01124       DC->makeDeclVisibleInContext(NewTemplate);
01125       if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
01126         PushOnScopeChains(NewTemplate, EnclosingScope,
01127                           /* AddToContext = */ false);
01128     }
01129 
01130     FriendDecl *Friend = FriendDecl::Create(
01131         Context, CurContext, NewClass->getLocation(), NewTemplate, FriendLoc);
01132     Friend->setAccess(AS_public);
01133     CurContext->addDecl(Friend);
01134   }
01135 
01136   if (Invalid) {
01137     NewTemplate->setInvalidDecl();
01138     NewClass->setInvalidDecl();
01139   }
01140 
01141   ActOnDocumentableDecl(NewTemplate);
01142 
01143   return NewTemplate;
01144 }
01145 
01146 /// \brief Diagnose the presence of a default template argument on a
01147 /// template parameter, which is ill-formed in certain contexts.
01148 ///
01149 /// \returns true if the default template argument should be dropped.
01150 static bool DiagnoseDefaultTemplateArgument(Sema &S,
01151                                             Sema::TemplateParamListContext TPC,
01152                                             SourceLocation ParamLoc,
01153                                             SourceRange DefArgRange) {
01154   switch (TPC) {
01155   case Sema::TPC_ClassTemplate:
01156   case Sema::TPC_VarTemplate:
01157   case Sema::TPC_TypeAliasTemplate:
01158     return false;
01159 
01160   case Sema::TPC_FunctionTemplate:
01161   case Sema::TPC_FriendFunctionTemplateDefinition:
01162     // C++ [temp.param]p9:
01163     //   A default template-argument shall not be specified in a
01164     //   function template declaration or a function template
01165     //   definition [...]
01166     //   If a friend function template declaration specifies a default 
01167     //   template-argument, that declaration shall be a definition and shall be
01168     //   the only declaration of the function template in the translation unit.
01169     // (C++98/03 doesn't have this wording; see DR226).
01170     S.Diag(ParamLoc, S.getLangOpts().CPlusPlus11 ?
01171          diag::warn_cxx98_compat_template_parameter_default_in_function_template
01172            : diag::ext_template_parameter_default_in_function_template)
01173       << DefArgRange;
01174     return false;
01175 
01176   case Sema::TPC_ClassTemplateMember:
01177     // C++0x [temp.param]p9:
01178     //   A default template-argument shall not be specified in the
01179     //   template-parameter-lists of the definition of a member of a
01180     //   class template that appears outside of the member's class.
01181     S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
01182       << DefArgRange;
01183     return true;
01184 
01185   case Sema::TPC_FriendClassTemplate:
01186   case Sema::TPC_FriendFunctionTemplate:
01187     // C++ [temp.param]p9:
01188     //   A default template-argument shall not be specified in a
01189     //   friend template declaration.
01190     S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
01191       << DefArgRange;
01192     return true;
01193 
01194     // FIXME: C++0x [temp.param]p9 allows default template-arguments
01195     // for friend function templates if there is only a single
01196     // declaration (and it is a definition). Strange!
01197   }
01198 
01199   llvm_unreachable("Invalid TemplateParamListContext!");
01200 }
01201 
01202 /// \brief Check for unexpanded parameter packs within the template parameters
01203 /// of a template template parameter, recursively.
01204 static bool DiagnoseUnexpandedParameterPacks(Sema &S,
01205                                              TemplateTemplateParmDecl *TTP) {
01206   // A template template parameter which is a parameter pack is also a pack
01207   // expansion.
01208   if (TTP->isParameterPack())
01209     return false;
01210 
01211   TemplateParameterList *Params = TTP->getTemplateParameters();
01212   for (unsigned I = 0, N = Params->size(); I != N; ++I) {
01213     NamedDecl *P = Params->getParam(I);
01214     if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {
01215       if (!NTTP->isParameterPack() &&
01216           S.DiagnoseUnexpandedParameterPack(NTTP->getLocation(),
01217                                             NTTP->getTypeSourceInfo(),
01218                                       Sema::UPPC_NonTypeTemplateParameterType))
01219         return true;
01220 
01221       continue;
01222     }
01223 
01224     if (TemplateTemplateParmDecl *InnerTTP
01225                                         = dyn_cast<TemplateTemplateParmDecl>(P))
01226       if (DiagnoseUnexpandedParameterPacks(S, InnerTTP))
01227         return true;
01228   }
01229 
01230   return false;
01231 }
01232 
01233 /// \brief Checks the validity of a template parameter list, possibly
01234 /// considering the template parameter list from a previous
01235 /// declaration.
01236 ///
01237 /// If an "old" template parameter list is provided, it must be
01238 /// equivalent (per TemplateParameterListsAreEqual) to the "new"
01239 /// template parameter list.
01240 ///
01241 /// \param NewParams Template parameter list for a new template
01242 /// declaration. This template parameter list will be updated with any
01243 /// default arguments that are carried through from the previous
01244 /// template parameter list.
01245 ///
01246 /// \param OldParams If provided, template parameter list from a
01247 /// previous declaration of the same template. Default template
01248 /// arguments will be merged from the old template parameter list to
01249 /// the new template parameter list.
01250 ///
01251 /// \param TPC Describes the context in which we are checking the given
01252 /// template parameter list.
01253 ///
01254 /// \returns true if an error occurred, false otherwise.
01255 bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
01256                                       TemplateParameterList *OldParams,
01257                                       TemplateParamListContext TPC) {
01258   bool Invalid = false;
01259 
01260   // C++ [temp.param]p10:
01261   //   The set of default template-arguments available for use with a
01262   //   template declaration or definition is obtained by merging the
01263   //   default arguments from the definition (if in scope) and all
01264   //   declarations in scope in the same way default function
01265   //   arguments are (8.3.6).
01266   bool SawDefaultArgument = false;
01267   SourceLocation PreviousDefaultArgLoc;
01268 
01269   // Dummy initialization to avoid warnings.
01270   TemplateParameterList::iterator OldParam = NewParams->end();
01271   if (OldParams)
01272     OldParam = OldParams->begin();
01273 
01274   bool RemoveDefaultArguments = false;
01275   for (TemplateParameterList::iterator NewParam = NewParams->begin(),
01276                                     NewParamEnd = NewParams->end();
01277        NewParam != NewParamEnd; ++NewParam) {
01278     // Variables used to diagnose redundant default arguments
01279     bool RedundantDefaultArg = false;
01280     SourceLocation OldDefaultLoc;
01281     SourceLocation NewDefaultLoc;
01282 
01283     // Variable used to diagnose missing default arguments
01284     bool MissingDefaultArg = false;
01285 
01286     // Variable used to diagnose non-final parameter packs
01287     bool SawParameterPack = false;
01288 
01289     if (TemplateTypeParmDecl *NewTypeParm
01290           = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
01291       // Check the presence of a default argument here.
01292       if (NewTypeParm->hasDefaultArgument() &&
01293           DiagnoseDefaultTemplateArgument(*this, TPC,
01294                                           NewTypeParm->getLocation(),
01295                NewTypeParm->getDefaultArgumentInfo()->getTypeLoc()
01296                                                        .getSourceRange()))
01297         NewTypeParm->removeDefaultArgument();
01298 
01299       // Merge default arguments for template type parameters.
01300       TemplateTypeParmDecl *OldTypeParm
01301           = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : nullptr;
01302 
01303       if (NewTypeParm->isParameterPack()) {
01304         assert(!NewTypeParm->hasDefaultArgument() &&
01305                "Parameter packs can't have a default argument!");
01306         SawParameterPack = true;
01307       } else if (OldTypeParm && OldTypeParm->hasDefaultArgument() &&
01308                  NewTypeParm->hasDefaultArgument()) {
01309         OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
01310         NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
01311         SawDefaultArgument = true;
01312         RedundantDefaultArg = true;
01313         PreviousDefaultArgLoc = NewDefaultLoc;
01314       } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
01315         // Merge the default argument from the old declaration to the
01316         // new declaration.
01317         NewTypeParm->setDefaultArgument(OldTypeParm->getDefaultArgumentInfo(),
01318                                         true);
01319         PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
01320       } else if (NewTypeParm->hasDefaultArgument()) {
01321         SawDefaultArgument = true;
01322         PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
01323       } else if (SawDefaultArgument)
01324         MissingDefaultArg = true;
01325     } else if (NonTypeTemplateParmDecl *NewNonTypeParm
01326                = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
01327       // Check for unexpanded parameter packs.
01328       if (!NewNonTypeParm->isParameterPack() &&
01329           DiagnoseUnexpandedParameterPack(NewNonTypeParm->getLocation(),
01330                                           NewNonTypeParm->getTypeSourceInfo(),
01331                                           UPPC_NonTypeTemplateParameterType)) {
01332         Invalid = true;
01333         continue;
01334       }
01335 
01336       // Check the presence of a default argument here.
01337       if (NewNonTypeParm->hasDefaultArgument() &&
01338           DiagnoseDefaultTemplateArgument(*this, TPC,
01339                                           NewNonTypeParm->getLocation(),
01340                     NewNonTypeParm->getDefaultArgument()->getSourceRange())) {
01341         NewNonTypeParm->removeDefaultArgument();
01342       }
01343 
01344       // Merge default arguments for non-type template parameters
01345       NonTypeTemplateParmDecl *OldNonTypeParm
01346         = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : nullptr;
01347       if (NewNonTypeParm->isParameterPack()) {
01348         assert(!NewNonTypeParm->hasDefaultArgument() &&
01349                "Parameter packs can't have a default argument!");
01350         if (!NewNonTypeParm->isPackExpansion())
01351           SawParameterPack = true;
01352       } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument() &&
01353                  NewNonTypeParm->hasDefaultArgument()) {
01354         OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
01355         NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
01356         SawDefaultArgument = true;
01357         RedundantDefaultArg = true;
01358         PreviousDefaultArgLoc = NewDefaultLoc;
01359       } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
01360         // Merge the default argument from the old declaration to the
01361         // new declaration.
01362         // FIXME: We need to create a new kind of "default argument"
01363         // expression that points to a previous non-type template
01364         // parameter.
01365         NewNonTypeParm->setDefaultArgument(
01366                                          OldNonTypeParm->getDefaultArgument(),
01367                                          /*Inherited=*/ true);
01368         PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
01369       } else if (NewNonTypeParm->hasDefaultArgument()) {
01370         SawDefaultArgument = true;
01371         PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
01372       } else if (SawDefaultArgument)
01373         MissingDefaultArg = true;
01374     } else {
01375       TemplateTemplateParmDecl *NewTemplateParm
01376         = cast<TemplateTemplateParmDecl>(*NewParam);
01377 
01378       // Check for unexpanded parameter packs, recursively.
01379       if (::DiagnoseUnexpandedParameterPacks(*this, NewTemplateParm)) {
01380         Invalid = true;
01381         continue;
01382       }
01383 
01384       // Check the presence of a default argument here.
01385       if (NewTemplateParm->hasDefaultArgument() &&
01386           DiagnoseDefaultTemplateArgument(*this, TPC,
01387                                           NewTemplateParm->getLocation(),
01388                      NewTemplateParm->getDefaultArgument().getSourceRange()))
01389         NewTemplateParm->removeDefaultArgument();
01390 
01391       // Merge default arguments for template template parameters
01392       TemplateTemplateParmDecl *OldTemplateParm
01393         = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : nullptr;
01394       if (NewTemplateParm->isParameterPack()) {
01395         assert(!NewTemplateParm->hasDefaultArgument() &&
01396                "Parameter packs can't have a default argument!");
01397         if (!NewTemplateParm->isPackExpansion())
01398           SawParameterPack = true;
01399       } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument() &&
01400           NewTemplateParm->hasDefaultArgument()) {
01401         OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
01402         NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
01403         SawDefaultArgument = true;
01404         RedundantDefaultArg = true;
01405         PreviousDefaultArgLoc = NewDefaultLoc;
01406       } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
01407         // Merge the default argument from the old declaration to the
01408         // new declaration.
01409         // FIXME: We need to create a new kind of "default argument" expression
01410         // that points to a previous template template parameter.
01411         NewTemplateParm->setDefaultArgument(
01412                                           OldTemplateParm->getDefaultArgument(),
01413                                           /*Inherited=*/ true);
01414         PreviousDefaultArgLoc
01415           = OldTemplateParm->getDefaultArgument().getLocation();
01416       } else if (NewTemplateParm->hasDefaultArgument()) {
01417         SawDefaultArgument = true;
01418         PreviousDefaultArgLoc
01419           = NewTemplateParm->getDefaultArgument().getLocation();
01420       } else if (SawDefaultArgument)
01421         MissingDefaultArg = true;
01422     }
01423 
01424     // C++11 [temp.param]p11:
01425     //   If a template parameter of a primary class template or alias template
01426     //   is a template parameter pack, it shall be the last template parameter.
01427     if (SawParameterPack && (NewParam + 1) != NewParamEnd &&
01428         (TPC == TPC_ClassTemplate || TPC == TPC_VarTemplate ||
01429          TPC == TPC_TypeAliasTemplate)) {
01430       Diag((*NewParam)->getLocation(),
01431            diag::err_template_param_pack_must_be_last_template_parameter);
01432       Invalid = true;
01433     }
01434 
01435     if (RedundantDefaultArg) {
01436       // C++ [temp.param]p12:
01437       //   A template-parameter shall not be given default arguments
01438       //   by two different declarations in the same scope.
01439       Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
01440       Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
01441       Invalid = true;
01442     } else if (MissingDefaultArg && TPC != TPC_FunctionTemplate) {
01443       // C++ [temp.param]p11:
01444       //   If a template-parameter of a class template has a default
01445       //   template-argument, each subsequent template-parameter shall either
01446       //   have a default template-argument supplied or be a template parameter
01447       //   pack.
01448       Diag((*NewParam)->getLocation(),
01449            diag::err_template_param_default_arg_missing);
01450       Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
01451       Invalid = true;
01452       RemoveDefaultArguments = true;
01453     }
01454 
01455     // If we have an old template parameter list that we're merging
01456     // in, move on to the next parameter.
01457     if (OldParams)
01458       ++OldParam;
01459   }
01460 
01461   // We were missing some default arguments at the end of the list, so remove
01462   // all of the default arguments.
01463   if (RemoveDefaultArguments) {
01464     for (TemplateParameterList::iterator NewParam = NewParams->begin(),
01465                                       NewParamEnd = NewParams->end();
01466          NewParam != NewParamEnd; ++NewParam) {
01467       if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*NewParam))
01468         TTP->removeDefaultArgument();
01469       else if (NonTypeTemplateParmDecl *NTTP
01470                                 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam))
01471         NTTP->removeDefaultArgument();
01472       else
01473         cast<TemplateTemplateParmDecl>(*NewParam)->removeDefaultArgument();
01474     }
01475   }
01476 
01477   return Invalid;
01478 }
01479 
01480 namespace {
01481 
01482 /// A class which looks for a use of a certain level of template
01483 /// parameter.
01484 struct DependencyChecker : RecursiveASTVisitor<DependencyChecker> {
01485   typedef RecursiveASTVisitor<DependencyChecker> super;
01486 
01487   unsigned Depth;
01488   bool Match;
01489   SourceLocation MatchLoc;
01490 
01491   DependencyChecker(unsigned Depth) : Depth(Depth), Match(false) {}
01492 
01493   DependencyChecker(TemplateParameterList *Params) : Match(false) {
01494     NamedDecl *ND = Params->getParam(0);
01495     if (TemplateTypeParmDecl *PD = dyn_cast<TemplateTypeParmDecl>(ND)) {
01496       Depth = PD->getDepth();
01497     } else if (NonTypeTemplateParmDecl *PD =
01498                  dyn_cast<NonTypeTemplateParmDecl>(ND)) {
01499       Depth = PD->getDepth();
01500     } else {
01501       Depth = cast<TemplateTemplateParmDecl>(ND)->getDepth();
01502     }
01503   }
01504 
01505   bool Matches(unsigned ParmDepth, SourceLocation Loc = SourceLocation()) {
01506     if (ParmDepth >= Depth) {
01507       Match = true;
01508       MatchLoc = Loc;
01509       return true;
01510     }
01511     return false;
01512   }
01513 
01514   bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
01515     return !Matches(TL.getTypePtr()->getDepth(), TL.getNameLoc());
01516   }
01517 
01518   bool VisitTemplateTypeParmType(const TemplateTypeParmType *T) {
01519     return !Matches(T->getDepth());
01520   }
01521 
01522   bool TraverseTemplateName(TemplateName N) {
01523     if (TemplateTemplateParmDecl *PD =
01524           dyn_cast_or_null<TemplateTemplateParmDecl>(N.getAsTemplateDecl()))
01525       if (Matches(PD->getDepth()))
01526         return false;
01527     return super::TraverseTemplateName(N);
01528   }
01529 
01530   bool VisitDeclRefExpr(DeclRefExpr *E) {
01531     if (NonTypeTemplateParmDecl *PD =
01532           dyn_cast<NonTypeTemplateParmDecl>(E->getDecl()))
01533       if (Matches(PD->getDepth(), E->getExprLoc()))
01534         return false;
01535     return super::VisitDeclRefExpr(E);
01536   }
01537 
01538   bool VisitSubstTemplateTypeParmType(const SubstTemplateTypeParmType *T) {
01539     return TraverseType(T->getReplacementType());
01540   }
01541 
01542   bool
01543   VisitSubstTemplateTypeParmPackType(const SubstTemplateTypeParmPackType *T) {
01544     return TraverseTemplateArgument(T->getArgumentPack());
01545   }
01546 
01547   bool TraverseInjectedClassNameType(const InjectedClassNameType *T) {
01548     return TraverseType(T->getInjectedSpecializationType());
01549   }
01550 };
01551 }
01552 
01553 /// Determines whether a given type depends on the given parameter
01554 /// list.
01555 static bool
01556 DependsOnTemplateParameters(QualType T, TemplateParameterList *Params) {
01557   DependencyChecker Checker(Params);
01558   Checker.TraverseType(T);
01559   return Checker.Match;
01560 }
01561 
01562 // Find the source range corresponding to the named type in the given
01563 // nested-name-specifier, if any.
01564 static SourceRange getRangeOfTypeInNestedNameSpecifier(ASTContext &Context,
01565                                                        QualType T,
01566                                                        const CXXScopeSpec &SS) {
01567   NestedNameSpecifierLoc NNSLoc(SS.getScopeRep(), SS.location_data());
01568   while (NestedNameSpecifier *NNS = NNSLoc.getNestedNameSpecifier()) {
01569     if (const Type *CurType = NNS->getAsType()) {
01570       if (Context.hasSameUnqualifiedType(T, QualType(CurType, 0)))
01571         return NNSLoc.getTypeLoc().getSourceRange();
01572     } else
01573       break;
01574     
01575     NNSLoc = NNSLoc.getPrefix();
01576   }
01577   
01578   return SourceRange();
01579 }
01580 
01581 /// \brief Match the given template parameter lists to the given scope
01582 /// specifier, returning the template parameter list that applies to the
01583 /// name.
01584 ///
01585 /// \param DeclStartLoc the start of the declaration that has a scope
01586 /// specifier or a template parameter list.
01587 ///
01588 /// \param DeclLoc The location of the declaration itself.
01589 ///
01590 /// \param SS the scope specifier that will be matched to the given template
01591 /// parameter lists. This scope specifier precedes a qualified name that is
01592 /// being declared.
01593 ///
01594 /// \param TemplateId The template-id following the scope specifier, if there
01595 /// is one. Used to check for a missing 'template<>'.
01596 ///
01597 /// \param ParamLists the template parameter lists, from the outermost to the
01598 /// innermost template parameter lists.
01599 ///
01600 /// \param IsFriend Whether to apply the slightly different rules for
01601 /// matching template parameters to scope specifiers in friend
01602 /// declarations.
01603 ///
01604 /// \param IsExplicitSpecialization will be set true if the entity being
01605 /// declared is an explicit specialization, false otherwise.
01606 ///
01607 /// \returns the template parameter list, if any, that corresponds to the
01608 /// name that is preceded by the scope specifier @p SS. This template
01609 /// parameter list may have template parameters (if we're declaring a
01610 /// template) or may have no template parameters (if we're declaring a
01611 /// template specialization), or may be NULL (if what we're declaring isn't
01612 /// itself a template).
01613 TemplateParameterList *Sema::MatchTemplateParametersToScopeSpecifier(
01614     SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS,
01615     TemplateIdAnnotation *TemplateId,
01616     ArrayRef<TemplateParameterList *> ParamLists, bool IsFriend,
01617     bool &IsExplicitSpecialization, bool &Invalid) {
01618   IsExplicitSpecialization = false;
01619   Invalid = false;
01620   
01621   // The sequence of nested types to which we will match up the template
01622   // parameter lists. We first build this list by starting with the type named
01623   // by the nested-name-specifier and walking out until we run out of types.
01624   SmallVector<QualType, 4> NestedTypes;
01625   QualType T;
01626   if (SS.getScopeRep()) {
01627     if (CXXRecordDecl *Record 
01628               = dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, true)))
01629       T = Context.getTypeDeclType(Record);
01630     else
01631       T = QualType(SS.getScopeRep()->getAsType(), 0);
01632   }
01633   
01634   // If we found an explicit specialization that prevents us from needing
01635   // 'template<>' headers, this will be set to the location of that
01636   // explicit specialization.
01637   SourceLocation ExplicitSpecLoc;
01638   
01639   while (!T.isNull()) {
01640     NestedTypes.push_back(T);
01641     
01642     // Retrieve the parent of a record type.
01643     if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
01644       // If this type is an explicit specialization, we're done.
01645       if (ClassTemplateSpecializationDecl *Spec
01646           = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
01647         if (!isa<ClassTemplatePartialSpecializationDecl>(Spec) && 
01648             Spec->getSpecializationKind() == TSK_ExplicitSpecialization) {
01649           ExplicitSpecLoc = Spec->getLocation();
01650           break;
01651         }
01652       } else if (Record->getTemplateSpecializationKind()
01653                                                 == TSK_ExplicitSpecialization) {
01654         ExplicitSpecLoc = Record->getLocation();
01655         break;
01656       }
01657       
01658       if (TypeDecl *Parent = dyn_cast<TypeDecl>(Record->getParent()))
01659         T = Context.getTypeDeclType(Parent);
01660       else
01661         T = QualType();
01662       continue;
01663     } 
01664     
01665     if (const TemplateSpecializationType *TST
01666                                      = T->getAs<TemplateSpecializationType>()) {
01667       if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
01668         if (TypeDecl *Parent = dyn_cast<TypeDecl>(Template->getDeclContext()))
01669           T = Context.getTypeDeclType(Parent);
01670         else
01671           T = QualType();
01672         continue;        
01673       }
01674     }
01675     
01676     // Look one step prior in a dependent template specialization type.
01677     if (const DependentTemplateSpecializationType *DependentTST
01678                           = T->getAs<DependentTemplateSpecializationType>()) {
01679       if (NestedNameSpecifier *NNS = DependentTST->getQualifier())
01680         T = QualType(NNS->getAsType(), 0);
01681       else
01682         T = QualType();
01683       continue;
01684     }
01685     
01686     // Look one step prior in a dependent name type.
01687     if (const DependentNameType *DependentName = T->getAs<DependentNameType>()){
01688       if (NestedNameSpecifier *NNS = DependentName->getQualifier())
01689         T = QualType(NNS->getAsType(), 0);
01690       else
01691         T = QualType();
01692       continue;
01693     }
01694     
01695     // Retrieve the parent of an enumeration type.
01696     if (const EnumType *EnumT = T->getAs<EnumType>()) {
01697       // FIXME: Forward-declared enums require a TSK_ExplicitSpecialization
01698       // check here.
01699       EnumDecl *Enum = EnumT->getDecl();
01700       
01701       // Get to the parent type.
01702       if (TypeDecl *Parent = dyn_cast<TypeDecl>(Enum->getParent()))
01703         T = Context.getTypeDeclType(Parent);
01704       else
01705         T = QualType();      
01706       continue;
01707     }
01708 
01709     T = QualType();
01710   }
01711   // Reverse the nested types list, since we want to traverse from the outermost
01712   // to the innermost while checking template-parameter-lists.
01713   std::reverse(NestedTypes.begin(), NestedTypes.end());
01714 
01715   // C++0x [temp.expl.spec]p17:
01716   //   A member or a member template may be nested within many
01717   //   enclosing class templates. In an explicit specialization for
01718   //   such a member, the member declaration shall be preceded by a
01719   //   template<> for each enclosing class template that is
01720   //   explicitly specialized.
01721   bool SawNonEmptyTemplateParameterList = false;
01722 
01723   auto CheckExplicitSpecialization = [&](SourceRange Range, bool Recovery) {
01724     if (SawNonEmptyTemplateParameterList) {
01725       Diag(DeclLoc, diag::err_specialize_member_of_template)
01726         << !Recovery << Range;
01727       Invalid = true;
01728       IsExplicitSpecialization = false;
01729       return true;
01730     }
01731 
01732     return false;
01733   };
01734 
01735   auto DiagnoseMissingExplicitSpecialization = [&] (SourceRange Range) {
01736     // Check that we can have an explicit specialization here.
01737     if (CheckExplicitSpecialization(Range, true))
01738       return true;
01739 
01740     // We don't have a template header, but we should.
01741     SourceLocation ExpectedTemplateLoc;
01742     if (!ParamLists.empty())
01743       ExpectedTemplateLoc = ParamLists[0]->getTemplateLoc();
01744     else
01745       ExpectedTemplateLoc = DeclStartLoc;
01746 
01747     Diag(DeclLoc, diag::err_template_spec_needs_header)
01748       << Range
01749       << FixItHint::CreateInsertion(ExpectedTemplateLoc, "template<> ");
01750     return false;
01751   };
01752 
01753   unsigned ParamIdx = 0;
01754   for (unsigned TypeIdx = 0, NumTypes = NestedTypes.size(); TypeIdx != NumTypes;
01755        ++TypeIdx) {
01756     T = NestedTypes[TypeIdx];
01757     
01758     // Whether we expect a 'template<>' header.
01759     bool NeedEmptyTemplateHeader = false;
01760 
01761     // Whether we expect a template header with parameters.
01762     bool NeedNonemptyTemplateHeader = false;
01763     
01764     // For a dependent type, the set of template parameters that we
01765     // expect to see.
01766     TemplateParameterList *ExpectedTemplateParams = nullptr;
01767 
01768     // C++0x [temp.expl.spec]p15:
01769     //   A member or a member template may be nested within many enclosing 
01770     //   class templates. In an explicit specialization for such a member, the 
01771     //   member declaration shall be preceded by a template<> for each 
01772     //   enclosing class template that is explicitly specialized.
01773     if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
01774       if (ClassTemplatePartialSpecializationDecl *Partial
01775             = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
01776         ExpectedTemplateParams = Partial->getTemplateParameters();
01777         NeedNonemptyTemplateHeader = true;
01778       } else if (Record->isDependentType()) {
01779         if (Record->getDescribedClassTemplate()) {
01780           ExpectedTemplateParams = Record->getDescribedClassTemplate()
01781                                                       ->getTemplateParameters();
01782           NeedNonemptyTemplateHeader = true;
01783         }
01784       } else if (ClassTemplateSpecializationDecl *Spec
01785                      = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
01786         // C++0x [temp.expl.spec]p4:
01787         //   Members of an explicitly specialized class template are defined
01788         //   in the same manner as members of normal classes, and not using 
01789         //   the template<> syntax. 
01790         if (Spec->getSpecializationKind() != TSK_ExplicitSpecialization)
01791           NeedEmptyTemplateHeader = true;
01792         else
01793           continue;
01794       } else if (Record->getTemplateSpecializationKind()) {
01795         if (Record->getTemplateSpecializationKind() 
01796                                                 != TSK_ExplicitSpecialization &&
01797             TypeIdx == NumTypes - 1)
01798           IsExplicitSpecialization = true;
01799         
01800         continue;
01801       }
01802     } else if (const TemplateSpecializationType *TST
01803                                      = T->getAs<TemplateSpecializationType>()) {
01804       if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {        
01805         ExpectedTemplateParams = Template->getTemplateParameters();
01806         NeedNonemptyTemplateHeader = true;        
01807       }
01808     } else if (T->getAs<DependentTemplateSpecializationType>()) {
01809       // FIXME:  We actually could/should check the template arguments here
01810       // against the corresponding template parameter list.
01811       NeedNonemptyTemplateHeader = false;
01812     } 
01813     
01814     // C++ [temp.expl.spec]p16:
01815     //   In an explicit specialization declaration for a member of a class 
01816     //   template or a member template that ap- pears in namespace scope, the 
01817     //   member template and some of its enclosing class templates may remain 
01818     //   unspecialized, except that the declaration shall not explicitly 
01819     //   specialize a class member template if its en- closing class templates 
01820     //   are not explicitly specialized as well.
01821     if (ParamIdx < ParamLists.size()) {
01822       if (ParamLists[ParamIdx]->size() == 0) {
01823         if (CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
01824                                         false))
01825           return nullptr;
01826       } else
01827         SawNonEmptyTemplateParameterList = true;
01828     }
01829     
01830     if (NeedEmptyTemplateHeader) {
01831       // If we're on the last of the types, and we need a 'template<>' header
01832       // here, then it's an explicit specialization.
01833       if (TypeIdx == NumTypes - 1)
01834         IsExplicitSpecialization = true;
01835 
01836       if (ParamIdx < ParamLists.size()) {
01837         if (ParamLists[ParamIdx]->size() > 0) {
01838           // The header has template parameters when it shouldn't. Complain.
01839           Diag(ParamLists[ParamIdx]->getTemplateLoc(), 
01840                diag::err_template_param_list_matches_nontemplate)
01841             << T
01842             << SourceRange(ParamLists[ParamIdx]->getLAngleLoc(),
01843                            ParamLists[ParamIdx]->getRAngleLoc())
01844             << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
01845           Invalid = true;
01846           return nullptr;
01847         }
01848 
01849         // Consume this template header.
01850         ++ParamIdx;
01851         continue;
01852       }
01853 
01854       if (!IsFriend)
01855         if (DiagnoseMissingExplicitSpecialization(
01856                 getRangeOfTypeInNestedNameSpecifier(Context, T, SS)))
01857           return nullptr;
01858 
01859       continue;
01860     }
01861 
01862     if (NeedNonemptyTemplateHeader) {
01863       // In friend declarations we can have template-ids which don't
01864       // depend on the corresponding template parameter lists.  But
01865       // assume that empty parameter lists are supposed to match this
01866       // template-id.
01867       if (IsFriend && T->isDependentType()) {
01868         if (ParamIdx < ParamLists.size() &&
01869             DependsOnTemplateParameters(T, ParamLists[ParamIdx]))
01870           ExpectedTemplateParams = nullptr;
01871         else 
01872           continue;
01873       }
01874 
01875       if (ParamIdx < ParamLists.size()) {
01876         // Check the template parameter list, if we can.
01877         if (ExpectedTemplateParams &&
01878             !TemplateParameterListsAreEqual(ParamLists[ParamIdx],
01879                                             ExpectedTemplateParams,
01880                                             true, TPL_TemplateMatch))
01881           Invalid = true;
01882 
01883         if (!Invalid &&
01884             CheckTemplateParameterList(ParamLists[ParamIdx], nullptr,
01885                                        TPC_ClassTemplateMember))
01886           Invalid = true;
01887         
01888         ++ParamIdx;
01889         continue;
01890       }
01891       
01892       Diag(DeclLoc, diag::err_template_spec_needs_template_parameters)
01893         << T
01894         << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
01895       Invalid = true;
01896       continue;
01897     }
01898   }
01899 
01900   // If there were at least as many template-ids as there were template
01901   // parameter lists, then there are no template parameter lists remaining for
01902   // the declaration itself.
01903   if (ParamIdx >= ParamLists.size()) {
01904     if (TemplateId && !IsFriend) {
01905       // We don't have a template header for the declaration itself, but we
01906       // should.
01907       IsExplicitSpecialization = true;
01908       DiagnoseMissingExplicitSpecialization(SourceRange(TemplateId->LAngleLoc,
01909                                                         TemplateId->RAngleLoc));
01910 
01911       // Fabricate an empty template parameter list for the invented header.
01912       return TemplateParameterList::Create(Context, SourceLocation(),
01913                                            SourceLocation(), nullptr, 0,
01914                                            SourceLocation());
01915     }
01916 
01917     return nullptr;
01918   }
01919 
01920   // If there were too many template parameter lists, complain about that now.
01921   if (ParamIdx < ParamLists.size() - 1) {
01922     bool HasAnyExplicitSpecHeader = false;
01923     bool AllExplicitSpecHeaders = true;
01924     for (unsigned I = ParamIdx, E = ParamLists.size() - 1; I != E; ++I) {
01925       if (ParamLists[I]->size() == 0)
01926         HasAnyExplicitSpecHeader = true;
01927       else
01928         AllExplicitSpecHeaders = false;
01929     }
01930 
01931     Diag(ParamLists[ParamIdx]->getTemplateLoc(),
01932          AllExplicitSpecHeaders ? diag::warn_template_spec_extra_headers
01933                                 : diag::err_template_spec_extra_headers)
01934         << SourceRange(ParamLists[ParamIdx]->getTemplateLoc(),
01935                        ParamLists[ParamLists.size() - 2]->getRAngleLoc());
01936 
01937     // If there was a specialization somewhere, such that 'template<>' is
01938     // not required, and there were any 'template<>' headers, note where the
01939     // specialization occurred.
01940     if (ExplicitSpecLoc.isValid() && HasAnyExplicitSpecHeader)
01941       Diag(ExplicitSpecLoc, 
01942            diag::note_explicit_template_spec_does_not_need_header)
01943         << NestedTypes.back();
01944     
01945     // We have a template parameter list with no corresponding scope, which
01946     // means that the resulting template declaration can't be instantiated
01947     // properly (we'll end up with dependent nodes when we shouldn't).
01948     if (!AllExplicitSpecHeaders)
01949       Invalid = true;
01950   }
01951 
01952   // C++ [temp.expl.spec]p16:
01953   //   In an explicit specialization declaration for a member of a class 
01954   //   template or a member template that ap- pears in namespace scope, the 
01955   //   member template and some of its enclosing class templates may remain 
01956   //   unspecialized, except that the declaration shall not explicitly 
01957   //   specialize a class member template if its en- closing class templates 
01958   //   are not explicitly specialized as well.
01959   if (ParamLists.back()->size() == 0 &&
01960       CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
01961                                   false))
01962     return nullptr;
01963 
01964   // Return the last template parameter list, which corresponds to the
01965   // entity being declared.
01966   return ParamLists.back();
01967 }
01968 
01969 void Sema::NoteAllFoundTemplates(TemplateName Name) {
01970   if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
01971     Diag(Template->getLocation(), diag::note_template_declared_here)
01972         << (isa<FunctionTemplateDecl>(Template)
01973                 ? 0
01974                 : isa<ClassTemplateDecl>(Template)
01975                       ? 1
01976                       : isa<VarTemplateDecl>(Template)
01977                             ? 2
01978                             : isa<TypeAliasTemplateDecl>(Template) ? 3 : 4)
01979         << Template->getDeclName();
01980     return;
01981   }
01982   
01983   if (OverloadedTemplateStorage *OST = Name.getAsOverloadedTemplate()) {
01984     for (OverloadedTemplateStorage::iterator I = OST->begin(), 
01985                                           IEnd = OST->end();
01986          I != IEnd; ++I)
01987       Diag((*I)->getLocation(), diag::note_template_declared_here)
01988         << 0 << (*I)->getDeclName();
01989     
01990     return;
01991   }
01992 }
01993 
01994 QualType Sema::CheckTemplateIdType(TemplateName Name,
01995                                    SourceLocation TemplateLoc,
01996                                    TemplateArgumentListInfo &TemplateArgs) {
01997   DependentTemplateName *DTN
01998     = Name.getUnderlying().getAsDependentTemplateName();
01999   if (DTN && DTN->isIdentifier())
02000     // When building a template-id where the template-name is dependent,
02001     // assume the template is a type template. Either our assumption is
02002     // correct, or the code is ill-formed and will be diagnosed when the
02003     // dependent name is substituted.
02004     return Context.getDependentTemplateSpecializationType(ETK_None,
02005                                                           DTN->getQualifier(),
02006                                                           DTN->getIdentifier(),
02007                                                           TemplateArgs);
02008 
02009   TemplateDecl *Template = Name.getAsTemplateDecl();
02010   if (!Template || isa<FunctionTemplateDecl>(Template) ||
02011       isa<VarTemplateDecl>(Template)) {
02012     // We might have a substituted template template parameter pack. If so,
02013     // build a template specialization type for it.
02014     if (Name.getAsSubstTemplateTemplateParmPack())
02015       return Context.getTemplateSpecializationType(Name, TemplateArgs);
02016 
02017     Diag(TemplateLoc, diag::err_template_id_not_a_type)
02018       << Name;
02019     NoteAllFoundTemplates(Name);
02020     return QualType();
02021   }
02022 
02023   // Check that the template argument list is well-formed for this
02024   // template.
02025   SmallVector<TemplateArgument, 4> Converted;
02026   if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
02027                                 false, Converted))
02028     return QualType();
02029 
02030   QualType CanonType;
02031 
02032   bool InstantiationDependent = false;
02033   if (TypeAliasTemplateDecl *AliasTemplate =
02034           dyn_cast<TypeAliasTemplateDecl>(Template)) {
02035     // Find the canonical type for this type alias template specialization.
02036     TypeAliasDecl *Pattern = AliasTemplate->getTemplatedDecl();
02037     if (Pattern->isInvalidDecl())
02038       return QualType();
02039 
02040     TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
02041                                       Converted.data(), Converted.size());
02042 
02043     // Only substitute for the innermost template argument list.
02044     MultiLevelTemplateArgumentList TemplateArgLists;
02045     TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
02046     unsigned Depth = AliasTemplate->getTemplateParameters()->getDepth();
02047     for (unsigned I = 0; I < Depth; ++I)
02048       TemplateArgLists.addOuterTemplateArguments(None);
02049 
02050     LocalInstantiationScope Scope(*this);
02051     InstantiatingTemplate Inst(*this, TemplateLoc, Template);
02052     if (Inst.isInvalid())
02053       return QualType();
02054 
02055     CanonType = SubstType(Pattern->getUnderlyingType(),
02056                           TemplateArgLists, AliasTemplate->getLocation(),
02057                           AliasTemplate->getDeclName());
02058     if (CanonType.isNull())
02059       return QualType();
02060   } else if (Name.isDependent() ||
02061              TemplateSpecializationType::anyDependentTemplateArguments(
02062                TemplateArgs, InstantiationDependent)) {
02063     // This class template specialization is a dependent
02064     // type. Therefore, its canonical type is another class template
02065     // specialization type that contains all of the converted
02066     // arguments in canonical form. This ensures that, e.g., A<T> and
02067     // A<T, T> have identical types when A is declared as:
02068     //
02069     //   template<typename T, typename U = T> struct A;
02070     TemplateName CanonName = Context.getCanonicalTemplateName(Name);
02071     CanonType = Context.getTemplateSpecializationType(CanonName,
02072                                                       Converted.data(),
02073                                                       Converted.size());
02074 
02075     // FIXME: CanonType is not actually the canonical type, and unfortunately
02076     // it is a TemplateSpecializationType that we will never use again.
02077     // In the future, we need to teach getTemplateSpecializationType to only
02078     // build the canonical type and return that to us.
02079     CanonType = Context.getCanonicalType(CanonType);
02080 
02081     // This might work out to be a current instantiation, in which
02082     // case the canonical type needs to be the InjectedClassNameType.
02083     //
02084     // TODO: in theory this could be a simple hashtable lookup; most
02085     // changes to CurContext don't change the set of current
02086     // instantiations.
02087     if (isa<ClassTemplateDecl>(Template)) {
02088       for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
02089         // If we get out to a namespace, we're done.
02090         if (Ctx->isFileContext()) break;
02091 
02092         // If this isn't a record, keep looking.
02093         CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
02094         if (!Record) continue;
02095 
02096         // Look for one of the two cases with InjectedClassNameTypes
02097         // and check whether it's the same template.
02098         if (!isa<ClassTemplatePartialSpecializationDecl>(Record) &&
02099             !Record->getDescribedClassTemplate())
02100           continue;
02101 
02102         // Fetch the injected class name type and check whether its
02103         // injected type is equal to the type we just built.
02104         QualType ICNT = Context.getTypeDeclType(Record);
02105         QualType Injected = cast<InjectedClassNameType>(ICNT)
02106           ->getInjectedSpecializationType();
02107 
02108         if (CanonType != Injected->getCanonicalTypeInternal())
02109           continue;
02110 
02111         // If so, the canonical type of this TST is the injected
02112         // class name type of the record we just found.
02113         assert(ICNT.isCanonical());
02114         CanonType = ICNT;
02115         break;
02116       }
02117     }
02118   } else if (ClassTemplateDecl *ClassTemplate
02119                = dyn_cast<ClassTemplateDecl>(Template)) {
02120     // Find the class template specialization declaration that
02121     // corresponds to these arguments.
02122     void *InsertPos = nullptr;
02123     ClassTemplateSpecializationDecl *Decl
02124       = ClassTemplate->findSpecialization(Converted, InsertPos);
02125     if (!Decl) {
02126       // This is the first time we have referenced this class template
02127       // specialization. Create the canonical declaration and add it to
02128       // the set of specializations.
02129       Decl = ClassTemplateSpecializationDecl::Create(Context,
02130                             ClassTemplate->getTemplatedDecl()->getTagKind(),
02131                                                 ClassTemplate->getDeclContext(),
02132                             ClassTemplate->getTemplatedDecl()->getLocStart(),
02133                                                 ClassTemplate->getLocation(),
02134                                                      ClassTemplate,
02135                                                      Converted.data(),
02136                                                      Converted.size(), nullptr);
02137       ClassTemplate->AddSpecialization(Decl, InsertPos);
02138       if (ClassTemplate->isOutOfLine())
02139         Decl->setLexicalDeclContext(ClassTemplate->getLexicalDeclContext());
02140     }
02141 
02142     // Diagnose uses of this specialization.
02143     (void)DiagnoseUseOfDecl(Decl, TemplateLoc);
02144 
02145     CanonType = Context.getTypeDeclType(Decl);
02146     assert(isa<RecordType>(CanonType) &&
02147            "type of non-dependent specialization is not a RecordType");
02148   }
02149 
02150   // Build the fully-sugared type for this class template
02151   // specialization, which refers back to the class template
02152   // specialization we created or found.
02153   return Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType);
02154 }
02155 
02156 TypeResult
02157 Sema::ActOnTemplateIdType(CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
02158                           TemplateTy TemplateD, SourceLocation TemplateLoc,
02159                           SourceLocation LAngleLoc,
02160                           ASTTemplateArgsPtr TemplateArgsIn,
02161                           SourceLocation RAngleLoc,
02162                           bool IsCtorOrDtorName) {
02163   if (SS.isInvalid())
02164     return true;
02165 
02166   TemplateName Template = TemplateD.get();
02167 
02168   // Translate the parser's template argument list in our AST format.
02169   TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
02170   translateTemplateArguments(TemplateArgsIn, TemplateArgs);
02171 
02172   if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
02173     QualType T
02174       = Context.getDependentTemplateSpecializationType(ETK_None,
02175                                                        DTN->getQualifier(),
02176                                                        DTN->getIdentifier(),
02177                                                        TemplateArgs);
02178     // Build type-source information.
02179     TypeLocBuilder TLB;
02180     DependentTemplateSpecializationTypeLoc SpecTL
02181       = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
02182     SpecTL.setElaboratedKeywordLoc(SourceLocation());
02183     SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
02184     SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
02185     SpecTL.setTemplateNameLoc(TemplateLoc);
02186     SpecTL.setLAngleLoc(LAngleLoc);
02187     SpecTL.setRAngleLoc(RAngleLoc);
02188     for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
02189       SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
02190     return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
02191   }
02192   
02193   QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
02194 
02195   if (Result.isNull())
02196     return true;
02197 
02198   // Build type-source information.
02199   TypeLocBuilder TLB;
02200   TemplateSpecializationTypeLoc SpecTL
02201     = TLB.push<TemplateSpecializationTypeLoc>(Result);
02202   SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
02203   SpecTL.setTemplateNameLoc(TemplateLoc);
02204   SpecTL.setLAngleLoc(LAngleLoc);
02205   SpecTL.setRAngleLoc(RAngleLoc);
02206   for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
02207     SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
02208 
02209   // NOTE: avoid constructing an ElaboratedTypeLoc if this is a
02210   // constructor or destructor name (in such a case, the scope specifier
02211   // will be attached to the enclosing Decl or Expr node).
02212   if (SS.isNotEmpty() && !IsCtorOrDtorName) {
02213     // Create an elaborated-type-specifier containing the nested-name-specifier.
02214     Result = Context.getElaboratedType(ETK_None, SS.getScopeRep(), Result);
02215     ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
02216     ElabTL.setElaboratedKeywordLoc(SourceLocation());
02217     ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
02218   }
02219   
02220   return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
02221 }
02222 
02223 TypeResult Sema::ActOnTagTemplateIdType(TagUseKind TUK,
02224                                         TypeSpecifierType TagSpec,
02225                                         SourceLocation TagLoc,
02226                                         CXXScopeSpec &SS,
02227                                         SourceLocation TemplateKWLoc,
02228                                         TemplateTy TemplateD,
02229                                         SourceLocation TemplateLoc,
02230                                         SourceLocation LAngleLoc,
02231                                         ASTTemplateArgsPtr TemplateArgsIn,
02232                                         SourceLocation RAngleLoc) {
02233   TemplateName Template = TemplateD.get();
02234   
02235   // Translate the parser's template argument list in our AST format.
02236   TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
02237   translateTemplateArguments(TemplateArgsIn, TemplateArgs);
02238   
02239   // Determine the tag kind
02240   TagTypeKind TagKind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
02241   ElaboratedTypeKeyword Keyword
02242     = TypeWithKeyword::getKeywordForTagTypeKind(TagKind);
02243 
02244   if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
02245     QualType T = Context.getDependentTemplateSpecializationType(Keyword,
02246                                                           DTN->getQualifier(), 
02247                                                           DTN->getIdentifier(), 
02248                                                                 TemplateArgs);
02249     
02250     // Build type-source information.    
02251     TypeLocBuilder TLB;
02252     DependentTemplateSpecializationTypeLoc SpecTL
02253       = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
02254     SpecTL.setElaboratedKeywordLoc(TagLoc);
02255     SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
02256     SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
02257     SpecTL.setTemplateNameLoc(TemplateLoc);
02258     SpecTL.setLAngleLoc(LAngleLoc);
02259     SpecTL.setRAngleLoc(RAngleLoc);
02260     for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
02261       SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
02262     return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
02263   }
02264 
02265   if (TypeAliasTemplateDecl *TAT =
02266         dyn_cast_or_null<TypeAliasTemplateDecl>(Template.getAsTemplateDecl())) {
02267     // C++0x [dcl.type.elab]p2:
02268     //   If the identifier resolves to a typedef-name or the simple-template-id
02269     //   resolves to an alias template specialization, the
02270     //   elaborated-type-specifier is ill-formed.
02271     Diag(TemplateLoc, diag::err_tag_reference_non_tag) << 4;
02272     Diag(TAT->getLocation(), diag::note_declared_at);
02273   }
02274   
02275   QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
02276   if (Result.isNull())
02277     return TypeResult(true);
02278   
02279   // Check the tag kind
02280   if (const RecordType *RT = Result->getAs<RecordType>()) {
02281     RecordDecl *D = RT->getDecl();
02282     
02283     IdentifierInfo *Id = D->getIdentifier();
02284     assert(Id && "templated class must have an identifier");
02285     
02286     if (!isAcceptableTagRedeclaration(D, TagKind, TUK == TUK_Definition,
02287                                       TagLoc, *Id)) {
02288       Diag(TagLoc, diag::err_use_with_wrong_tag)
02289         << Result
02290         << FixItHint::CreateReplacement(SourceRange(TagLoc), D->getKindName());
02291       Diag(D->getLocation(), diag::note_previous_use);
02292     }
02293   }
02294 
02295   // Provide source-location information for the template specialization.
02296   TypeLocBuilder TLB;
02297   TemplateSpecializationTypeLoc SpecTL
02298     = TLB.push<TemplateSpecializationTypeLoc>(Result);
02299   SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
02300   SpecTL.setTemplateNameLoc(TemplateLoc);
02301   SpecTL.setLAngleLoc(LAngleLoc);
02302   SpecTL.setRAngleLoc(RAngleLoc);
02303   for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
02304     SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
02305 
02306   // Construct an elaborated type containing the nested-name-specifier (if any)
02307   // and tag keyword.
02308   Result = Context.getElaboratedType(Keyword, SS.getScopeRep(), Result);
02309   ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
02310   ElabTL.setElaboratedKeywordLoc(TagLoc);
02311   ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
02312   return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
02313 }
02314 
02315 static bool CheckTemplatePartialSpecializationArgs(
02316     Sema &S, SourceLocation NameLoc, TemplateParameterList *TemplateParams,
02317     unsigned ExplicitArgs, SmallVectorImpl<TemplateArgument> &TemplateArgs);
02318 
02319 static bool CheckTemplateSpecializationScope(Sema &S, NamedDecl *Specialized,
02320                                              NamedDecl *PrevDecl,
02321                                              SourceLocation Loc,
02322                                              bool IsPartialSpecialization);
02323 
02324 static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D);
02325 
02326 static bool isTemplateArgumentTemplateParameter(
02327     const TemplateArgument &Arg, unsigned Depth, unsigned Index) {
02328   switch (Arg.getKind()) {
02329   case TemplateArgument::Null:
02330   case TemplateArgument::NullPtr:
02331   case TemplateArgument::Integral:
02332   case TemplateArgument::Declaration:
02333   case TemplateArgument::Pack:
02334   case TemplateArgument::TemplateExpansion:
02335     return false;
02336 
02337   case TemplateArgument::Type: {
02338     QualType Type = Arg.getAsType();
02339     const TemplateTypeParmType *TPT =
02340         Arg.getAsType()->getAs<TemplateTypeParmType>();
02341     return TPT && !Type.hasQualifiers() &&
02342            TPT->getDepth() == Depth && TPT->getIndex() == Index;
02343   }
02344 
02345   case TemplateArgument::Expression: {
02346     DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg.getAsExpr());
02347     if (!DRE || !DRE->getDecl())
02348       return false;
02349     const NonTypeTemplateParmDecl *NTTP =
02350         dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
02351     return NTTP && NTTP->getDepth() == Depth && NTTP->getIndex() == Index;
02352   }
02353 
02354   case TemplateArgument::Template:
02355     const TemplateTemplateParmDecl *TTP =
02356         dyn_cast_or_null<TemplateTemplateParmDecl>(
02357             Arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl());
02358     return TTP && TTP->getDepth() == Depth && TTP->getIndex() == Index;
02359   }
02360   llvm_unreachable("unexpected kind of template argument");
02361 }
02362 
02363 static bool isSameAsPrimaryTemplate(TemplateParameterList *Params,
02364                                     ArrayRef<TemplateArgument> Args) {
02365   if (Params->size() != Args.size())
02366     return false;
02367 
02368   unsigned Depth = Params->getDepth();
02369 
02370   for (unsigned I = 0, N = Args.size(); I != N; ++I) {
02371     TemplateArgument Arg = Args[I];
02372 
02373     // If the parameter is a pack expansion, the argument must be a pack
02374     // whose only element is a pack expansion.
02375     if (Params->getParam(I)->isParameterPack()) {
02376       if (Arg.getKind() != TemplateArgument::Pack || Arg.pack_size() != 1 ||
02377           !Arg.pack_begin()->isPackExpansion())
02378         return false;
02379       Arg = Arg.pack_begin()->getPackExpansionPattern();
02380     }
02381 
02382     if (!isTemplateArgumentTemplateParameter(Arg, Depth, I))
02383       return false;
02384   }
02385 
02386   return true;
02387 }
02388 
02389 /// Convert the parser's template argument list representation into our form.
02390 static TemplateArgumentListInfo
02391 makeTemplateArgumentListInfo(Sema &S, TemplateIdAnnotation &TemplateId) {
02392   TemplateArgumentListInfo TemplateArgs(TemplateId.LAngleLoc,
02393                                         TemplateId.RAngleLoc);
02394   ASTTemplateArgsPtr TemplateArgsPtr(TemplateId.getTemplateArgs(),
02395                                      TemplateId.NumArgs);
02396   S.translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
02397   return TemplateArgs;
02398 }
02399 
02400 DeclResult Sema::ActOnVarTemplateSpecialization(
02401     Scope *S, Declarator &D, TypeSourceInfo *DI, SourceLocation TemplateKWLoc,
02402     TemplateParameterList *TemplateParams, StorageClass SC,
02403     bool IsPartialSpecialization) {
02404   // D must be variable template id.
02405   assert(D.getName().getKind() == UnqualifiedId::IK_TemplateId &&
02406          "Variable template specialization is declared with a template it.");
02407 
02408   TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
02409   TemplateArgumentListInfo TemplateArgs =
02410       makeTemplateArgumentListInfo(*this, *TemplateId);
02411   SourceLocation TemplateNameLoc = D.getIdentifierLoc();
02412   SourceLocation LAngleLoc = TemplateId->LAngleLoc;
02413   SourceLocation RAngleLoc = TemplateId->RAngleLoc;
02414 
02415   TemplateName Name = TemplateId->Template.get();
02416 
02417   // The template-id must name a variable template.
02418   VarTemplateDecl *VarTemplate =
02419       dyn_cast_or_null<VarTemplateDecl>(Name.getAsTemplateDecl());
02420   if (!VarTemplate) {
02421     NamedDecl *FnTemplate;
02422     if (auto *OTS = Name.getAsOverloadedTemplate())
02423       FnTemplate = *OTS->begin();
02424     else
02425       FnTemplate = dyn_cast_or_null<FunctionTemplateDecl>(Name.getAsTemplateDecl());
02426     if (FnTemplate)
02427       return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template_but_method)
02428                << FnTemplate->getDeclName();
02429     return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template)
02430              << IsPartialSpecialization;
02431   }
02432 
02433   // Check for unexpanded parameter packs in any of the template arguments.
02434   for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
02435     if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
02436                                         UPPC_PartialSpecialization))
02437       return true;
02438 
02439   // Check that the template argument list is well-formed for this
02440   // template.
02441   SmallVector<TemplateArgument, 4> Converted;
02442   if (CheckTemplateArgumentList(VarTemplate, TemplateNameLoc, TemplateArgs,
02443                                 false, Converted))
02444     return true;
02445 
02446   // Check that the type of this variable template specialization
02447   // matches the expected type.
02448   TypeSourceInfo *ExpectedDI;
02449   {
02450     // Do substitution on the type of the declaration
02451     TemplateArgumentList TemplateArgList(TemplateArgumentList::OnStack,
02452                                          Converted.data(), Converted.size());
02453     InstantiatingTemplate Inst(*this, TemplateKWLoc, VarTemplate);
02454     if (Inst.isInvalid())
02455       return true;
02456     VarDecl *Templated = VarTemplate->getTemplatedDecl();
02457     ExpectedDI =
02458         SubstType(Templated->getTypeSourceInfo(),
02459                   MultiLevelTemplateArgumentList(TemplateArgList),
02460                   Templated->getTypeSpecStartLoc(), Templated->getDeclName());
02461   }
02462   if (!ExpectedDI)
02463     return true;
02464 
02465   // Find the variable template (partial) specialization declaration that
02466   // corresponds to these arguments.
02467   if (IsPartialSpecialization) {
02468     if (CheckTemplatePartialSpecializationArgs(
02469             *this, TemplateNameLoc, VarTemplate->getTemplateParameters(),
02470             TemplateArgs.size(), Converted))
02471       return true;
02472 
02473     bool InstantiationDependent;
02474     if (!Name.isDependent() &&
02475         !TemplateSpecializationType::anyDependentTemplateArguments(
02476             TemplateArgs.getArgumentArray(), TemplateArgs.size(),
02477             InstantiationDependent)) {
02478       Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
02479           << VarTemplate->getDeclName();
02480       IsPartialSpecialization = false;
02481     }
02482 
02483     if (isSameAsPrimaryTemplate(VarTemplate->getTemplateParameters(),
02484                                 Converted)) {
02485       // C++ [temp.class.spec]p9b3:
02486       //
02487       //   -- The argument list of the specialization shall not be identical
02488       //      to the implicit argument list of the primary template.
02489       Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
02490         << /*variable template*/ 1
02491         << /*is definition*/(SC != SC_Extern && !CurContext->isRecord())
02492         << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
02493       // FIXME: Recover from this by treating the declaration as a redeclaration
02494       // of the primary template.
02495       return true;
02496     }
02497   }
02498 
02499   void *InsertPos = nullptr;
02500   VarTemplateSpecializationDecl *PrevDecl = nullptr;
02501 
02502   if (IsPartialSpecialization)
02503     // FIXME: Template parameter list matters too
02504     PrevDecl = VarTemplate->findPartialSpecialization(Converted, InsertPos);
02505   else
02506     PrevDecl = VarTemplate->findSpecialization(Converted, InsertPos);
02507 
02508   VarTemplateSpecializationDecl *Specialization = nullptr;
02509 
02510   // Check whether we can declare a variable template specialization in
02511   // the current scope.
02512   if (CheckTemplateSpecializationScope(*this, VarTemplate, PrevDecl,
02513                                        TemplateNameLoc,
02514                                        IsPartialSpecialization))
02515     return true;
02516 
02517   if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
02518     // Since the only prior variable template specialization with these
02519     // arguments was referenced but not declared,  reuse that
02520     // declaration node as our own, updating its source location and
02521     // the list of outer template parameters to reflect our new declaration.
02522     Specialization = PrevDecl;
02523     Specialization->setLocation(TemplateNameLoc);
02524     PrevDecl = nullptr;
02525   } else if (IsPartialSpecialization) {
02526     // Create a new class template partial specialization declaration node.
02527     VarTemplatePartialSpecializationDecl *PrevPartial =
02528         cast_or_null<VarTemplatePartialSpecializationDecl>(PrevDecl);
02529     VarTemplatePartialSpecializationDecl *Partial =
02530         VarTemplatePartialSpecializationDecl::Create(
02531             Context, VarTemplate->getDeclContext(), TemplateKWLoc,
02532             TemplateNameLoc, TemplateParams, VarTemplate, DI->getType(), DI, SC,
02533             Converted.data(), Converted.size(), TemplateArgs);
02534 
02535     if (!PrevPartial)
02536       VarTemplate->AddPartialSpecialization(Partial, InsertPos);
02537     Specialization = Partial;
02538 
02539     // If we are providing an explicit specialization of a member variable
02540     // template specialization, make a note of that.
02541     if (PrevPartial && PrevPartial->getInstantiatedFromMember())
02542       PrevPartial->setMemberSpecialization();
02543 
02544     // Check that all of the template parameters of the variable template
02545     // partial specialization are deducible from the template
02546     // arguments. If not, this variable template partial specialization
02547     // will never be used.
02548     llvm::SmallBitVector DeducibleParams(TemplateParams->size());
02549     MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
02550                                TemplateParams->getDepth(), DeducibleParams);
02551 
02552     if (!DeducibleParams.all()) {
02553       unsigned NumNonDeducible =
02554           DeducibleParams.size() - DeducibleParams.count();
02555       Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
02556         << /*variable template*/ 1 << (NumNonDeducible > 1)
02557         << SourceRange(TemplateNameLoc, RAngleLoc);
02558       for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
02559         if (!DeducibleParams[I]) {
02560           NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
02561           if (Param->getDeclName())
02562             Diag(Param->getLocation(), diag::note_partial_spec_unused_parameter)
02563                 << Param->getDeclName();
02564           else
02565             Diag(Param->getLocation(), diag::note_partial_spec_unused_parameter)
02566                 << "(anonymous)";
02567         }
02568       }
02569     }
02570   } else {
02571     // Create a new class template specialization declaration node for
02572     // this explicit specialization or friend declaration.
02573     Specialization = VarTemplateSpecializationDecl::Create(
02574         Context, VarTemplate->getDeclContext(), TemplateKWLoc, TemplateNameLoc,
02575         VarTemplate, DI->getType(), DI, SC, Converted.data(), Converted.size());
02576     Specialization->setTemplateArgsInfo(TemplateArgs);
02577 
02578     if (!PrevDecl)
02579       VarTemplate->AddSpecialization(Specialization, InsertPos);
02580   }
02581 
02582   // C++ [temp.expl.spec]p6:
02583   //   If a template, a member template or the member of a class template is
02584   //   explicitly specialized then that specialization shall be declared
02585   //   before the first use of that specialization that would cause an implicit
02586   //   instantiation to take place, in every translation unit in which such a
02587   //   use occurs; no diagnostic is required.
02588   if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
02589     bool Okay = false;
02590     for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
02591       // Is there any previous explicit specialization declaration?
02592       if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
02593         Okay = true;
02594         break;
02595       }
02596     }
02597 
02598     if (!Okay) {
02599       SourceRange Range(TemplateNameLoc, RAngleLoc);
02600       Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
02601           << Name << Range;
02602 
02603       Diag(PrevDecl->getPointOfInstantiation(),
02604            diag::note_instantiation_required_here)
02605           << (PrevDecl->getTemplateSpecializationKind() !=
02606               TSK_ImplicitInstantiation);
02607       return true;
02608     }
02609   }
02610 
02611   Specialization->setTemplateKeywordLoc(TemplateKWLoc);
02612   Specialization->setLexicalDeclContext(CurContext);
02613 
02614   // Add the specialization into its lexical context, so that it can
02615   // be seen when iterating through the list of declarations in that
02616   // context. However, specializations are not found by name lookup.
02617   CurContext->addDecl(Specialization);
02618 
02619   // Note that this is an explicit specialization.
02620   Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
02621 
02622   if (PrevDecl) {
02623     // Check that this isn't a redefinition of this specialization,
02624     // merging with previous declarations.
02625     LookupResult PrevSpec(*this, GetNameForDeclarator(D), LookupOrdinaryName,
02626                           ForRedeclaration);
02627     PrevSpec.addDecl(PrevDecl);
02628     D.setRedeclaration(CheckVariableDeclaration(Specialization, PrevSpec));
02629   } else if (Specialization->isStaticDataMember() &&
02630              Specialization->isOutOfLine()) {
02631     Specialization->setAccess(VarTemplate->getAccess());
02632   }
02633 
02634   // Link instantiations of static data members back to the template from
02635   // which they were instantiated.
02636   if (Specialization->isStaticDataMember())
02637     Specialization->setInstantiationOfStaticDataMember(
02638         VarTemplate->getTemplatedDecl(),
02639         Specialization->getSpecializationKind());
02640 
02641   return Specialization;
02642 }
02643 
02644 namespace {
02645 /// \brief A partial specialization whose template arguments have matched
02646 /// a given template-id.
02647 struct PartialSpecMatchResult {
02648   VarTemplatePartialSpecializationDecl *Partial;
02649   TemplateArgumentList *Args;
02650 };
02651 }
02652 
02653 DeclResult
02654 Sema::CheckVarTemplateId(VarTemplateDecl *Template, SourceLocation TemplateLoc,
02655                          SourceLocation TemplateNameLoc,
02656                          const TemplateArgumentListInfo &TemplateArgs) {
02657   assert(Template && "A variable template id without template?");
02658 
02659   // Check that the template argument list is well-formed for this template.
02660   SmallVector<TemplateArgument, 4> Converted;
02661   if (CheckTemplateArgumentList(
02662           Template, TemplateNameLoc,
02663           const_cast<TemplateArgumentListInfo &>(TemplateArgs), false,
02664           Converted))
02665     return true;
02666 
02667   // Find the variable template specialization declaration that
02668   // corresponds to these arguments.
02669   void *InsertPos = nullptr;
02670   if (VarTemplateSpecializationDecl *Spec = Template->findSpecialization(
02671           Converted, InsertPos))
02672     // If we already have a variable template specialization, return it.
02673     return Spec;
02674 
02675   // This is the first time we have referenced this variable template
02676   // specialization. Create the canonical declaration and add it to
02677   // the set of specializations, based on the closest partial specialization
02678   // that it represents. That is,
02679   VarDecl *InstantiationPattern = Template->getTemplatedDecl();
02680   TemplateArgumentList TemplateArgList(TemplateArgumentList::OnStack,
02681                                        Converted.data(), Converted.size());
02682   TemplateArgumentList *InstantiationArgs = &TemplateArgList;
02683   bool AmbiguousPartialSpec = false;
02684   typedef PartialSpecMatchResult MatchResult;
02685   SmallVector<MatchResult, 4> Matched;
02686   SourceLocation PointOfInstantiation = TemplateNameLoc;
02687   TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation);
02688 
02689   // 1. Attempt to find the closest partial specialization that this
02690   // specializes, if any.
02691   // If any of the template arguments is dependent, then this is probably
02692   // a placeholder for an incomplete declarative context; which must be
02693   // complete by instantiation time. Thus, do not search through the partial
02694   // specializations yet.
02695   // TODO: Unify with InstantiateClassTemplateSpecialization()?
02696   //       Perhaps better after unification of DeduceTemplateArguments() and
02697   //       getMoreSpecializedPartialSpecialization().
02698   bool InstantiationDependent = false;
02699   if (!TemplateSpecializationType::anyDependentTemplateArguments(
02700           TemplateArgs, InstantiationDependent)) {
02701 
02702     SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs;
02703     Template->getPartialSpecializations(PartialSpecs);
02704 
02705     for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
02706       VarTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
02707       TemplateDeductionInfo Info(FailedCandidates.getLocation());
02708 
02709       if (TemplateDeductionResult Result =
02710               DeduceTemplateArguments(Partial, TemplateArgList, Info)) {
02711         // Store the failed-deduction information for use in diagnostics, later.
02712         // TODO: Actually use the failed-deduction info?
02713         FailedCandidates.addCandidate()
02714             .set(Partial, MakeDeductionFailureInfo(Context, Result, Info));
02715         (void)Result;
02716       } else {
02717         Matched.push_back(PartialSpecMatchResult());
02718         Matched.back().Partial = Partial;
02719         Matched.back().Args = Info.take();
02720       }
02721     }
02722 
02723     if (Matched.size() >= 1) {
02724       SmallVector<MatchResult, 4>::iterator Best = Matched.begin();
02725       if (Matched.size() == 1) {
02726         //   -- If exactly one matching specialization is found, the
02727         //      instantiation is generated from that specialization.
02728         // We don't need to do anything for this.
02729       } else {
02730         //   -- If more than one matching specialization is found, the
02731         //      partial order rules (14.5.4.2) are used to determine
02732         //      whether one of the specializations is more specialized
02733         //      than the others. If none of the specializations is more
02734         //      specialized than all of the other matching
02735         //      specializations, then the use of the variable template is
02736         //      ambiguous and the program is ill-formed.
02737         for (SmallVector<MatchResult, 4>::iterator P = Best + 1,
02738                                                    PEnd = Matched.end();
02739              P != PEnd; ++P) {
02740           if (getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
02741                                                       PointOfInstantiation) ==
02742               P->Partial)
02743             Best = P;
02744         }
02745 
02746         // Determine if the best partial specialization is more specialized than
02747         // the others.
02748         for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
02749                                                    PEnd = Matched.end();
02750              P != PEnd; ++P) {
02751           if (P != Best && getMoreSpecializedPartialSpecialization(
02752                                P->Partial, Best->Partial,
02753                                PointOfInstantiation) != Best->Partial) {
02754             AmbiguousPartialSpec = true;
02755             break;
02756           }
02757         }
02758       }
02759 
02760       // Instantiate using the best variable template partial specialization.
02761       InstantiationPattern = Best->Partial;
02762       InstantiationArgs = Best->Args;
02763     } else {
02764       //   -- If no match is found, the instantiation is generated
02765       //      from the primary template.
02766       // InstantiationPattern = Template->getTemplatedDecl();
02767     }
02768   }
02769 
02770   // 2. Create the canonical declaration.
02771   // Note that we do not instantiate the variable just yet, since
02772   // instantiation is handled in DoMarkVarDeclReferenced().
02773   // FIXME: LateAttrs et al.?
02774   VarTemplateSpecializationDecl *Decl = BuildVarTemplateInstantiation(
02775       Template, InstantiationPattern, *InstantiationArgs, TemplateArgs,
02776       Converted, TemplateNameLoc, InsertPos /*, LateAttrs, StartingScope*/);
02777   if (!Decl)
02778     return true;
02779 
02780   if (AmbiguousPartialSpec) {
02781     // Partial ordering did not produce a clear winner. Complain.
02782     Decl->setInvalidDecl();
02783     Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous)
02784         << Decl;
02785 
02786     // Print the matching partial specializations.
02787     for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
02788                                                PEnd = Matched.end();
02789          P != PEnd; ++P)
02790       Diag(P->Partial->getLocation(), diag::note_partial_spec_match)
02791           << getTemplateArgumentBindingsText(
02792                  P->Partial->getTemplateParameters(), *P->Args);
02793     return true;
02794   }
02795 
02796   if (VarTemplatePartialSpecializationDecl *D =
02797           dyn_cast<VarTemplatePartialSpecializationDecl>(InstantiationPattern))
02798     Decl->setInstantiationOf(D, InstantiationArgs);
02799 
02800   assert(Decl && "No variable template specialization?");
02801   return Decl;
02802 }
02803 
02804 ExprResult
02805 Sema::CheckVarTemplateId(const CXXScopeSpec &SS,
02806                          const DeclarationNameInfo &NameInfo,
02807                          VarTemplateDecl *Template, SourceLocation TemplateLoc,
02808                          const TemplateArgumentListInfo *TemplateArgs) {
02809 
02810   DeclResult Decl = CheckVarTemplateId(Template, TemplateLoc, NameInfo.getLoc(),
02811                                        *TemplateArgs);
02812   if (Decl.isInvalid())
02813     return ExprError();
02814 
02815   VarDecl *Var = cast<VarDecl>(Decl.get());
02816   if (!Var->getTemplateSpecializationKind())
02817     Var->setTemplateSpecializationKind(TSK_ImplicitInstantiation,
02818                                        NameInfo.getLoc());
02819 
02820   // Build an ordinary singleton decl ref.
02821   return BuildDeclarationNameExpr(SS, NameInfo, Var,
02822                                   /*FoundD=*/nullptr, TemplateArgs);
02823 }
02824 
02825 ExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,
02826                                      SourceLocation TemplateKWLoc,
02827                                      LookupResult &R,
02828                                      bool RequiresADL,
02829                                  const TemplateArgumentListInfo *TemplateArgs) {
02830   // FIXME: Can we do any checking at this point? I guess we could check the
02831   // template arguments that we have against the template name, if the template
02832   // name refers to a single template. That's not a terribly common case,
02833   // though.
02834   // foo<int> could identify a single function unambiguously
02835   // This approach does NOT work, since f<int>(1);
02836   // gets resolved prior to resorting to overload resolution
02837   // i.e., template<class T> void f(double);
02838   //       vs template<class T, class U> void f(U);
02839 
02840   // These should be filtered out by our callers.
02841   assert(!R.empty() && "empty lookup results when building templateid");
02842   assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
02843 
02844   // In C++1y, check variable template ids.
02845   bool InstantiationDependent;
02846   if (R.getAsSingle<VarTemplateDecl>() &&
02847       !TemplateSpecializationType::anyDependentTemplateArguments(
02848            *TemplateArgs, InstantiationDependent)) {
02849     return CheckVarTemplateId(SS, R.getLookupNameInfo(),
02850                               R.getAsSingle<VarTemplateDecl>(),
02851                               TemplateKWLoc, TemplateArgs);
02852   }
02853 
02854   // We don't want lookup warnings at this point.
02855   R.suppressDiagnostics();
02856 
02857   UnresolvedLookupExpr *ULE
02858     = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
02859                                    SS.getWithLocInContext(Context),
02860                                    TemplateKWLoc,
02861                                    R.getLookupNameInfo(),
02862                                    RequiresADL, TemplateArgs,
02863                                    R.begin(), R.end());
02864 
02865   return ULE;
02866 }
02867 
02868 // We actually only call this from template instantiation.
02869 ExprResult
02870 Sema::BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
02871                                    SourceLocation TemplateKWLoc,
02872                                    const DeclarationNameInfo &NameInfo,
02873                              const TemplateArgumentListInfo *TemplateArgs) {
02874 
02875   assert(TemplateArgs || TemplateKWLoc.isValid());
02876   DeclContext *DC;
02877   if (!(DC = computeDeclContext(SS, false)) ||
02878       DC->isDependentContext() ||
02879       RequireCompleteDeclContext(SS, DC))
02880     return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
02881 
02882   bool MemberOfUnknownSpecialization;
02883   LookupResult R(*this, NameInfo, LookupOrdinaryName);
02884   LookupTemplateName(R, (Scope*)nullptr, SS, QualType(), /*Entering*/ false,
02885                      MemberOfUnknownSpecialization);
02886 
02887   if (R.isAmbiguous())
02888     return ExprError();
02889 
02890   if (R.empty()) {
02891     Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_non_template)
02892       << NameInfo.getName() << SS.getRange();
02893     return ExprError();
02894   }
02895 
02896   if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>()) {
02897     Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_class_template)
02898       << SS.getScopeRep()
02899       << NameInfo.getName().getAsString() << SS.getRange();
02900     Diag(Temp->getLocation(), diag::note_referenced_class_template);
02901     return ExprError();
02902   }
02903 
02904   return BuildTemplateIdExpr(SS, TemplateKWLoc, R, /*ADL*/ false, TemplateArgs);
02905 }
02906 
02907 /// \brief Form a dependent template name.
02908 ///
02909 /// This action forms a dependent template name given the template
02910 /// name and its (presumably dependent) scope specifier. For
02911 /// example, given "MetaFun::template apply", the scope specifier \p
02912 /// SS will be "MetaFun::", \p TemplateKWLoc contains the location
02913 /// of the "template" keyword, and "apply" is the \p Name.
02914 TemplateNameKind Sema::ActOnDependentTemplateName(Scope *S,
02915                                                   CXXScopeSpec &SS,
02916                                                   SourceLocation TemplateKWLoc,
02917                                                   UnqualifiedId &Name,
02918                                                   ParsedType ObjectType,
02919                                                   bool EnteringContext,
02920                                                   TemplateTy &Result) {
02921   if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent())
02922     Diag(TemplateKWLoc,
02923          getLangOpts().CPlusPlus11 ?
02924            diag::warn_cxx98_compat_template_outside_of_template :
02925            diag::ext_template_outside_of_template)
02926       << FixItHint::CreateRemoval(TemplateKWLoc);
02927 
02928   DeclContext *LookupCtx = nullptr;
02929   if (SS.isSet())
02930     LookupCtx = computeDeclContext(SS, EnteringContext);
02931   if (!LookupCtx && ObjectType)
02932     LookupCtx = computeDeclContext(ObjectType.get());
02933   if (LookupCtx) {
02934     // C++0x [temp.names]p5:
02935     //   If a name prefixed by the keyword template is not the name of
02936     //   a template, the program is ill-formed. [Note: the keyword
02937     //   template may not be applied to non-template members of class
02938     //   templates. -end note ] [ Note: as is the case with the
02939     //   typename prefix, the template prefix is allowed in cases
02940     //   where it is not strictly necessary; i.e., when the
02941     //   nested-name-specifier or the expression on the left of the ->
02942     //   or . is not dependent on a template-parameter, or the use
02943     //   does not appear in the scope of a template. -end note]
02944     //
02945     // Note: C++03 was more strict here, because it banned the use of
02946     // the "template" keyword prior to a template-name that was not a
02947     // dependent name. C++ DR468 relaxed this requirement (the
02948     // "template" keyword is now permitted). We follow the C++0x
02949     // rules, even in C++03 mode with a warning, retroactively applying the DR.
02950     bool MemberOfUnknownSpecialization;
02951     TemplateNameKind TNK = isTemplateName(S, SS, TemplateKWLoc.isValid(), Name,
02952                                           ObjectType, EnteringContext, Result,
02953                                           MemberOfUnknownSpecialization);
02954     if (TNK == TNK_Non_template && LookupCtx->isDependentContext() &&
02955         isa<CXXRecordDecl>(LookupCtx) &&
02956         (!cast<CXXRecordDecl>(LookupCtx)->hasDefinition() ||
02957          cast<CXXRecordDecl>(LookupCtx)->hasAnyDependentBases())) {
02958       // This is a dependent template. Handle it below.
02959     } else if (TNK == TNK_Non_template) {
02960       Diag(Name.getLocStart(),
02961            diag::err_template_kw_refers_to_non_template)
02962         << GetNameFromUnqualifiedId(Name).getName()
02963         << Name.getSourceRange()
02964         << TemplateKWLoc;
02965       return TNK_Non_template;
02966     } else {
02967       // We found something; return it.
02968       return TNK;
02969     }
02970   }
02971 
02972   NestedNameSpecifier *Qualifier = SS.getScopeRep();
02973 
02974   switch (Name.getKind()) {
02975   case UnqualifiedId::IK_Identifier:
02976     Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
02977                                                               Name.Identifier));
02978     return TNK_Dependent_template_name;
02979 
02980   case UnqualifiedId::IK_OperatorFunctionId:
02981     Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
02982                                              Name.OperatorFunctionId.Operator));
02983     return TNK_Function_template;
02984 
02985   case UnqualifiedId::IK_LiteralOperatorId:
02986     llvm_unreachable("literal operator id cannot have a dependent scope");
02987 
02988   default:
02989     break;
02990   }
02991 
02992   Diag(Name.getLocStart(),
02993        diag::err_template_kw_refers_to_non_template)
02994     << GetNameFromUnqualifiedId(Name).getName()
02995     << Name.getSourceRange()
02996     << TemplateKWLoc;
02997   return TNK_Non_template;
02998 }
02999 
03000 bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
03001                                      TemplateArgumentLoc &AL,
03002                           SmallVectorImpl<TemplateArgument> &Converted) {
03003   const TemplateArgument &Arg = AL.getArgument();
03004   QualType ArgType;
03005   TypeSourceInfo *TSI = nullptr;
03006 
03007   // Check template type parameter.
03008   switch(Arg.getKind()) {
03009   case TemplateArgument::Type:
03010     // C++ [temp.arg.type]p1:
03011     //   A template-argument for a template-parameter which is a
03012     //   type shall be a type-id.
03013     ArgType = Arg.getAsType();
03014     TSI = AL.getTypeSourceInfo();
03015     break;
03016   case TemplateArgument::Template: {
03017     // We have a template type parameter but the template argument
03018     // is a template without any arguments.
03019     SourceRange SR = AL.getSourceRange();
03020     TemplateName Name = Arg.getAsTemplate();
03021     Diag(SR.getBegin(), diag::err_template_missing_args)
03022       << Name << SR;
03023     if (TemplateDecl *Decl = Name.getAsTemplateDecl())
03024       Diag(Decl->getLocation(), diag::note_template_decl_here);
03025 
03026     return true;
03027   }
03028   case TemplateArgument::Expression: {
03029     // We have a template type parameter but the template argument is an
03030     // expression; see if maybe it is missing the "typename" keyword.
03031     CXXScopeSpec SS;
03032     DeclarationNameInfo NameInfo;
03033 
03034     if (DeclRefExpr *ArgExpr = dyn_cast<DeclRefExpr>(Arg.getAsExpr())) {
03035       SS.Adopt(ArgExpr->getQualifierLoc());
03036       NameInfo = ArgExpr->getNameInfo();
03037     } else if (DependentScopeDeclRefExpr *ArgExpr =
03038                dyn_cast<DependentScopeDeclRefExpr>(Arg.getAsExpr())) {
03039       SS.Adopt(ArgExpr->getQualifierLoc());
03040       NameInfo = ArgExpr->getNameInfo();
03041     } else if (CXXDependentScopeMemberExpr *ArgExpr =
03042                dyn_cast<CXXDependentScopeMemberExpr>(Arg.getAsExpr())) {
03043       if (ArgExpr->isImplicitAccess()) {
03044         SS.Adopt(ArgExpr->getQualifierLoc());
03045         NameInfo = ArgExpr->getMemberNameInfo();
03046       }
03047     }
03048 
03049     if (auto *II = NameInfo.getName().getAsIdentifierInfo()) {
03050       LookupResult Result(*this, NameInfo, LookupOrdinaryName);
03051       LookupParsedName(Result, CurScope, &SS);
03052 
03053       if (Result.getAsSingle<TypeDecl>() ||
03054           Result.getResultKind() ==
03055               LookupResult::NotFoundInCurrentInstantiation) {
03056         // Suggest that the user add 'typename' before the NNS.
03057         SourceLocation Loc = AL.getSourceRange().getBegin();
03058         Diag(Loc, getLangOpts().MSVCCompat
03059                       ? diag::ext_ms_template_type_arg_missing_typename
03060                       : diag::err_template_arg_must_be_type_suggest)
03061             << FixItHint::CreateInsertion(Loc, "typename ");
03062         Diag(Param->getLocation(), diag::note_template_param_here);
03063 
03064         // Recover by synthesizing a type using the location information that we
03065         // already have.
03066         ArgType =
03067             Context.getDependentNameType(ETK_Typename, SS.getScopeRep(), II);
03068         TypeLocBuilder TLB;
03069         DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(ArgType);
03070         TL.setElaboratedKeywordLoc(SourceLocation(/*synthesized*/));
03071         TL.setQualifierLoc(SS.getWithLocInContext(Context));
03072         TL.setNameLoc(NameInfo.getLoc());
03073         TSI = TLB.getTypeSourceInfo(Context, ArgType);
03074 
03075         // Overwrite our input TemplateArgumentLoc so that we can recover
03076         // properly.
03077         AL = TemplateArgumentLoc(TemplateArgument(ArgType),
03078                                  TemplateArgumentLocInfo(TSI));
03079 
03080         break;
03081       }
03082     }
03083     // fallthrough
03084   }
03085   default: {
03086     // We have a template type parameter but the template argument
03087     // is not a type.
03088     SourceRange SR = AL.getSourceRange();
03089     Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
03090     Diag(Param->getLocation(), diag::note_template_param_here);
03091 
03092     return true;
03093   }
03094   }
03095 
03096   if (CheckTemplateArgument(Param, TSI))
03097     return true;
03098 
03099   // Add the converted template type argument.
03100   ArgType = Context.getCanonicalType(ArgType);
03101   
03102   // Objective-C ARC:
03103   //   If an explicitly-specified template argument type is a lifetime type
03104   //   with no lifetime qualifier, the __strong lifetime qualifier is inferred.
03105   if (getLangOpts().ObjCAutoRefCount &&
03106       ArgType->isObjCLifetimeType() &&
03107       !ArgType.getObjCLifetime()) {
03108     Qualifiers Qs;
03109     Qs.setObjCLifetime(Qualifiers::OCL_Strong);
03110     ArgType = Context.getQualifiedType(ArgType, Qs);
03111   }
03112   
03113   Converted.push_back(TemplateArgument(ArgType));
03114   return false;
03115 }
03116 
03117 /// \brief Substitute template arguments into the default template argument for
03118 /// the given template type parameter.
03119 ///
03120 /// \param SemaRef the semantic analysis object for which we are performing
03121 /// the substitution.
03122 ///
03123 /// \param Template the template that we are synthesizing template arguments
03124 /// for.
03125 ///
03126 /// \param TemplateLoc the location of the template name that started the
03127 /// template-id we are checking.
03128 ///
03129 /// \param RAngleLoc the location of the right angle bracket ('>') that
03130 /// terminates the template-id.
03131 ///
03132 /// \param Param the template template parameter whose default we are
03133 /// substituting into.
03134 ///
03135 /// \param Converted the list of template arguments provided for template
03136 /// parameters that precede \p Param in the template parameter list.
03137 /// \returns the substituted template argument, or NULL if an error occurred.
03138 static TypeSourceInfo *
03139 SubstDefaultTemplateArgument(Sema &SemaRef,
03140                              TemplateDecl *Template,
03141                              SourceLocation TemplateLoc,
03142                              SourceLocation RAngleLoc,
03143                              TemplateTypeParmDecl *Param,
03144                          SmallVectorImpl<TemplateArgument> &Converted) {
03145   TypeSourceInfo *ArgType = Param->getDefaultArgumentInfo();
03146 
03147   // If the argument type is dependent, instantiate it now based
03148   // on the previously-computed template arguments.
03149   if (ArgType->getType()->isDependentType()) {
03150     Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
03151                                      Template, Converted,
03152                                      SourceRange(TemplateLoc, RAngleLoc));
03153     if (Inst.isInvalid())
03154       return nullptr;
03155 
03156     TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
03157                                       Converted.data(), Converted.size());
03158 
03159     // Only substitute for the innermost template argument list.
03160     MultiLevelTemplateArgumentList TemplateArgLists;
03161     TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
03162     for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
03163       TemplateArgLists.addOuterTemplateArguments(None);
03164 
03165     Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
03166     ArgType =
03167         SemaRef.SubstType(ArgType, TemplateArgLists,
03168                           Param->getDefaultArgumentLoc(), Param->getDeclName());
03169   }
03170 
03171   return ArgType;
03172 }
03173 
03174 /// \brief Substitute template arguments into the default template argument for
03175 /// the given non-type template parameter.
03176 ///
03177 /// \param SemaRef the semantic analysis object for which we are performing
03178 /// the substitution.
03179 ///
03180 /// \param Template the template that we are synthesizing template arguments
03181 /// for.
03182 ///
03183 /// \param TemplateLoc the location of the template name that started the
03184 /// template-id we are checking.
03185 ///
03186 /// \param RAngleLoc the location of the right angle bracket ('>') that
03187 /// terminates the template-id.
03188 ///
03189 /// \param Param the non-type template parameter whose default we are
03190 /// substituting into.
03191 ///
03192 /// \param Converted the list of template arguments provided for template
03193 /// parameters that precede \p Param in the template parameter list.
03194 ///
03195 /// \returns the substituted template argument, or NULL if an error occurred.
03196 static ExprResult
03197 SubstDefaultTemplateArgument(Sema &SemaRef,
03198                              TemplateDecl *Template,
03199                              SourceLocation TemplateLoc,
03200                              SourceLocation RAngleLoc,
03201                              NonTypeTemplateParmDecl *Param,
03202                         SmallVectorImpl<TemplateArgument> &Converted) {
03203   Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
03204                                    Template, Converted,
03205                                    SourceRange(TemplateLoc, RAngleLoc));
03206   if (Inst.isInvalid())
03207     return ExprError();
03208 
03209   TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
03210                                     Converted.data(), Converted.size());
03211 
03212   // Only substitute for the innermost template argument list.
03213   MultiLevelTemplateArgumentList TemplateArgLists;
03214   TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
03215   for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
03216     TemplateArgLists.addOuterTemplateArguments(None);
03217 
03218   Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
03219   EnterExpressionEvaluationContext Unevaluated(SemaRef, Sema::Unevaluated);
03220   return SemaRef.SubstExpr(Param->getDefaultArgument(), TemplateArgLists);
03221 }
03222 
03223 /// \brief Substitute template arguments into the default template argument for
03224 /// the given template template parameter.
03225 ///
03226 /// \param SemaRef the semantic analysis object for which we are performing
03227 /// the substitution.
03228 ///
03229 /// \param Template the template that we are synthesizing template arguments
03230 /// for.
03231 ///
03232 /// \param TemplateLoc the location of the template name that started the
03233 /// template-id we are checking.
03234 ///
03235 /// \param RAngleLoc the location of the right angle bracket ('>') that
03236 /// terminates the template-id.
03237 ///
03238 /// \param Param the template template parameter whose default we are
03239 /// substituting into.
03240 ///
03241 /// \param Converted the list of template arguments provided for template
03242 /// parameters that precede \p Param in the template parameter list.
03243 ///
03244 /// \param QualifierLoc Will be set to the nested-name-specifier (with 
03245 /// source-location information) that precedes the template name.
03246 ///
03247 /// \returns the substituted template argument, or NULL if an error occurred.
03248 static TemplateName
03249 SubstDefaultTemplateArgument(Sema &SemaRef,
03250                              TemplateDecl *Template,
03251                              SourceLocation TemplateLoc,
03252                              SourceLocation RAngleLoc,
03253                              TemplateTemplateParmDecl *Param,
03254                        SmallVectorImpl<TemplateArgument> &Converted,
03255                              NestedNameSpecifierLoc &QualifierLoc) {
03256   Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc, Template, Converted,
03257                                    SourceRange(TemplateLoc, RAngleLoc));
03258   if (Inst.isInvalid())
03259     return TemplateName();
03260 
03261   TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
03262                                     Converted.data(), Converted.size());
03263 
03264   // Only substitute for the innermost template argument list.
03265   MultiLevelTemplateArgumentList TemplateArgLists;
03266   TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
03267   for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
03268     TemplateArgLists.addOuterTemplateArguments(None);
03269 
03270   Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
03271   // Substitute into the nested-name-specifier first,
03272   QualifierLoc = Param->getDefaultArgument().getTemplateQualifierLoc();
03273   if (QualifierLoc) {
03274     QualifierLoc =
03275         SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgLists);
03276     if (!QualifierLoc)
03277       return TemplateName();
03278   }
03279 
03280   return SemaRef.SubstTemplateName(
03281              QualifierLoc,
03282              Param->getDefaultArgument().getArgument().getAsTemplate(),
03283              Param->getDefaultArgument().getTemplateNameLoc(),
03284              TemplateArgLists);
03285 }
03286 
03287 /// \brief If the given template parameter has a default template
03288 /// argument, substitute into that default template argument and
03289 /// return the corresponding template argument.
03290 TemplateArgumentLoc
03291 Sema::SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
03292                                               SourceLocation TemplateLoc,
03293                                               SourceLocation RAngleLoc,
03294                                               Decl *Param,
03295                                               SmallVectorImpl<TemplateArgument>
03296                                                 &Converted,
03297                                               bool &HasDefaultArg) {
03298   HasDefaultArg = false;
03299 
03300   if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
03301     if (!TypeParm->hasDefaultArgument())
03302       return TemplateArgumentLoc();
03303 
03304     HasDefaultArg = true;
03305     TypeSourceInfo *DI = SubstDefaultTemplateArgument(*this, Template,
03306                                                       TemplateLoc,
03307                                                       RAngleLoc,
03308                                                       TypeParm,
03309                                                       Converted);
03310     if (DI)
03311       return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
03312 
03313     return TemplateArgumentLoc();
03314   }
03315 
03316   if (NonTypeTemplateParmDecl *NonTypeParm
03317         = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
03318     if (!NonTypeParm->hasDefaultArgument())
03319       return TemplateArgumentLoc();
03320 
03321     HasDefaultArg = true;
03322     ExprResult Arg = SubstDefaultTemplateArgument(*this, Template,
03323                                                   TemplateLoc,
03324                                                   RAngleLoc,
03325                                                   NonTypeParm,
03326                                                   Converted);
03327     if (Arg.isInvalid())
03328       return TemplateArgumentLoc();
03329 
03330     Expr *ArgE = Arg.getAs<Expr>();
03331     return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE);
03332   }
03333 
03334   TemplateTemplateParmDecl *TempTempParm
03335     = cast<TemplateTemplateParmDecl>(Param);
03336   if (!TempTempParm->hasDefaultArgument())
03337     return TemplateArgumentLoc();
03338 
03339   HasDefaultArg = true;
03340   NestedNameSpecifierLoc QualifierLoc;
03341   TemplateName TName = SubstDefaultTemplateArgument(*this, Template,
03342                                                     TemplateLoc,
03343                                                     RAngleLoc,
03344                                                     TempTempParm,
03345                                                     Converted,
03346                                                     QualifierLoc);
03347   if (TName.isNull())
03348     return TemplateArgumentLoc();
03349 
03350   return TemplateArgumentLoc(TemplateArgument(TName),
03351                 TempTempParm->getDefaultArgument().getTemplateQualifierLoc(),
03352                 TempTempParm->getDefaultArgument().getTemplateNameLoc());
03353 }
03354 
03355 /// \brief Check that the given template argument corresponds to the given
03356 /// template parameter.
03357 ///
03358 /// \param Param The template parameter against which the argument will be
03359 /// checked.
03360 ///
03361 /// \param Arg The template argument.
03362 ///
03363 /// \param Template The template in which the template argument resides.
03364 ///
03365 /// \param TemplateLoc The location of the template name for the template
03366 /// whose argument list we're matching.
03367 ///
03368 /// \param RAngleLoc The location of the right angle bracket ('>') that closes
03369 /// the template argument list.
03370 ///
03371 /// \param ArgumentPackIndex The index into the argument pack where this
03372 /// argument will be placed. Only valid if the parameter is a parameter pack.
03373 ///
03374 /// \param Converted The checked, converted argument will be added to the
03375 /// end of this small vector.
03376 ///
03377 /// \param CTAK Describes how we arrived at this particular template argument:
03378 /// explicitly written, deduced, etc.
03379 ///
03380 /// \returns true on error, false otherwise.
03381 bool Sema::CheckTemplateArgument(NamedDecl *Param,
03382                                  TemplateArgumentLoc &Arg,
03383                                  NamedDecl *Template,
03384                                  SourceLocation TemplateLoc,
03385                                  SourceLocation RAngleLoc,
03386                                  unsigned ArgumentPackIndex,
03387                             SmallVectorImpl<TemplateArgument> &Converted,
03388                                  CheckTemplateArgumentKind CTAK) {
03389   // Check template type parameters.
03390   if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
03391     return CheckTemplateTypeArgument(TTP, Arg, Converted);
03392 
03393   // Check non-type template parameters.
03394   if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
03395     // Do substitution on the type of the non-type template parameter
03396     // with the template arguments we've seen thus far.  But if the
03397     // template has a dependent context then we cannot substitute yet.
03398     QualType NTTPType = NTTP->getType();
03399     if (NTTP->isParameterPack() && NTTP->isExpandedParameterPack())
03400       NTTPType = NTTP->getExpansionType(ArgumentPackIndex);
03401 
03402     if (NTTPType->isDependentType() &&
03403         !isa<TemplateTemplateParmDecl>(Template) &&
03404         !Template->getDeclContext()->isDependentContext()) {
03405       // Do substitution on the type of the non-type template parameter.
03406       InstantiatingTemplate Inst(*this, TemplateLoc, Template,
03407                                  NTTP, Converted,
03408                                  SourceRange(TemplateLoc, RAngleLoc));
03409       if (Inst.isInvalid())
03410         return true;
03411 
03412       TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
03413                                         Converted.data(), Converted.size());
03414       NTTPType = SubstType(NTTPType,
03415                            MultiLevelTemplateArgumentList(TemplateArgs),
03416                            NTTP->getLocation(),
03417                            NTTP->getDeclName());
03418       // If that worked, check the non-type template parameter type
03419       // for validity.
03420       if (!NTTPType.isNull())
03421         NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
03422                                                      NTTP->getLocation());
03423       if (NTTPType.isNull())
03424         return true;
03425     }
03426 
03427     switch (Arg.getArgument().getKind()) {
03428     case TemplateArgument::Null:
03429       llvm_unreachable("Should never see a NULL template argument here");
03430 
03431     case TemplateArgument::Expression: {
03432       TemplateArgument Result;
03433       ExprResult Res =
03434         CheckTemplateArgument(NTTP, NTTPType, Arg.getArgument().getAsExpr(),
03435                               Result, CTAK);
03436       if (Res.isInvalid())
03437         return true;
03438 
03439       Converted.push_back(Result);
03440       break;
03441     }
03442 
03443     case TemplateArgument::Declaration:
03444     case TemplateArgument::Integral:
03445     case TemplateArgument::NullPtr:
03446       // We've already checked this template argument, so just copy
03447       // it to the list of converted arguments.
03448       Converted.push_back(Arg.getArgument());
03449       break;
03450 
03451     case TemplateArgument::Template:
03452     case TemplateArgument::TemplateExpansion:
03453       // We were given a template template argument. It may not be ill-formed;
03454       // see below.
03455       if (DependentTemplateName *DTN
03456             = Arg.getArgument().getAsTemplateOrTemplatePattern()
03457                                               .getAsDependentTemplateName()) {
03458         // We have a template argument such as \c T::template X, which we
03459         // parsed as a template template argument. However, since we now
03460         // know that we need a non-type template argument, convert this
03461         // template name into an expression.
03462 
03463         DeclarationNameInfo NameInfo(DTN->getIdentifier(),
03464                                      Arg.getTemplateNameLoc());
03465 
03466         CXXScopeSpec SS;
03467         SS.Adopt(Arg.getTemplateQualifierLoc());
03468         // FIXME: the template-template arg was a DependentTemplateName,
03469         // so it was provided with a template keyword. However, its source
03470         // location is not stored in the template argument structure.
03471         SourceLocation TemplateKWLoc;
03472         ExprResult E = DependentScopeDeclRefExpr::Create(
03473             Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
03474             nullptr);
03475 
03476         // If we parsed the template argument as a pack expansion, create a
03477         // pack expansion expression.
03478         if (Arg.getArgument().getKind() == TemplateArgument::TemplateExpansion){
03479           E = ActOnPackExpansion(E.get(), Arg.getTemplateEllipsisLoc());
03480           if (E.isInvalid())
03481             return true;
03482         }
03483 
03484         TemplateArgument Result;
03485         E = CheckTemplateArgument(NTTP, NTTPType, E.get(), Result);
03486         if (E.isInvalid())
03487           return true;
03488 
03489         Converted.push_back(Result);
03490         break;
03491       }
03492 
03493       // We have a template argument that actually does refer to a class
03494       // template, alias template, or template template parameter, and
03495       // therefore cannot be a non-type template argument.
03496       Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
03497         << Arg.getSourceRange();
03498 
03499       Diag(Param->getLocation(), diag::note_template_param_here);
03500       return true;
03501 
03502     case TemplateArgument::Type: {
03503       // We have a non-type template parameter but the template
03504       // argument is a type.
03505 
03506       // C++ [temp.arg]p2:
03507       //   In a template-argument, an ambiguity between a type-id and
03508       //   an expression is resolved to a type-id, regardless of the
03509       //   form of the corresponding template-parameter.
03510       //
03511       // We warn specifically about this case, since it can be rather
03512       // confusing for users.
03513       QualType T = Arg.getArgument().getAsType();
03514       SourceRange SR = Arg.getSourceRange();
03515       if (T->isFunctionType())
03516         Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
03517       else
03518         Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
03519       Diag(Param->getLocation(), diag::note_template_param_here);
03520       return true;
03521     }
03522 
03523     case TemplateArgument::Pack:
03524       llvm_unreachable("Caller must expand template argument packs");
03525     }
03526 
03527     return false;
03528   }
03529 
03530 
03531   // Check template template parameters.
03532   TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
03533 
03534   // Substitute into the template parameter list of the template
03535   // template parameter, since previously-supplied template arguments
03536   // may appear within the template template parameter.
03537   {
03538     // Set up a template instantiation context.
03539     LocalInstantiationScope Scope(*this);
03540     InstantiatingTemplate Inst(*this, TemplateLoc, Template,
03541                                TempParm, Converted,
03542                                SourceRange(TemplateLoc, RAngleLoc));
03543     if (Inst.isInvalid())
03544       return true;
03545 
03546     TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
03547                                       Converted.data(), Converted.size());
03548     TempParm = cast_or_null<TemplateTemplateParmDecl>(
03549                       SubstDecl(TempParm, CurContext,
03550                                 MultiLevelTemplateArgumentList(TemplateArgs)));
03551     if (!TempParm)
03552       return true;
03553   }
03554 
03555   switch (Arg.getArgument().getKind()) {
03556   case TemplateArgument::Null:
03557     llvm_unreachable("Should never see a NULL template argument here");
03558 
03559   case TemplateArgument::Template:
03560   case TemplateArgument::TemplateExpansion:
03561     if (CheckTemplateArgument(TempParm, Arg, ArgumentPackIndex))
03562       return true;
03563 
03564     Converted.push_back(Arg.getArgument());
03565     break;
03566 
03567   case TemplateArgument::Expression:
03568   case TemplateArgument::Type:
03569     // We have a template template parameter but the template
03570     // argument does not refer to a template.
03571     Diag(Arg.getLocation(), diag::err_template_arg_must_be_template)
03572       << getLangOpts().CPlusPlus11;
03573     return true;
03574 
03575   case TemplateArgument::Declaration:
03576     llvm_unreachable("Declaration argument with template template parameter");
03577   case TemplateArgument::Integral:
03578     llvm_unreachable("Integral argument with template template parameter");
03579   case TemplateArgument::NullPtr:
03580     llvm_unreachable("Null pointer argument with template template parameter");
03581 
03582   case TemplateArgument::Pack:
03583     llvm_unreachable("Caller must expand template argument packs");
03584   }
03585 
03586   return false;
03587 }
03588 
03589 /// \brief Diagnose an arity mismatch in the 
03590 static bool diagnoseArityMismatch(Sema &S, TemplateDecl *Template,
03591                                   SourceLocation TemplateLoc,
03592                                   TemplateArgumentListInfo &TemplateArgs) {
03593   TemplateParameterList *Params = Template->getTemplateParameters();
03594   unsigned NumParams = Params->size();
03595   unsigned NumArgs = TemplateArgs.size();
03596 
03597   SourceRange Range;
03598   if (NumArgs > NumParams)
03599     Range = SourceRange(TemplateArgs[NumParams].getLocation(), 
03600                         TemplateArgs.getRAngleLoc());
03601   S.Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
03602     << (NumArgs > NumParams)
03603     << (isa<ClassTemplateDecl>(Template)? 0 :
03604         isa<FunctionTemplateDecl>(Template)? 1 :
03605         isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
03606     << Template << Range;
03607   S.Diag(Template->getLocation(), diag::note_template_decl_here)
03608     << Params->getSourceRange();
03609   return true;
03610 }
03611 
03612 /// \brief Check whether the template parameter is a pack expansion, and if so,
03613 /// determine the number of parameters produced by that expansion. For instance:
03614 ///
03615 /// \code
03616 /// template<typename ...Ts> struct A {
03617 ///   template<Ts ...NTs, template<Ts> class ...TTs, typename ...Us> struct B;
03618 /// };
03619 /// \endcode
03620 ///
03621 /// In \c A<int,int>::B, \c NTs and \c TTs have expanded pack size 2, and \c Us
03622 /// is not a pack expansion, so returns an empty Optional.
03623 static Optional<unsigned> getExpandedPackSize(NamedDecl *Param) {
03624   if (NonTypeTemplateParmDecl *NTTP
03625         = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
03626     if (NTTP->isExpandedParameterPack())
03627       return NTTP->getNumExpansionTypes();
03628   }
03629 
03630   if (TemplateTemplateParmDecl *TTP
03631         = dyn_cast<TemplateTemplateParmDecl>(Param)) {
03632     if (TTP->isExpandedParameterPack())
03633       return TTP->getNumExpansionTemplateParameters();
03634   }
03635 
03636   return None;
03637 }
03638 
03639 /// \brief Check that the given template argument list is well-formed
03640 /// for specializing the given template.
03641 bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
03642                                      SourceLocation TemplateLoc,
03643                                      TemplateArgumentListInfo &TemplateArgs,
03644                                      bool PartialTemplateArgs,
03645                           SmallVectorImpl<TemplateArgument> &Converted) {
03646   TemplateParameterList *Params = Template->getTemplateParameters();
03647 
03648   SourceLocation RAngleLoc = TemplateArgs.getRAngleLoc();
03649 
03650   // C++ [temp.arg]p1:
03651   //   [...] The type and form of each template-argument specified in
03652   //   a template-id shall match the type and form specified for the
03653   //   corresponding parameter declared by the template in its
03654   //   template-parameter-list.
03655   bool isTemplateTemplateParameter = isa<TemplateTemplateParmDecl>(Template);
03656   SmallVector<TemplateArgument, 2> ArgumentPack;
03657   unsigned ArgIdx = 0, NumArgs = TemplateArgs.size();
03658   LocalInstantiationScope InstScope(*this, true);
03659   for (TemplateParameterList::iterator Param = Params->begin(),
03660                                        ParamEnd = Params->end();
03661        Param != ParamEnd; /* increment in loop */) {
03662     // If we have an expanded parameter pack, make sure we don't have too
03663     // many arguments.
03664     if (Optional<unsigned> Expansions = getExpandedPackSize(*Param)) {
03665       if (*Expansions == ArgumentPack.size()) {
03666         // We're done with this parameter pack. Pack up its arguments and add
03667         // them to the list.
03668         Converted.push_back(
03669           TemplateArgument::CreatePackCopy(Context,
03670                                            ArgumentPack.data(),
03671                                            ArgumentPack.size()));
03672         ArgumentPack.clear();
03673 
03674         // This argument is assigned to the next parameter.
03675         ++Param;
03676         continue;
03677       } else if (ArgIdx == NumArgs && !PartialTemplateArgs) {
03678         // Not enough arguments for this parameter pack.
03679         Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
03680           << false
03681           << (isa<ClassTemplateDecl>(Template)? 0 :
03682               isa<FunctionTemplateDecl>(Template)? 1 :
03683               isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
03684           << Template;
03685         Diag(Template->getLocation(), diag::note_template_decl_here)
03686           << Params->getSourceRange();
03687         return true;
03688       }
03689     }
03690 
03691     if (ArgIdx < NumArgs) {
03692       // Check the template argument we were given.
03693       if (CheckTemplateArgument(*Param, TemplateArgs[ArgIdx], Template,
03694                                 TemplateLoc, RAngleLoc,
03695                                 ArgumentPack.size(), Converted))
03696         return true;
03697 
03698       bool PackExpansionIntoNonPack =
03699           TemplateArgs[ArgIdx].getArgument().isPackExpansion() &&
03700           (!(*Param)->isTemplateParameterPack() || getExpandedPackSize(*Param));
03701       if (PackExpansionIntoNonPack && isa<TypeAliasTemplateDecl>(Template)) {
03702         // Core issue 1430: we have a pack expansion as an argument to an
03703         // alias template, and it's not part of a parameter pack. This
03704         // can't be canonicalized, so reject it now.
03705         Diag(TemplateArgs[ArgIdx].getLocation(),
03706              diag::err_alias_template_expansion_into_fixed_list)
03707           << TemplateArgs[ArgIdx].getSourceRange();
03708         Diag((*Param)->getLocation(), diag::note_template_param_here);
03709         return true;
03710       }
03711 
03712       // We're now done with this argument.
03713       ++ArgIdx;
03714 
03715       if ((*Param)->isTemplateParameterPack()) {
03716         // The template parameter was a template parameter pack, so take the
03717         // deduced argument and place it on the argument pack. Note that we
03718         // stay on the same template parameter so that we can deduce more
03719         // arguments.
03720         ArgumentPack.push_back(Converted.pop_back_val());
03721       } else {
03722         // Move to the next template parameter.
03723         ++Param;
03724       }
03725 
03726       // If we just saw a pack expansion into a non-pack, then directly convert
03727       // the remaining arguments, because we don't know what parameters they'll
03728       // match up with.
03729       if (PackExpansionIntoNonPack) {
03730         if (!ArgumentPack.empty()) {
03731           // If we were part way through filling in an expanded parameter pack,
03732           // fall back to just producing individual arguments.
03733           Converted.insert(Converted.end(),
03734                            ArgumentPack.begin(), ArgumentPack.end());
03735           ArgumentPack.clear();
03736         }
03737 
03738         while (ArgIdx < NumArgs) {
03739           Converted.push_back(TemplateArgs[ArgIdx].getArgument());
03740           ++ArgIdx;
03741         }
03742 
03743         return false;
03744       }
03745 
03746       continue;
03747     }
03748 
03749     // If we're checking a partial template argument list, we're done.
03750     if (PartialTemplateArgs) {
03751       if ((*Param)->isTemplateParameterPack() && !ArgumentPack.empty())
03752         Converted.push_back(TemplateArgument::CreatePackCopy(Context,
03753                                                          ArgumentPack.data(),
03754                                                          ArgumentPack.size()));
03755         
03756       return false;
03757     }
03758 
03759     // If we have a template parameter pack with no more corresponding
03760     // arguments, just break out now and we'll fill in the argument pack below.
03761     if ((*Param)->isTemplateParameterPack()) {
03762       assert(!getExpandedPackSize(*Param) &&
03763              "Should have dealt with this already");
03764 
03765       // A non-expanded parameter pack before the end of the parameter list
03766       // only occurs for an ill-formed template parameter list, unless we've
03767       // got a partial argument list for a function template, so just bail out.
03768       if (Param + 1 != ParamEnd)
03769         return true;
03770 
03771       Converted.push_back(TemplateArgument::CreatePackCopy(Context,
03772                                                        ArgumentPack.data(),
03773                                                        ArgumentPack.size()));
03774       ArgumentPack.clear();
03775 
03776       ++Param;
03777       continue;
03778     }
03779 
03780     // Check whether we have a default argument.
03781     TemplateArgumentLoc Arg;
03782 
03783     // Retrieve the default template argument from the template
03784     // parameter. For each kind of template parameter, we substitute the
03785     // template arguments provided thus far and any "outer" template arguments
03786     // (when the template parameter was part of a nested template) into
03787     // the default argument.
03788     if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
03789       if (!TTP->hasDefaultArgument())
03790         return diagnoseArityMismatch(*this, Template, TemplateLoc, 
03791                                      TemplateArgs);
03792 
03793       TypeSourceInfo *ArgType = SubstDefaultTemplateArgument(*this,
03794                                                              Template,
03795                                                              TemplateLoc,
03796                                                              RAngleLoc,
03797                                                              TTP,
03798                                                              Converted);
03799       if (!ArgType)
03800         return true;
03801 
03802       Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()),
03803                                 ArgType);
03804     } else if (NonTypeTemplateParmDecl *NTTP
03805                  = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
03806       if (!NTTP->hasDefaultArgument())
03807         return diagnoseArityMismatch(*this, Template, TemplateLoc, 
03808                                      TemplateArgs);
03809 
03810       ExprResult E = SubstDefaultTemplateArgument(*this, Template,
03811                                                               TemplateLoc,
03812                                                               RAngleLoc,
03813                                                               NTTP,
03814                                                               Converted);
03815       if (E.isInvalid())
03816         return true;
03817 
03818       Expr *Ex = E.getAs<Expr>();
03819       Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
03820     } else {
03821       TemplateTemplateParmDecl *TempParm
03822         = cast<TemplateTemplateParmDecl>(*Param);
03823 
03824       if (!TempParm->hasDefaultArgument())
03825         return diagnoseArityMismatch(*this, Template, TemplateLoc, 
03826                                      TemplateArgs);
03827 
03828       NestedNameSpecifierLoc QualifierLoc;
03829       TemplateName Name = SubstDefaultTemplateArgument(*this, Template,
03830                                                        TemplateLoc,
03831                                                        RAngleLoc,
03832                                                        TempParm,
03833                                                        Converted,
03834                                                        QualifierLoc);
03835       if (Name.isNull())
03836         return true;
03837 
03838       Arg = TemplateArgumentLoc(TemplateArgument(Name), QualifierLoc,
03839                            TempParm->getDefaultArgument().getTemplateNameLoc());
03840     }
03841 
03842     // Introduce an instantiation record that describes where we are using
03843     // the default template argument.
03844     InstantiatingTemplate Inst(*this, RAngleLoc, Template, *Param, Converted,
03845                                SourceRange(TemplateLoc, RAngleLoc));
03846     if (Inst.isInvalid())
03847       return true;
03848 
03849     // Check the default template argument.
03850     if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc,
03851                               RAngleLoc, 0, Converted))
03852       return true;
03853 
03854     // Core issue 150 (assumed resolution): if this is a template template 
03855     // parameter, keep track of the default template arguments from the 
03856     // template definition.
03857     if (isTemplateTemplateParameter)
03858       TemplateArgs.addArgument(Arg);
03859     
03860     // Move to the next template parameter and argument.
03861     ++Param;
03862     ++ArgIdx;
03863   }
03864 
03865   // If we're performing a partial argument substitution, allow any trailing
03866   // pack expansions; they might be empty. This can happen even if
03867   // PartialTemplateArgs is false (the list of arguments is complete but
03868   // still dependent).
03869   if (ArgIdx < NumArgs && CurrentInstantiationScope &&
03870       CurrentInstantiationScope->getPartiallySubstitutedPack()) {
03871     while (ArgIdx < NumArgs &&
03872            TemplateArgs[ArgIdx].getArgument().isPackExpansion())
03873       Converted.push_back(TemplateArgs[ArgIdx++].getArgument());
03874   }
03875 
03876   // If we have any leftover arguments, then there were too many arguments.
03877   // Complain and fail.
03878   if (ArgIdx < NumArgs)
03879     return diagnoseArityMismatch(*this, Template, TemplateLoc, TemplateArgs);
03880 
03881   return false;
03882 }
03883 
03884 namespace {
03885   class UnnamedLocalNoLinkageFinder
03886     : public TypeVisitor<UnnamedLocalNoLinkageFinder, bool>
03887   {
03888     Sema &S;
03889     SourceRange SR;
03890 
03891     typedef TypeVisitor<UnnamedLocalNoLinkageFinder, bool> inherited;
03892 
03893   public:
03894     UnnamedLocalNoLinkageFinder(Sema &S, SourceRange SR) : S(S), SR(SR) { }
03895 
03896     bool Visit(QualType T) {
03897       return inherited::Visit(T.getTypePtr());
03898     }
03899 
03900 #define TYPE(Class, Parent) \
03901     bool Visit##Class##Type(const Class##Type *);
03902 #define ABSTRACT_TYPE(Class, Parent) \
03903     bool Visit##Class##Type(const Class##Type *) { return false; }
03904 #define NON_CANONICAL_TYPE(Class, Parent) \
03905     bool Visit##Class##Type(const Class##Type *) { return false; }
03906 #include "clang/AST/TypeNodes.def"
03907 
03908     bool VisitTagDecl(const TagDecl *Tag);
03909     bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS);
03910   };
03911 }
03912 
03913 bool UnnamedLocalNoLinkageFinder::VisitBuiltinType(const BuiltinType*) {
03914   return false;
03915 }
03916 
03917 bool UnnamedLocalNoLinkageFinder::VisitComplexType(const ComplexType* T) {
03918   return Visit(T->getElementType());
03919 }
03920 
03921 bool UnnamedLocalNoLinkageFinder::VisitPointerType(const PointerType* T) {
03922   return Visit(T->getPointeeType());
03923 }
03924 
03925 bool UnnamedLocalNoLinkageFinder::VisitBlockPointerType(
03926                                                     const BlockPointerType* T) {
03927   return Visit(T->getPointeeType());
03928 }
03929 
03930 bool UnnamedLocalNoLinkageFinder::VisitLValueReferenceType(
03931                                                 const LValueReferenceType* T) {
03932   return Visit(T->getPointeeType());
03933 }
03934 
03935 bool UnnamedLocalNoLinkageFinder::VisitRValueReferenceType(
03936                                                 const RValueReferenceType* T) {
03937   return Visit(T->getPointeeType());
03938 }
03939 
03940 bool UnnamedLocalNoLinkageFinder::VisitMemberPointerType(
03941                                                   const MemberPointerType* T) {
03942   return Visit(T->getPointeeType()) || Visit(QualType(T->getClass(), 0));
03943 }
03944 
03945 bool UnnamedLocalNoLinkageFinder::VisitConstantArrayType(
03946                                                   const ConstantArrayType* T) {
03947   return Visit(T->getElementType());
03948 }
03949 
03950 bool UnnamedLocalNoLinkageFinder::VisitIncompleteArrayType(
03951                                                  const IncompleteArrayType* T) {
03952   return Visit(T->getElementType());
03953 }
03954 
03955 bool UnnamedLocalNoLinkageFinder::VisitVariableArrayType(
03956                                                    const VariableArrayType* T) {
03957   return Visit(T->getElementType());
03958 }
03959 
03960 bool UnnamedLocalNoLinkageFinder::VisitDependentSizedArrayType(
03961                                             const DependentSizedArrayType* T) {
03962   return Visit(T->getElementType());
03963 }
03964 
03965 bool UnnamedLocalNoLinkageFinder::VisitDependentSizedExtVectorType(
03966                                          const DependentSizedExtVectorType* T) {
03967   return Visit(T->getElementType());
03968 }
03969 
03970 bool UnnamedLocalNoLinkageFinder::VisitVectorType(const VectorType* T) {
03971   return Visit(T->getElementType());
03972 }
03973 
03974 bool UnnamedLocalNoLinkageFinder::VisitExtVectorType(const ExtVectorType* T) {
03975   return Visit(T->getElementType());
03976 }
03977 
03978 bool UnnamedLocalNoLinkageFinder::VisitFunctionProtoType(
03979                                                   const FunctionProtoType* T) {
03980   for (const auto &A : T->param_types()) {
03981     if (Visit(A))
03982       return true;
03983   }
03984 
03985   return Visit(T->getReturnType());
03986 }
03987 
03988 bool UnnamedLocalNoLinkageFinder::VisitFunctionNoProtoType(
03989                                                const FunctionNoProtoType* T) {
03990   return Visit(T->getReturnType());
03991 }
03992 
03993 bool UnnamedLocalNoLinkageFinder::VisitUnresolvedUsingType(
03994                                                   const UnresolvedUsingType*) {
03995   return false;
03996 }
03997 
03998 bool UnnamedLocalNoLinkageFinder::VisitTypeOfExprType(const TypeOfExprType*) {
03999   return false;
04000 }
04001 
04002 bool UnnamedLocalNoLinkageFinder::VisitTypeOfType(const TypeOfType* T) {
04003   return Visit(T->getUnderlyingType());
04004 }
04005 
04006 bool UnnamedLocalNoLinkageFinder::VisitDecltypeType(const DecltypeType*) {
04007   return false;
04008 }
04009 
04010 bool UnnamedLocalNoLinkageFinder::VisitUnaryTransformType(
04011                                                     const UnaryTransformType*) {
04012   return false;
04013 }
04014 
04015 bool UnnamedLocalNoLinkageFinder::VisitAutoType(const AutoType *T) {
04016   return Visit(T->getDeducedType());
04017 }
04018 
04019 bool UnnamedLocalNoLinkageFinder::VisitRecordType(const RecordType* T) {
04020   return VisitTagDecl(T->getDecl());
04021 }
04022 
04023 bool UnnamedLocalNoLinkageFinder::VisitEnumType(const EnumType* T) {
04024   return VisitTagDecl(T->getDecl());
04025 }
04026 
04027 bool UnnamedLocalNoLinkageFinder::VisitTemplateTypeParmType(
04028                                                  const TemplateTypeParmType*) {
04029   return false;
04030 }
04031 
04032 bool UnnamedLocalNoLinkageFinder::VisitSubstTemplateTypeParmPackType(
04033                                         const SubstTemplateTypeParmPackType *) {
04034   return false;
04035 }
04036 
04037 bool UnnamedLocalNoLinkageFinder::VisitTemplateSpecializationType(
04038                                             const TemplateSpecializationType*) {
04039   return false;
04040 }
04041 
04042 bool UnnamedLocalNoLinkageFinder::VisitInjectedClassNameType(
04043                                               const InjectedClassNameType* T) {
04044   return VisitTagDecl(T->getDecl());
04045 }
04046 
04047 bool UnnamedLocalNoLinkageFinder::VisitDependentNameType(
04048                                                    const DependentNameType* T) {
04049   return VisitNestedNameSpecifier(T->getQualifier());
04050 }
04051 
04052 bool UnnamedLocalNoLinkageFinder::VisitDependentTemplateSpecializationType(
04053                                  const DependentTemplateSpecializationType* T) {
04054   return VisitNestedNameSpecifier(T->getQualifier());
04055 }
04056 
04057 bool UnnamedLocalNoLinkageFinder::VisitPackExpansionType(
04058                                                    const PackExpansionType* T) {
04059   return Visit(T->getPattern());
04060 }
04061 
04062 bool UnnamedLocalNoLinkageFinder::VisitObjCObjectType(const ObjCObjectType *) {
04063   return false;
04064 }
04065 
04066 bool UnnamedLocalNoLinkageFinder::VisitObjCInterfaceType(
04067                                                    const ObjCInterfaceType *) {
04068   return false;
04069 }
04070 
04071 bool UnnamedLocalNoLinkageFinder::VisitObjCObjectPointerType(
04072                                                 const ObjCObjectPointerType *) {
04073   return false;
04074 }
04075 
04076 bool UnnamedLocalNoLinkageFinder::VisitAtomicType(const AtomicType* T) {
04077   return Visit(T->getValueType());
04078 }
04079 
04080 bool UnnamedLocalNoLinkageFinder::VisitTagDecl(const TagDecl *Tag) {
04081   if (Tag->getDeclContext()->isFunctionOrMethod()) {
04082     S.Diag(SR.getBegin(),
04083            S.getLangOpts().CPlusPlus11 ?
04084              diag::warn_cxx98_compat_template_arg_local_type :
04085              diag::ext_template_arg_local_type)
04086       << S.Context.getTypeDeclType(Tag) << SR;
04087     return true;
04088   }
04089 
04090   if (!Tag->hasNameForLinkage()) {
04091     S.Diag(SR.getBegin(),
04092            S.getLangOpts().CPlusPlus11 ?
04093              diag::warn_cxx98_compat_template_arg_unnamed_type :
04094              diag::ext_template_arg_unnamed_type) << SR;
04095     S.Diag(Tag->getLocation(), diag::note_template_unnamed_type_here);
04096     return true;
04097   }
04098 
04099   return false;
04100 }
04101 
04102 bool UnnamedLocalNoLinkageFinder::VisitNestedNameSpecifier(
04103                                                     NestedNameSpecifier *NNS) {
04104   if (NNS->getPrefix() && VisitNestedNameSpecifier(NNS->getPrefix()))
04105     return true;
04106 
04107   switch (NNS->getKind()) {
04108   case NestedNameSpecifier::Identifier:
04109   case NestedNameSpecifier::Namespace:
04110   case NestedNameSpecifier::NamespaceAlias:
04111   case NestedNameSpecifier::Global:
04112   case NestedNameSpecifier::Super:
04113     return false;
04114 
04115   case NestedNameSpecifier::TypeSpec:
04116   case NestedNameSpecifier::TypeSpecWithTemplate:
04117     return Visit(QualType(NNS->getAsType(), 0));
04118   }
04119   llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
04120 }
04121 
04122 
04123 /// \brief Check a template argument against its corresponding
04124 /// template type parameter.
04125 ///
04126 /// This routine implements the semantics of C++ [temp.arg.type]. It
04127 /// returns true if an error occurred, and false otherwise.
04128 bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
04129                                  TypeSourceInfo *ArgInfo) {
04130   assert(ArgInfo && "invalid TypeSourceInfo");
04131   QualType Arg = ArgInfo->getType();
04132   SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
04133 
04134   if (Arg->isVariablyModifiedType()) {
04135     return Diag(SR.getBegin(), diag::err_variably_modified_template_arg) << Arg;
04136   } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
04137     return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
04138   }
04139 
04140   // C++03 [temp.arg.type]p2:
04141   //   A local type, a type with no linkage, an unnamed type or a type
04142   //   compounded from any of these types shall not be used as a
04143   //   template-argument for a template type-parameter.
04144   //
04145   // C++11 allows these, and even in C++03 we allow them as an extension with
04146   // a warning.
04147   bool NeedsCheck;
04148   if (LangOpts.CPlusPlus11)
04149     NeedsCheck =
04150         !Diags.isIgnored(diag::warn_cxx98_compat_template_arg_unnamed_type,
04151                          SR.getBegin()) ||
04152         !Diags.isIgnored(diag::warn_cxx98_compat_template_arg_local_type,
04153                          SR.getBegin());
04154   else
04155     NeedsCheck = Arg->hasUnnamedOrLocalType();
04156 
04157   if (NeedsCheck) {
04158     UnnamedLocalNoLinkageFinder Finder(*this, SR);
04159     (void)Finder.Visit(Context.getCanonicalType(Arg));
04160   }
04161 
04162   return false;
04163 }
04164 
04165 enum NullPointerValueKind {
04166   NPV_NotNullPointer,
04167   NPV_NullPointer,
04168   NPV_Error
04169 };
04170 
04171 /// \brief Determine whether the given template argument is a null pointer
04172 /// value of the appropriate type.
04173 static NullPointerValueKind
04174 isNullPointerValueTemplateArgument(Sema &S, NonTypeTemplateParmDecl *Param,
04175                                    QualType ParamType, Expr *Arg) {
04176   if (Arg->isValueDependent() || Arg->isTypeDependent())
04177     return NPV_NotNullPointer;
04178   
04179   if (!S.getLangOpts().CPlusPlus11)
04180     return NPV_NotNullPointer;
04181   
04182   // Determine whether we have a constant expression.
04183   ExprResult ArgRV = S.DefaultFunctionArrayConversion(Arg);
04184   if (ArgRV.isInvalid())
04185     return NPV_Error;
04186   Arg = ArgRV.get();
04187   
04188   Expr::EvalResult EvalResult;
04189   SmallVector<PartialDiagnosticAt, 8> Notes;
04190   EvalResult.Diag = &Notes;
04191   if (!Arg->EvaluateAsRValue(EvalResult, S.Context) ||
04192       EvalResult.HasSideEffects) {
04193     SourceLocation DiagLoc = Arg->getExprLoc();
04194     
04195     // If our only note is the usual "invalid subexpression" note, just point
04196     // the caret at its location rather than producing an essentially
04197     // redundant note.
04198     if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
04199         diag::note_invalid_subexpr_in_const_expr) {
04200       DiagLoc = Notes[0].first;
04201       Notes.clear();
04202     }
04203     
04204     S.Diag(DiagLoc, diag::err_template_arg_not_address_constant)
04205       << Arg->getType() << Arg->getSourceRange();
04206     for (unsigned I = 0, N = Notes.size(); I != N; ++I)
04207       S.Diag(Notes[I].first, Notes[I].second);
04208     
04209     S.Diag(Param->getLocation(), diag::note_template_param_here);
04210     return NPV_Error;
04211   }
04212   
04213   // C++11 [temp.arg.nontype]p1:
04214   //   - an address constant expression of type std::nullptr_t
04215   if (Arg->getType()->isNullPtrType())
04216     return NPV_NullPointer;
04217   
04218   //   - a constant expression that evaluates to a null pointer value (4.10); or
04219   //   - a constant expression that evaluates to a null member pointer value
04220   //     (4.11); or
04221   if ((EvalResult.Val.isLValue() && !EvalResult.Val.getLValueBase()) ||
04222       (EvalResult.Val.isMemberPointer() &&
04223        !EvalResult.Val.getMemberPointerDecl())) {
04224     // If our expression has an appropriate type, we've succeeded.
04225     bool ObjCLifetimeConversion;
04226     if (S.Context.hasSameUnqualifiedType(Arg->getType(), ParamType) ||
04227         S.IsQualificationConversion(Arg->getType(), ParamType, false,
04228                                      ObjCLifetimeConversion))
04229       return NPV_NullPointer;
04230     
04231     // The types didn't match, but we know we got a null pointer; complain,
04232     // then recover as if the types were correct.
04233     S.Diag(Arg->getExprLoc(), diag::err_template_arg_wrongtype_null_constant)
04234       << Arg->getType() << ParamType << Arg->getSourceRange();
04235     S.Diag(Param->getLocation(), diag::note_template_param_here);
04236     return NPV_NullPointer;
04237   }
04238 
04239   // If we don't have a null pointer value, but we do have a NULL pointer
04240   // constant, suggest a cast to the appropriate type.
04241   if (Arg->isNullPointerConstant(S.Context, Expr::NPC_NeverValueDependent)) {
04242     std::string Code = "static_cast<" + ParamType.getAsString() + ">(";
04243     S.Diag(Arg->getExprLoc(), diag::err_template_arg_untyped_null_constant)
04244         << ParamType << FixItHint::CreateInsertion(Arg->getLocStart(), Code)
04245         << FixItHint::CreateInsertion(S.getLocForEndOfToken(Arg->getLocEnd()),
04246                                       ")");
04247     S.Diag(Param->getLocation(), diag::note_template_param_here);
04248     return NPV_NullPointer;
04249   }
04250   
04251   // FIXME: If we ever want to support general, address-constant expressions
04252   // as non-type template arguments, we should return the ExprResult here to
04253   // be interpreted by the caller.
04254   return NPV_NotNullPointer;
04255 }
04256 
04257 /// \brief Checks whether the given template argument is compatible with its
04258 /// template parameter.
04259 static bool CheckTemplateArgumentIsCompatibleWithParameter(
04260     Sema &S, NonTypeTemplateParmDecl *Param, QualType ParamType, Expr *ArgIn,
04261     Expr *Arg, QualType ArgType) {
04262   bool ObjCLifetimeConversion;
04263   if (ParamType->isPointerType() &&
04264       !ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType() &&
04265       S.IsQualificationConversion(ArgType, ParamType, false,
04266                                   ObjCLifetimeConversion)) {
04267     // For pointer-to-object types, qualification conversions are
04268     // permitted.
04269   } else {
04270     if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
04271       if (!ParamRef->getPointeeType()->isFunctionType()) {
04272         // C++ [temp.arg.nontype]p5b3:
04273         //   For a non-type template-parameter of type reference to
04274         //   object, no conversions apply. The type referred to by the
04275         //   reference may be more cv-qualified than the (otherwise
04276         //   identical) type of the template- argument. The
04277         //   template-parameter is bound directly to the
04278         //   template-argument, which shall be an lvalue.
04279 
04280         // FIXME: Other qualifiers?
04281         unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
04282         unsigned ArgQuals = ArgType.getCVRQualifiers();
04283 
04284         if ((ParamQuals | ArgQuals) != ParamQuals) {
04285           S.Diag(Arg->getLocStart(),
04286                  diag::err_template_arg_ref_bind_ignores_quals)
04287             << ParamType << Arg->getType() << Arg->getSourceRange();
04288           S.Diag(Param->getLocation(), diag::note_template_param_here);
04289           return true;
04290         }
04291       }
04292     }
04293 
04294     // At this point, the template argument refers to an object or
04295     // function with external linkage. We now need to check whether the
04296     // argument and parameter types are compatible.
04297     if (!S.Context.hasSameUnqualifiedType(ArgType,
04298                                           ParamType.getNonReferenceType())) {
04299       // We can't perform this conversion or binding.
04300       if (ParamType->isReferenceType())
04301         S.Diag(Arg->getLocStart(), diag::err_template_arg_no_ref_bind)
04302           << ParamType << ArgIn->getType() << Arg->getSourceRange();
04303       else
04304         S.Diag(Arg->getLocStart(),  diag::err_template_arg_not_convertible)
04305           << ArgIn->getType() << ParamType << Arg->getSourceRange();
04306       S.Diag(Param->getLocation(), diag::note_template_param_here);
04307       return true;
04308     }
04309   }
04310 
04311   return false;
04312 }
04313 
04314 /// \brief Checks whether the given template argument is the address
04315 /// of an object or function according to C++ [temp.arg.nontype]p1.
04316 static bool
04317 CheckTemplateArgumentAddressOfObjectOrFunction(Sema &S,
04318                                                NonTypeTemplateParmDecl *Param,
04319                                                QualType ParamType,
04320                                                Expr *ArgIn,
04321                                                TemplateArgument &Converted) {
04322   bool Invalid = false;
04323   Expr *Arg = ArgIn;
04324   QualType ArgType = Arg->getType();
04325 
04326   bool AddressTaken = false;
04327   SourceLocation AddrOpLoc;
04328   if (S.getLangOpts().MicrosoftExt) {
04329     // Microsoft Visual C++ strips all casts, allows an arbitrary number of
04330     // dereference and address-of operators.
04331     Arg = Arg->IgnoreParenCasts();
04332 
04333     bool ExtWarnMSTemplateArg = false;
04334     UnaryOperatorKind FirstOpKind;
04335     SourceLocation FirstOpLoc;
04336     while (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
04337       UnaryOperatorKind UnOpKind = UnOp->getOpcode();
04338       if (UnOpKind == UO_Deref)
04339         ExtWarnMSTemplateArg = true;
04340       if (UnOpKind == UO_AddrOf || UnOpKind == UO_Deref) {
04341         Arg = UnOp->getSubExpr()->IgnoreParenCasts();
04342         if (!AddrOpLoc.isValid()) {
04343           FirstOpKind = UnOpKind;
04344           FirstOpLoc = UnOp->getOperatorLoc();
04345         }
04346       } else
04347         break;
04348     }
04349     if (FirstOpLoc.isValid()) {
04350       if (ExtWarnMSTemplateArg)
04351         S.Diag(ArgIn->getLocStart(), diag::ext_ms_deref_template_argument)
04352           << ArgIn->getSourceRange();
04353 
04354       if (FirstOpKind == UO_AddrOf)
04355         AddressTaken = true;
04356       else if (Arg->getType()->isPointerType()) {
04357         // We cannot let pointers get dereferenced here, that is obviously not a
04358         // constant expression.
04359         assert(FirstOpKind == UO_Deref);
04360         S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
04361           << Arg->getSourceRange();
04362       }
04363     }
04364   } else {
04365     // See through any implicit casts we added to fix the type.
04366     Arg = Arg->IgnoreImpCasts();
04367 
04368     // C++ [temp.arg.nontype]p1:
04369     //
04370     //   A template-argument for a non-type, non-template
04371     //   template-parameter shall be one of: [...]
04372     //
04373     //     -- the address of an object or function with external
04374     //        linkage, including function templates and function
04375     //        template-ids but excluding non-static class members,
04376     //        expressed as & id-expression where the & is optional if
04377     //        the name refers to a function or array, or if the
04378     //        corresponding template-parameter is a reference; or
04379 
04380     // In C++98/03 mode, give an extension warning on any extra parentheses.
04381     // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
04382     bool ExtraParens = false;
04383     while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
04384       if (!Invalid && !ExtraParens) {
04385         S.Diag(Arg->getLocStart(),
04386                S.getLangOpts().CPlusPlus11
04387                    ? diag::warn_cxx98_compat_template_arg_extra_parens
04388                    : diag::ext_template_arg_extra_parens)
04389             << Arg->getSourceRange();
04390         ExtraParens = true;
04391       }
04392 
04393       Arg = Parens->getSubExpr();
04394     }
04395 
04396     while (SubstNonTypeTemplateParmExpr *subst =
04397                dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
04398       Arg = subst->getReplacement()->IgnoreImpCasts();
04399 
04400     if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
04401       if (UnOp->getOpcode() == UO_AddrOf) {
04402         Arg = UnOp->getSubExpr();
04403         AddressTaken = true;
04404         AddrOpLoc = UnOp->getOperatorLoc();
04405       }
04406     }
04407 
04408     while (SubstNonTypeTemplateParmExpr *subst =
04409                dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
04410       Arg = subst->getReplacement()->IgnoreImpCasts();
04411   }
04412 
04413   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg);
04414   ValueDecl *Entity = DRE ? DRE->getDecl() : nullptr;
04415 
04416   // If our parameter has pointer type, check for a null template value.
04417   if (ParamType->isPointerType() || ParamType->isNullPtrType()) {
04418     NullPointerValueKind NPV;
04419     // dllimport'd entities aren't constant but are available inside of template
04420     // arguments.
04421     if (Entity && Entity->hasAttr<DLLImportAttr>())
04422       NPV = NPV_NotNullPointer;
04423     else
04424       NPV = isNullPointerValueTemplateArgument(S, Param, ParamType, ArgIn);
04425     switch (NPV) {
04426     case NPV_NullPointer:
04427       S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
04428       Converted = TemplateArgument(S.Context.getCanonicalType(ParamType),
04429                                    /*isNullPtr=*/true);
04430       return false;
04431 
04432     case NPV_Error:
04433       return true;
04434 
04435     case NPV_NotNullPointer:
04436       break;
04437     }
04438   }
04439 
04440   // Stop checking the precise nature of the argument if it is value dependent,
04441   // it should be checked when instantiated.
04442   if (Arg->isValueDependent()) {
04443     Converted = TemplateArgument(ArgIn);
04444     return false;
04445   }
04446 
04447   if (isa<CXXUuidofExpr>(Arg)) {
04448     if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType,
04449                                                        ArgIn, Arg, ArgType))
04450       return true;
04451 
04452     Converted = TemplateArgument(ArgIn);
04453     return false;
04454   }
04455 
04456   if (!DRE) {
04457     S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
04458     << Arg->getSourceRange();
04459     S.Diag(Param->getLocation(), diag::note_template_param_here);
04460     return true;
04461   }
04462 
04463   // Cannot refer to non-static data members
04464   if (isa<FieldDecl>(Entity) || isa<IndirectFieldDecl>(Entity)) {
04465     S.Diag(Arg->getLocStart(), diag::err_template_arg_field)
04466       << Entity << Arg->getSourceRange();
04467     S.Diag(Param->getLocation(), diag::note_template_param_here);
04468     return true;
04469   }
04470 
04471   // Cannot refer to non-static member functions
04472   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Entity)) {
04473     if (!Method->isStatic()) {
04474       S.Diag(Arg->getLocStart(), diag::err_template_arg_method)
04475         << Method << Arg->getSourceRange();
04476       S.Diag(Param->getLocation(), diag::note_template_param_here);
04477       return true;
04478     }
04479   }
04480 
04481   FunctionDecl *Func = dyn_cast<FunctionDecl>(Entity);
04482   VarDecl *Var = dyn_cast<VarDecl>(Entity);
04483 
04484   // A non-type template argument must refer to an object or function.
04485   if (!Func && !Var) {
04486     // We found something, but we don't know specifically what it is.
04487     S.Diag(Arg->getLocStart(), diag::err_template_arg_not_object_or_func)
04488       << Arg->getSourceRange();
04489     S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
04490     return true;
04491   }
04492 
04493   // Address / reference template args must have external linkage in C++98.
04494   if (Entity->getFormalLinkage() == InternalLinkage) {
04495     S.Diag(Arg->getLocStart(), S.getLangOpts().CPlusPlus11 ?
04496              diag::warn_cxx98_compat_template_arg_object_internal :
04497              diag::ext_template_arg_object_internal)
04498       << !Func << Entity << Arg->getSourceRange();
04499     S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
04500       << !Func;
04501   } else if (!Entity->hasLinkage()) {
04502     S.Diag(Arg->getLocStart(), diag::err_template_arg_object_no_linkage)
04503       << !Func << Entity << Arg->getSourceRange();
04504     S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
04505       << !Func;
04506     return true;
04507   }
04508 
04509   if (Func) {
04510     // If the template parameter has pointer type, the function decays.
04511     if (ParamType->isPointerType() && !AddressTaken)
04512       ArgType = S.Context.getPointerType(Func->getType());
04513     else if (AddressTaken && ParamType->isReferenceType()) {
04514       // If we originally had an address-of operator, but the
04515       // parameter has reference type, complain and (if things look
04516       // like they will work) drop the address-of operator.
04517       if (!S.Context.hasSameUnqualifiedType(Func->getType(),
04518                                             ParamType.getNonReferenceType())) {
04519         S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
04520           << ParamType;
04521         S.Diag(Param->getLocation(), diag::note_template_param_here);
04522         return true;
04523       }
04524 
04525       S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
04526         << ParamType
04527         << FixItHint::CreateRemoval(AddrOpLoc);
04528       S.Diag(Param->getLocation(), diag::note_template_param_here);
04529 
04530       ArgType = Func->getType();
04531     }
04532   } else {
04533     // A value of reference type is not an object.
04534     if (Var->getType()->isReferenceType()) {
04535       S.Diag(Arg->getLocStart(),
04536              diag::err_template_arg_reference_var)
04537         << Var->getType() << Arg->getSourceRange();
04538       S.Diag(Param->getLocation(), diag::note_template_param_here);
04539       return true;
04540     }
04541 
04542     // A template argument must have static storage duration.
04543     if (Var->getTLSKind()) {
04544       S.Diag(Arg->getLocStart(), diag::err_template_arg_thread_local)
04545         << Arg->getSourceRange();
04546       S.Diag(Var->getLocation(), diag::note_template_arg_refers_here);
04547       return true;
04548     }
04549 
04550     // If the template parameter has pointer type, we must have taken
04551     // the address of this object.
04552     if (ParamType->isReferenceType()) {
04553       if (AddressTaken) {
04554         // If we originally had an address-of operator, but the
04555         // parameter has reference type, complain and (if things look
04556         // like they will work) drop the address-of operator.
04557         if (!S.Context.hasSameUnqualifiedType(Var->getType(),
04558                                             ParamType.getNonReferenceType())) {
04559           S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
04560             << ParamType;
04561           S.Diag(Param->getLocation(), diag::note_template_param_here);
04562           return true;
04563         }
04564 
04565         S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
04566           << ParamType
04567           << FixItHint::CreateRemoval(AddrOpLoc);
04568         S.Diag(Param->getLocation(), diag::note_template_param_here);
04569 
04570         ArgType = Var->getType();
04571       }
04572     } else if (!AddressTaken && ParamType->isPointerType()) {
04573       if (Var->getType()->isArrayType()) {
04574         // Array-to-pointer decay.
04575         ArgType = S.Context.getArrayDecayedType(Var->getType());
04576       } else {
04577         // If the template parameter has pointer type but the address of
04578         // this object was not taken, complain and (possibly) recover by
04579         // taking the address of the entity.
04580         ArgType = S.Context.getPointerType(Var->getType());
04581         if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) {
04582           S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
04583             << ParamType;
04584           S.Diag(Param->getLocation(), diag::note_template_param_here);
04585           return true;
04586         }
04587 
04588         S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
04589           << ParamType
04590           << FixItHint::CreateInsertion(Arg->getLocStart(), "&");
04591 
04592         S.Diag(Param->getLocation(), diag::note_template_param_here);
04593       }
04594     }
04595   }
04596 
04597   if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType, ArgIn,
04598                                                      Arg, ArgType))
04599     return true;
04600 
04601   // Create the template argument.
04602   Converted =
04603       TemplateArgument(cast<ValueDecl>(Entity->getCanonicalDecl()), ParamType);
04604   S.MarkAnyDeclReferenced(Arg->getLocStart(), Entity, false);
04605   return false;
04606 }
04607 
04608 /// \brief Checks whether the given template argument is a pointer to
04609 /// member constant according to C++ [temp.arg.nontype]p1.
04610 static bool CheckTemplateArgumentPointerToMember(Sema &S,
04611                                                  NonTypeTemplateParmDecl *Param,
04612                                                  QualType ParamType,
04613                                                  Expr *&ResultArg,
04614                                                  TemplateArgument &Converted) {
04615   bool Invalid = false;
04616 
04617   // Check for a null pointer value.
04618   Expr *Arg = ResultArg;
04619   switch (isNullPointerValueTemplateArgument(S, Param, ParamType, Arg)) {
04620   case NPV_Error:
04621     return true;
04622   case NPV_NullPointer:
04623     S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
04624     Converted = TemplateArgument(S.Context.getCanonicalType(ParamType),
04625                                  /*isNullPtr*/true);
04626     if (S.Context.getTargetInfo().getCXXABI().isMicrosoft())
04627       S.RequireCompleteType(Arg->getExprLoc(), ParamType, 0);
04628     return false;
04629   case NPV_NotNullPointer:
04630     break;
04631   }
04632 
04633   bool ObjCLifetimeConversion;
04634   if (S.IsQualificationConversion(Arg->getType(),
04635                                   ParamType.getNonReferenceType(),
04636                                   false, ObjCLifetimeConversion)) {
04637     Arg = S.ImpCastExprToType(Arg, ParamType, CK_NoOp,
04638                               Arg->getValueKind()).get();
04639     ResultArg = Arg;
04640   } else if (!S.Context.hasSameUnqualifiedType(Arg->getType(),
04641                 ParamType.getNonReferenceType())) {
04642     // We can't perform this conversion.
04643     S.Diag(Arg->getLocStart(), diag::err_template_arg_not_convertible)
04644       << Arg->getType() << ParamType << Arg->getSourceRange();
04645     S.Diag(Param->getLocation(), diag::note_template_param_here);
04646     return true;
04647   }
04648 
04649   // See through any implicit casts we added to fix the type.
04650   while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
04651     Arg = Cast->getSubExpr();
04652 
04653   // C++ [temp.arg.nontype]p1:
04654   //
04655   //   A template-argument for a non-type, non-template
04656   //   template-parameter shall be one of: [...]
04657   //
04658   //     -- a pointer to member expressed as described in 5.3.1.
04659   DeclRefExpr *DRE = nullptr;
04660 
04661   // In C++98/03 mode, give an extension warning on any extra parentheses.
04662   // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
04663   bool ExtraParens = false;
04664   while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
04665     if (!Invalid && !ExtraParens) {
04666       S.Diag(Arg->getLocStart(),
04667              S.getLangOpts().CPlusPlus11 ?
04668                diag::warn_cxx98_compat_template_arg_extra_parens :
04669                diag::ext_template_arg_extra_parens)
04670         << Arg->getSourceRange();
04671       ExtraParens = true;
04672     }
04673 
04674     Arg = Parens->getSubExpr();
04675   }
04676 
04677   while (SubstNonTypeTemplateParmExpr *subst =
04678            dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
04679     Arg = subst->getReplacement()->IgnoreImpCasts();
04680 
04681   // A pointer-to-member constant written &Class::member.
04682   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
04683     if (UnOp->getOpcode() == UO_AddrOf) {
04684       DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
04685       if (DRE && !DRE->getQualifier())
04686         DRE = nullptr;
04687     }
04688   }
04689   // A constant of pointer-to-member type.
04690   else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
04691     if (ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl())) {
04692       if (VD->getType()->isMemberPointerType()) {
04693         if (isa<NonTypeTemplateParmDecl>(VD)) {
04694           if (Arg->isTypeDependent() || Arg->isValueDependent()) {
04695             Converted = TemplateArgument(Arg);
04696           } else {
04697             VD = cast<ValueDecl>(VD->getCanonicalDecl());
04698             Converted = TemplateArgument(VD, ParamType);
04699           }
04700           return Invalid;
04701         }
04702       }
04703     }
04704 
04705     DRE = nullptr;
04706   }
04707 
04708   if (!DRE)
04709     return S.Diag(Arg->getLocStart(),
04710                   diag::err_template_arg_not_pointer_to_member_form)
04711       << Arg->getSourceRange();
04712 
04713   if (isa<FieldDecl>(DRE->getDecl()) ||
04714       isa<IndirectFieldDecl>(DRE->getDecl()) ||
04715       isa<CXXMethodDecl>(DRE->getDecl())) {
04716     assert((isa<FieldDecl>(DRE->getDecl()) ||
04717             isa<IndirectFieldDecl>(DRE->getDecl()) ||
04718             !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
04719            "Only non-static member pointers can make it here");
04720 
04721     // Okay: this is the address of a non-static member, and therefore
04722     // a member pointer constant.
04723     if (Arg->isTypeDependent() || Arg->isValueDependent()) {
04724       Converted = TemplateArgument(Arg);
04725     } else {
04726       ValueDecl *D = cast<ValueDecl>(DRE->getDecl()->getCanonicalDecl());
04727       Converted = TemplateArgument(D, ParamType);
04728     }
04729     return Invalid;
04730   }
04731 
04732   // We found something else, but we don't know specifically what it is.
04733   S.Diag(Arg->getLocStart(),
04734          diag::err_template_arg_not_pointer_to_member_form)
04735     << Arg->getSourceRange();
04736   S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
04737   return true;
04738 }
04739 
04740 /// \brief Check a template argument against its corresponding
04741 /// non-type template parameter.
04742 ///
04743 /// This routine implements the semantics of C++ [temp.arg.nontype].
04744 /// If an error occurred, it returns ExprError(); otherwise, it
04745 /// returns the converted template argument. \p
04746 /// InstantiatedParamType is the type of the non-type template
04747 /// parameter after it has been instantiated.
04748 ExprResult Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
04749                                        QualType InstantiatedParamType, Expr *Arg,
04750                                        TemplateArgument &Converted,
04751                                        CheckTemplateArgumentKind CTAK) {
04752   SourceLocation StartLoc = Arg->getLocStart();
04753 
04754   // If either the parameter has a dependent type or the argument is
04755   // type-dependent, there's nothing we can check now.
04756   if (InstantiatedParamType->isDependentType() || Arg->isTypeDependent()) {
04757     // FIXME: Produce a cloned, canonical expression?
04758     Converted = TemplateArgument(Arg);
04759     return Arg;
04760   }
04761 
04762   // C++ [temp.arg.nontype]p5:
04763   //   The following conversions are performed on each expression used
04764   //   as a non-type template-argument. If a non-type
04765   //   template-argument cannot be converted to the type of the
04766   //   corresponding template-parameter then the program is
04767   //   ill-formed.
04768   QualType ParamType = InstantiatedParamType;
04769   if (ParamType->isIntegralOrEnumerationType()) {
04770     // C++11:
04771     //   -- for a non-type template-parameter of integral or
04772     //      enumeration type, conversions permitted in a converted
04773     //      constant expression are applied.
04774     //
04775     // C++98:
04776     //   -- for a non-type template-parameter of integral or
04777     //      enumeration type, integral promotions (4.5) and integral
04778     //      conversions (4.7) are applied.
04779 
04780     if (CTAK == CTAK_Deduced &&
04781         !Context.hasSameUnqualifiedType(ParamType, Arg->getType())) {
04782       // C++ [temp.deduct.type]p17:
04783       //   If, in the declaration of a function template with a non-type
04784       //   template-parameter, the non-type template-parameter is used
04785       //   in an expression in the function parameter-list and, if the
04786       //   corresponding template-argument is deduced, the
04787       //   template-argument type shall match the type of the
04788       //   template-parameter exactly, except that a template-argument
04789       //   deduced from an array bound may be of any integral type.
04790       Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
04791         << Arg->getType().getUnqualifiedType()
04792         << ParamType.getUnqualifiedType();
04793       Diag(Param->getLocation(), diag::note_template_param_here);
04794       return ExprError();
04795     }
04796 
04797     if (getLangOpts().CPlusPlus11) {
04798       // We can't check arbitrary value-dependent arguments.
04799       // FIXME: If there's no viable conversion to the template parameter type,
04800       // we should be able to diagnose that prior to instantiation.
04801       if (Arg->isValueDependent()) {
04802         Converted = TemplateArgument(Arg);
04803         return Arg;
04804       }
04805 
04806       // C++ [temp.arg.nontype]p1:
04807       //   A template-argument for a non-type, non-template template-parameter
04808       //   shall be one of:
04809       //
04810       //     -- for a non-type template-parameter of integral or enumeration
04811       //        type, a converted constant expression of the type of the
04812       //        template-parameter; or
04813       llvm::APSInt Value;
04814       ExprResult ArgResult =
04815         CheckConvertedConstantExpression(Arg, ParamType, Value,
04816                                          CCEK_TemplateArg);
04817       if (ArgResult.isInvalid())
04818         return ExprError();
04819 
04820       // Widen the argument value to sizeof(parameter type). This is almost
04821       // always a no-op, except when the parameter type is bool. In
04822       // that case, this may extend the argument from 1 bit to 8 bits.
04823       QualType IntegerType = ParamType;
04824       if (const EnumType *Enum = IntegerType->getAs<EnumType>())
04825         IntegerType = Enum->getDecl()->getIntegerType();
04826       Value = Value.extOrTrunc(Context.getTypeSize(IntegerType));
04827 
04828       Converted = TemplateArgument(Context, Value,
04829                                    Context.getCanonicalType(ParamType));
04830       return ArgResult;
04831     }
04832 
04833     ExprResult ArgResult = DefaultLvalueConversion(Arg);
04834     if (ArgResult.isInvalid())
04835       return ExprError();
04836     Arg = ArgResult.get();
04837 
04838     QualType ArgType = Arg->getType();
04839 
04840     // C++ [temp.arg.nontype]p1:
04841     //   A template-argument for a non-type, non-template
04842     //   template-parameter shall be one of:
04843     //
04844     //     -- an integral constant-expression of integral or enumeration
04845     //        type; or
04846     //     -- the name of a non-type template-parameter; or
04847     SourceLocation NonConstantLoc;
04848     llvm::APSInt Value;
04849     if (!ArgType->isIntegralOrEnumerationType()) {
04850       Diag(Arg->getLocStart(),
04851            diag::err_template_arg_not_integral_or_enumeral)
04852         << ArgType << Arg->getSourceRange();
04853       Diag(Param->getLocation(), diag::note_template_param_here);
04854       return ExprError();
04855     } else if (!Arg->isValueDependent()) {
04856       class TmplArgICEDiagnoser : public VerifyICEDiagnoser {
04857         QualType T;
04858         
04859       public:
04860         TmplArgICEDiagnoser(QualType T) : T(T) { }
04861 
04862         void diagnoseNotICE(Sema &S, SourceLocation Loc,
04863                             SourceRange SR) override {
04864           S.Diag(Loc, diag::err_template_arg_not_ice) << T << SR;
04865         }
04866       } Diagnoser(ArgType);
04867 
04868       Arg = VerifyIntegerConstantExpression(Arg, &Value, Diagnoser,
04869                                             false).get();
04870       if (!Arg)
04871         return ExprError();
04872     }
04873 
04874     // From here on out, all we care about are the unqualified forms
04875     // of the parameter and argument types.
04876     ParamType = ParamType.getUnqualifiedType();
04877     ArgType = ArgType.getUnqualifiedType();
04878 
04879     // Try to convert the argument to the parameter's type.
04880     if (Context.hasSameType(ParamType, ArgType)) {
04881       // Okay: no conversion necessary
04882     } else if (ParamType->isBooleanType()) {
04883       // This is an integral-to-boolean conversion.
04884       Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralToBoolean).get();
04885     } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
04886                !ParamType->isEnumeralType()) {
04887       // This is an integral promotion or conversion.
04888       Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralCast).get();
04889     } else {
04890       // We can't perform this conversion.
04891       Diag(Arg->getLocStart(),
04892            diag::err_template_arg_not_convertible)
04893         << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
04894       Diag(Param->getLocation(), diag::note_template_param_here);
04895       return ExprError();
04896     }
04897 
04898     // Add the value of this argument to the list of converted
04899     // arguments. We use the bitwidth and signedness of the template
04900     // parameter.
04901     if (Arg->isValueDependent()) {
04902       // The argument is value-dependent. Create a new
04903       // TemplateArgument with the converted expression.
04904       Converted = TemplateArgument(Arg);
04905       return Arg;
04906     }
04907 
04908     QualType IntegerType = Context.getCanonicalType(ParamType);
04909     if (const EnumType *Enum = IntegerType->getAs<EnumType>())
04910       IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
04911 
04912     if (ParamType->isBooleanType()) {
04913       // Value must be zero or one.
04914       Value = Value != 0;
04915       unsigned AllowedBits = Context.getTypeSize(IntegerType);
04916       if (Value.getBitWidth() != AllowedBits)
04917         Value = Value.extOrTrunc(AllowedBits);
04918       Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
04919     } else {
04920       llvm::APSInt OldValue = Value;
04921       
04922       // Coerce the template argument's value to the value it will have
04923       // based on the template parameter's type.
04924       unsigned AllowedBits = Context.getTypeSize(IntegerType);
04925       if (Value.getBitWidth() != AllowedBits)
04926         Value = Value.extOrTrunc(AllowedBits);
04927       Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
04928       
04929       // Complain if an unsigned parameter received a negative value.
04930       if (IntegerType->isUnsignedIntegerOrEnumerationType()
04931                && (OldValue.isSigned() && OldValue.isNegative())) {
04932         Diag(Arg->getLocStart(), diag::warn_template_arg_negative)
04933           << OldValue.toString(10) << Value.toString(10) << Param->getType()
04934           << Arg->getSourceRange();
04935         Diag(Param->getLocation(), diag::note_template_param_here);
04936       }
04937       
04938       // Complain if we overflowed the template parameter's type.
04939       unsigned RequiredBits;
04940       if (IntegerType->isUnsignedIntegerOrEnumerationType())
04941         RequiredBits = OldValue.getActiveBits();
04942       else if (OldValue.isUnsigned())
04943         RequiredBits = OldValue.getActiveBits() + 1;
04944       else
04945         RequiredBits = OldValue.getMinSignedBits();
04946       if (RequiredBits > AllowedBits) {
04947         Diag(Arg->getLocStart(),
04948              diag::warn_template_arg_too_large)
04949           << OldValue.toString(10) << Value.toString(10) << Param->getType()
04950           << Arg->getSourceRange();
04951         Diag(Param->getLocation(), diag::note_template_param_here);
04952       }
04953     }
04954 
04955     Converted = TemplateArgument(Context, Value,
04956                                  ParamType->isEnumeralType() 
04957                                    ? Context.getCanonicalType(ParamType)
04958                                    : IntegerType);
04959     return Arg;
04960   }
04961 
04962   QualType ArgType = Arg->getType();
04963   DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
04964 
04965   // Handle pointer-to-function, reference-to-function, and
04966   // pointer-to-member-function all in (roughly) the same way.
04967   if (// -- For a non-type template-parameter of type pointer to
04968       //    function, only the function-to-pointer conversion (4.3) is
04969       //    applied. If the template-argument represents a set of
04970       //    overloaded functions (or a pointer to such), the matching
04971       //    function is selected from the set (13.4).
04972       (ParamType->isPointerType() &&
04973        ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
04974       // -- For a non-type template-parameter of type reference to
04975       //    function, no conversions apply. If the template-argument
04976       //    represents a set of overloaded functions, the matching
04977       //    function is selected from the set (13.4).
04978       (ParamType->isReferenceType() &&
04979        ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
04980       // -- For a non-type template-parameter of type pointer to
04981       //    member function, no conversions apply. If the
04982       //    template-argument represents a set of overloaded member
04983       //    functions, the matching member function is selected from
04984       //    the set (13.4).
04985       (ParamType->isMemberPointerType() &&
04986        ParamType->getAs<MemberPointerType>()->getPointeeType()
04987          ->isFunctionType())) {
04988 
04989     if (Arg->getType() == Context.OverloadTy) {
04990       if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType,
04991                                                                 true,
04992                                                                 FoundResult)) {
04993         if (DiagnoseUseOfDecl(Fn, Arg->getLocStart()))
04994           return ExprError();
04995 
04996         Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
04997         ArgType = Arg->getType();
04998       } else
04999         return ExprError();
05000     }
05001 
05002     if (!ParamType->isMemberPointerType()) {
05003       if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
05004                                                          ParamType,
05005                                                          Arg, Converted))
05006         return ExprError();
05007       return Arg;
05008     }
05009 
05010     if (CheckTemplateArgumentPointerToMember(*this, Param, ParamType, Arg,
05011                                              Converted))
05012       return ExprError();
05013     return Arg;
05014   }
05015 
05016   if (ParamType->isPointerType()) {
05017     //   -- for a non-type template-parameter of type pointer to
05018     //      object, qualification conversions (4.4) and the
05019     //      array-to-pointer conversion (4.2) are applied.
05020     // C++0x also allows a value of std::nullptr_t.
05021     assert(ParamType->getPointeeType()->isIncompleteOrObjectType() &&
05022            "Only object pointers allowed here");
05023 
05024     if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
05025                                                        ParamType,
05026                                                        Arg, Converted))
05027       return ExprError();
05028     return Arg;
05029   }
05030 
05031   if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
05032     //   -- For a non-type template-parameter of type reference to
05033     //      object, no conversions apply. The type referred to by the
05034     //      reference may be more cv-qualified than the (otherwise
05035     //      identical) type of the template-argument. The
05036     //      template-parameter is bound directly to the
05037     //      template-argument, which must be an lvalue.
05038     assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() &&
05039            "Only object references allowed here");
05040 
05041     if (Arg->getType() == Context.OverloadTy) {
05042       if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg,
05043                                                  ParamRefType->getPointeeType(),
05044                                                                 true,
05045                                                                 FoundResult)) {
05046         if (DiagnoseUseOfDecl(Fn, Arg->getLocStart()))
05047           return ExprError();
05048 
05049         Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
05050         ArgType = Arg->getType();
05051       } else
05052         return ExprError();
05053     }
05054 
05055     if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
05056                                                        ParamType,
05057                                                        Arg, Converted))
05058       return ExprError();
05059     return Arg;
05060   }
05061 
05062   // Deal with parameters of type std::nullptr_t.
05063   if (ParamType->isNullPtrType()) {
05064     if (Arg->isTypeDependent() || Arg->isValueDependent()) {
05065       Converted = TemplateArgument(Arg);
05066       return Arg;
05067     }
05068     
05069     switch (isNullPointerValueTemplateArgument(*this, Param, ParamType, Arg)) {
05070     case NPV_NotNullPointer:
05071       Diag(Arg->getExprLoc(), diag::err_template_arg_not_convertible)
05072         << Arg->getType() << ParamType;
05073       Diag(Param->getLocation(), diag::note_template_param_here);
05074       return ExprError();
05075       
05076     case NPV_Error:
05077       return ExprError();
05078       
05079     case NPV_NullPointer:
05080       Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
05081       Converted = TemplateArgument(Context.getCanonicalType(ParamType),
05082                                    /*isNullPtr*/true);
05083       return Arg;
05084     }
05085   }
05086 
05087   //     -- For a non-type template-parameter of type pointer to data
05088   //        member, qualification conversions (4.4) are applied.
05089   assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
05090 
05091   if (CheckTemplateArgumentPointerToMember(*this, Param, ParamType, Arg,
05092                                            Converted))
05093     return ExprError();
05094   return Arg;
05095 }
05096 
05097 /// \brief Check a template argument against its corresponding
05098 /// template template parameter.
05099 ///
05100 /// This routine implements the semantics of C++ [temp.arg.template].
05101 /// It returns true if an error occurred, and false otherwise.
05102 bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
05103                                  TemplateArgumentLoc &Arg,
05104                                  unsigned ArgumentPackIndex) {
05105   TemplateName Name = Arg.getArgument().getAsTemplateOrTemplatePattern();
05106   TemplateDecl *Template = Name.getAsTemplateDecl();
05107   if (!Template) {
05108     // Any dependent template name is fine.
05109     assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
05110     return false;
05111   }
05112 
05113   // C++0x [temp.arg.template]p1:
05114   //   A template-argument for a template template-parameter shall be
05115   //   the name of a class template or an alias template, expressed as an
05116   //   id-expression. When the template-argument names a class template, only
05117   //   primary class templates are considered when matching the
05118   //   template template argument with the corresponding parameter;
05119   //   partial specializations are not considered even if their
05120   //   parameter lists match that of the template template parameter.
05121   //
05122   // Note that we also allow template template parameters here, which
05123   // will happen when we are dealing with, e.g., class template
05124   // partial specializations.
05125   if (!isa<ClassTemplateDecl>(Template) &&
05126       !isa<TemplateTemplateParmDecl>(Template) &&
05127       !isa<TypeAliasTemplateDecl>(Template)) {
05128     assert(isa<FunctionTemplateDecl>(Template) &&
05129            "Only function templates are possible here");
05130     Diag(Arg.getLocation(), diag::err_template_arg_not_class_template);
05131     Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
05132       << Template;
05133   }
05134 
05135   TemplateParameterList *Params = Param->getTemplateParameters();
05136   if (Param->isExpandedParameterPack())
05137     Params = Param->getExpansionTemplateParameters(ArgumentPackIndex);
05138 
05139   return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
05140                                          Params,
05141                                          true,
05142                                          TPL_TemplateTemplateArgumentMatch,
05143                                          Arg.getLocation());
05144 }
05145 
05146 /// \brief Given a non-type template argument that refers to a
05147 /// declaration and the type of its corresponding non-type template
05148 /// parameter, produce an expression that properly refers to that
05149 /// declaration.
05150 ExprResult
05151 Sema::BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
05152                                               QualType ParamType,
05153                                               SourceLocation Loc) {
05154   // C++ [temp.param]p8:
05155   //
05156   //   A non-type template-parameter of type "array of T" or
05157   //   "function returning T" is adjusted to be of type "pointer to
05158   //   T" or "pointer to function returning T", respectively.
05159   if (ParamType->isArrayType())
05160     ParamType = Context.getArrayDecayedType(ParamType);
05161   else if (ParamType->isFunctionType())
05162     ParamType = Context.getPointerType(ParamType);
05163 
05164   // For a NULL non-type template argument, return nullptr casted to the
05165   // parameter's type.
05166   if (Arg.getKind() == TemplateArgument::NullPtr) {
05167     return ImpCastExprToType(
05168              new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc),
05169                              ParamType,
05170                              ParamType->getAs<MemberPointerType>()
05171                                ? CK_NullToMemberPointer
05172                                : CK_NullToPointer);
05173   }
05174   assert(Arg.getKind() == TemplateArgument::Declaration &&
05175          "Only declaration template arguments permitted here");
05176 
05177   ValueDecl *VD = cast<ValueDecl>(Arg.getAsDecl());
05178 
05179   if (VD->getDeclContext()->isRecord() &&
05180       (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD) ||
05181        isa<IndirectFieldDecl>(VD))) {
05182     // If the value is a class member, we might have a pointer-to-member.
05183     // Determine whether the non-type template template parameter is of
05184     // pointer-to-member type. If so, we need to build an appropriate
05185     // expression for a pointer-to-member, since a "normal" DeclRefExpr
05186     // would refer to the member itself.
05187     if (ParamType->isMemberPointerType()) {
05188       QualType ClassType
05189         = Context.getTypeDeclType(cast<RecordDecl>(VD->getDeclContext()));
05190       NestedNameSpecifier *Qualifier
05191         = NestedNameSpecifier::Create(Context, nullptr, false,
05192                                       ClassType.getTypePtr());
05193       CXXScopeSpec SS;
05194       SS.MakeTrivial(Context, Qualifier, Loc);
05195 
05196       // The actual value-ness of this is unimportant, but for
05197       // internal consistency's sake, references to instance methods
05198       // are r-values.
05199       ExprValueKind VK = VK_LValue;
05200       if (isa<CXXMethodDecl>(VD) && cast<CXXMethodDecl>(VD)->isInstance())
05201         VK = VK_RValue;
05202 
05203       ExprResult RefExpr = BuildDeclRefExpr(VD,
05204                                             VD->getType().getNonReferenceType(),
05205                                             VK,
05206                                             Loc,
05207                                             &SS);
05208       if (RefExpr.isInvalid())
05209         return ExprError();
05210 
05211       RefExpr = CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
05212 
05213       // We might need to perform a trailing qualification conversion, since
05214       // the element type on the parameter could be more qualified than the
05215       // element type in the expression we constructed.
05216       bool ObjCLifetimeConversion;
05217       if (IsQualificationConversion(((Expr*) RefExpr.get())->getType(),
05218                                     ParamType.getUnqualifiedType(), false,
05219                                     ObjCLifetimeConversion))
05220         RefExpr = ImpCastExprToType(RefExpr.get(), ParamType.getUnqualifiedType(), CK_NoOp);
05221 
05222       assert(!RefExpr.isInvalid() &&
05223              Context.hasSameType(((Expr*) RefExpr.get())->getType(),
05224                                  ParamType.getUnqualifiedType()));
05225       return RefExpr;
05226     }
05227   }
05228 
05229   QualType T = VD->getType().getNonReferenceType();
05230 
05231   if (ParamType->isPointerType()) {
05232     // When the non-type template parameter is a pointer, take the
05233     // address of the declaration.
05234     ExprResult RefExpr = BuildDeclRefExpr(VD, T, VK_LValue, Loc);
05235     if (RefExpr.isInvalid())
05236       return ExprError();
05237 
05238     if (T->isFunctionType() || T->isArrayType()) {
05239       // Decay functions and arrays.
05240       RefExpr = DefaultFunctionArrayConversion(RefExpr.get());
05241       if (RefExpr.isInvalid())
05242         return ExprError();
05243 
05244       return RefExpr;
05245     }
05246 
05247     // Take the address of everything else
05248     return CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
05249   }
05250 
05251   ExprValueKind VK = VK_RValue;
05252 
05253   // If the non-type template parameter has reference type, qualify the
05254   // resulting declaration reference with the extra qualifiers on the
05255   // type that the reference refers to.
05256   if (const ReferenceType *TargetRef = ParamType->getAs<ReferenceType>()) {
05257     VK = VK_LValue;
05258     T = Context.getQualifiedType(T,
05259                               TargetRef->getPointeeType().getQualifiers());
05260   } else if (isa<FunctionDecl>(VD)) {
05261     // References to functions are always lvalues.
05262     VK = VK_LValue;
05263   }
05264 
05265   return BuildDeclRefExpr(VD, T, VK, Loc);
05266 }
05267 
05268 /// \brief Construct a new expression that refers to the given
05269 /// integral template argument with the given source-location
05270 /// information.
05271 ///
05272 /// This routine takes care of the mapping from an integral template
05273 /// argument (which may have any integral type) to the appropriate
05274 /// literal value.
05275 ExprResult
05276 Sema::BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
05277                                                   SourceLocation Loc) {
05278   assert(Arg.getKind() == TemplateArgument::Integral &&
05279          "Operation is only valid for integral template arguments");
05280   QualType OrigT = Arg.getIntegralType();
05281 
05282   // If this is an enum type that we're instantiating, we need to use an integer
05283   // type the same size as the enumerator.  We don't want to build an
05284   // IntegerLiteral with enum type.  The integer type of an enum type can be of
05285   // any integral type with C++11 enum classes, make sure we create the right
05286   // type of literal for it.
05287   QualType T = OrigT;
05288   if (const EnumType *ET = OrigT->getAs<EnumType>())
05289     T = ET->getDecl()->getIntegerType();
05290 
05291   Expr *E;
05292   if (T->isAnyCharacterType()) {
05293     CharacterLiteral::CharacterKind Kind;
05294     if (T->isWideCharType())
05295       Kind = CharacterLiteral::Wide;
05296     else if (T->isChar16Type())
05297       Kind = CharacterLiteral::UTF16;
05298     else if (T->isChar32Type())
05299       Kind = CharacterLiteral::UTF32;
05300     else
05301       Kind = CharacterLiteral::Ascii;
05302 
05303     E = new (Context) CharacterLiteral(Arg.getAsIntegral().getZExtValue(),
05304                                        Kind, T, Loc);
05305   } else if (T->isBooleanType()) {
05306     E = new (Context) CXXBoolLiteralExpr(Arg.getAsIntegral().getBoolValue(),
05307                                          T, Loc);
05308   } else if (T->isNullPtrType()) {
05309     E = new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc);
05310   } else {
05311     E = IntegerLiteral::Create(Context, Arg.getAsIntegral(), T, Loc);
05312   }
05313 
05314   if (OrigT->isEnumeralType()) {
05315     // FIXME: This is a hack. We need a better way to handle substituted
05316     // non-type template parameters.
05317     E = CStyleCastExpr::Create(Context, OrigT, VK_RValue, CK_IntegralCast, E,
05318                                nullptr,
05319                                Context.getTrivialTypeSourceInfo(OrigT, Loc),
05320                                Loc, Loc);
05321   }
05322   
05323   return E;
05324 }
05325 
05326 /// \brief Match two template parameters within template parameter lists.
05327 static bool MatchTemplateParameterKind(Sema &S, NamedDecl *New, NamedDecl *Old,
05328                                        bool Complain,
05329                                      Sema::TemplateParameterListEqualKind Kind,
05330                                        SourceLocation TemplateArgLoc) {
05331   // Check the actual kind (type, non-type, template).
05332   if (Old->getKind() != New->getKind()) {
05333     if (Complain) {
05334       unsigned NextDiag = diag::err_template_param_different_kind;
05335       if (TemplateArgLoc.isValid()) {
05336         S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
05337         NextDiag = diag::note_template_param_different_kind;
05338       }
05339       S.Diag(New->getLocation(), NextDiag)
05340         << (Kind != Sema::TPL_TemplateMatch);
05341       S.Diag(Old->getLocation(), diag::note_template_prev_declaration)
05342         << (Kind != Sema::TPL_TemplateMatch);
05343     }
05344 
05345     return false;
05346   }
05347 
05348   // Check that both are parameter packs are neither are parameter packs.
05349   // However, if we are matching a template template argument to a
05350   // template template parameter, the template template parameter can have
05351   // a parameter pack where the template template argument does not.
05352   if (Old->isTemplateParameterPack() != New->isTemplateParameterPack() &&
05353       !(Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
05354         Old->isTemplateParameterPack())) {
05355     if (Complain) {
05356       unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
05357       if (TemplateArgLoc.isValid()) {
05358         S.Diag(TemplateArgLoc,
05359              diag::err_template_arg_template_params_mismatch);
05360         NextDiag = diag::note_template_parameter_pack_non_pack;
05361       }
05362 
05363       unsigned ParamKind = isa<TemplateTypeParmDecl>(New)? 0
05364                       : isa<NonTypeTemplateParmDecl>(New)? 1
05365                       : 2;
05366       S.Diag(New->getLocation(), NextDiag)
05367         << ParamKind << New->isParameterPack();
05368       S.Diag(Old->getLocation(), diag::note_template_parameter_pack_here)
05369         << ParamKind << Old->isParameterPack();
05370     }
05371 
05372     return false;
05373   }
05374 
05375   // For non-type template parameters, check the type of the parameter.
05376   if (NonTypeTemplateParmDecl *OldNTTP
05377                                     = dyn_cast<NonTypeTemplateParmDecl>(Old)) {
05378     NonTypeTemplateParmDecl *NewNTTP = cast<NonTypeTemplateParmDecl>(New);
05379 
05380     // If we are matching a template template argument to a template
05381     // template parameter and one of the non-type template parameter types
05382     // is dependent, then we must wait until template instantiation time
05383     // to actually compare the arguments.
05384     if (Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
05385         (OldNTTP->getType()->isDependentType() ||
05386          NewNTTP->getType()->isDependentType()))
05387       return true;
05388 
05389     if (!S.Context.hasSameType(OldNTTP->getType(), NewNTTP->getType())) {
05390       if (Complain) {
05391         unsigned NextDiag = diag::err_template_nontype_parm_different_type;
05392         if (TemplateArgLoc.isValid()) {
05393           S.Diag(TemplateArgLoc,
05394                  diag::err_template_arg_template_params_mismatch);
05395           NextDiag = diag::note_template_nontype_parm_different_type;
05396         }
05397         S.Diag(NewNTTP->getLocation(), NextDiag)
05398           << NewNTTP->getType()
05399           << (Kind != Sema::TPL_TemplateMatch);
05400         S.Diag(OldNTTP->getLocation(),
05401                diag::note_template_nontype_parm_prev_declaration)
05402           << OldNTTP->getType();
05403       }
05404 
05405       return false;
05406     }
05407 
05408     return true;
05409   }
05410 
05411   // For template template parameters, check the template parameter types.
05412   // The template parameter lists of template template
05413   // parameters must agree.
05414   if (TemplateTemplateParmDecl *OldTTP
05415                                     = dyn_cast<TemplateTemplateParmDecl>(Old)) {
05416     TemplateTemplateParmDecl *NewTTP = cast<TemplateTemplateParmDecl>(New);
05417     return S.TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
05418                                             OldTTP->getTemplateParameters(),
05419                                             Complain,
05420                                         (Kind == Sema::TPL_TemplateMatch
05421                                            ? Sema::TPL_TemplateTemplateParmMatch
05422                                            : Kind),
05423                                             TemplateArgLoc);
05424   }
05425 
05426   return true;
05427 }
05428 
05429 /// \brief Diagnose a known arity mismatch when comparing template argument
05430 /// lists.
05431 static
05432 void DiagnoseTemplateParameterListArityMismatch(Sema &S,
05433                                                 TemplateParameterList *New,
05434                                                 TemplateParameterList *Old,
05435                                       Sema::TemplateParameterListEqualKind Kind,
05436                                                 SourceLocation TemplateArgLoc) {
05437   unsigned NextDiag = diag::err_template_param_list_different_arity;
05438   if (TemplateArgLoc.isValid()) {
05439     S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
05440     NextDiag = diag::note_template_param_list_different_arity;
05441   }
05442   S.Diag(New->getTemplateLoc(), NextDiag)
05443     << (New->size() > Old->size())
05444     << (Kind != Sema::TPL_TemplateMatch)
05445     << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
05446   S.Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
05447     << (Kind != Sema::TPL_TemplateMatch)
05448     << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
05449 }
05450 
05451 /// \brief Determine whether the given template parameter lists are
05452 /// equivalent.
05453 ///
05454 /// \param New  The new template parameter list, typically written in the
05455 /// source code as part of a new template declaration.
05456 ///
05457 /// \param Old  The old template parameter list, typically found via
05458 /// name lookup of the template declared with this template parameter
05459 /// list.
05460 ///
05461 /// \param Complain  If true, this routine will produce a diagnostic if
05462 /// the template parameter lists are not equivalent.
05463 ///
05464 /// \param Kind describes how we are to match the template parameter lists.
05465 ///
05466 /// \param TemplateArgLoc If this source location is valid, then we
05467 /// are actually checking the template parameter list of a template
05468 /// argument (New) against the template parameter list of its
05469 /// corresponding template template parameter (Old). We produce
05470 /// slightly different diagnostics in this scenario.
05471 ///
05472 /// \returns True if the template parameter lists are equal, false
05473 /// otherwise.
05474 bool
05475 Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
05476                                      TemplateParameterList *Old,
05477                                      bool Complain,
05478                                      TemplateParameterListEqualKind Kind,
05479                                      SourceLocation TemplateArgLoc) {
05480   if (Old->size() != New->size() && Kind != TPL_TemplateTemplateArgumentMatch) {
05481     if (Complain)
05482       DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
05483                                                  TemplateArgLoc);
05484 
05485     return false;
05486   }
05487 
05488   // C++0x [temp.arg.template]p3:
05489   //   A template-argument matches a template template-parameter (call it P)
05490   //   when each of the template parameters in the template-parameter-list of
05491   //   the template-argument's corresponding class template or alias template
05492   //   (call it A) matches the corresponding template parameter in the
05493   //   template-parameter-list of P. [...]
05494   TemplateParameterList::iterator NewParm = New->begin();
05495   TemplateParameterList::iterator NewParmEnd = New->end();
05496   for (TemplateParameterList::iterator OldParm = Old->begin(),
05497                                     OldParmEnd = Old->end();
05498        OldParm != OldParmEnd; ++OldParm) {
05499     if (Kind != TPL_TemplateTemplateArgumentMatch ||
05500         !(*OldParm)->isTemplateParameterPack()) {
05501       if (NewParm == NewParmEnd) {
05502         if (Complain)
05503           DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
05504                                                      TemplateArgLoc);
05505 
05506         return false;
05507       }
05508 
05509       if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
05510                                       Kind, TemplateArgLoc))
05511         return false;
05512 
05513       ++NewParm;
05514       continue;
05515     }
05516 
05517     // C++0x [temp.arg.template]p3:
05518     //   [...] When P's template- parameter-list contains a template parameter
05519     //   pack (14.5.3), the template parameter pack will match zero or more
05520     //   template parameters or template parameter packs in the
05521     //   template-parameter-list of A with the same type and form as the
05522     //   template parameter pack in P (ignoring whether those template
05523     //   parameters are template parameter packs).
05524     for (; NewParm != NewParmEnd; ++NewParm) {
05525       if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
05526                                       Kind, TemplateArgLoc))
05527         return false;
05528     }
05529   }
05530 
05531   // Make sure we exhausted all of the arguments.
05532   if (NewParm != NewParmEnd) {
05533     if (Complain)
05534       DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
05535                                                  TemplateArgLoc);
05536 
05537     return false;
05538   }
05539 
05540   return true;
05541 }
05542 
05543 /// \brief Check whether a template can be declared within this scope.
05544 ///
05545 /// If the template declaration is valid in this scope, returns
05546 /// false. Otherwise, issues a diagnostic and returns true.
05547 bool
05548 Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
05549   if (!S)
05550     return false;
05551 
05552   // Find the nearest enclosing declaration scope.
05553   while ((S->getFlags() & Scope::DeclScope) == 0 ||
05554          (S->getFlags() & Scope::TemplateParamScope) != 0)
05555     S = S->getParent();
05556 
05557   // C++ [temp]p4:
05558   //   A template [...] shall not have C linkage.
05559   DeclContext *Ctx = S->getEntity();
05560   if (Ctx && Ctx->isExternCContext())
05561     return Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
05562              << TemplateParams->getSourceRange();
05563 
05564   while (Ctx && isa<LinkageSpecDecl>(Ctx))
05565     Ctx = Ctx->getParent();
05566 
05567   // C++ [temp]p2:
05568   //   A template-declaration can appear only as a namespace scope or
05569   //   class scope declaration.
05570   if (Ctx) {
05571     if (Ctx->isFileContext())
05572       return false;
05573     if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Ctx)) {
05574       // C++ [temp.mem]p2:
05575       //   A local class shall not have member templates.
05576       if (RD->isLocalClass())
05577         return Diag(TemplateParams->getTemplateLoc(),
05578                     diag::err_template_inside_local_class)
05579           << TemplateParams->getSourceRange();
05580       else
05581         return false;
05582     }
05583   }
05584 
05585   return Diag(TemplateParams->getTemplateLoc(),
05586               diag::err_template_outside_namespace_or_class_scope)
05587     << TemplateParams->getSourceRange();
05588 }
05589 
05590 /// \brief Determine what kind of template specialization the given declaration
05591 /// is.
05592 static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D) {
05593   if (!D)
05594     return TSK_Undeclared;
05595 
05596   if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
05597     return Record->getTemplateSpecializationKind();
05598   if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
05599     return Function->getTemplateSpecializationKind();
05600   if (VarDecl *Var = dyn_cast<VarDecl>(D))
05601     return Var->getTemplateSpecializationKind();
05602 
05603   return TSK_Undeclared;
05604 }
05605 
05606 /// \brief Check whether a specialization is well-formed in the current
05607 /// context.
05608 ///
05609 /// This routine determines whether a template specialization can be declared
05610 /// in the current context (C++ [temp.expl.spec]p2).
05611 ///
05612 /// \param S the semantic analysis object for which this check is being
05613 /// performed.
05614 ///
05615 /// \param Specialized the entity being specialized or instantiated, which
05616 /// may be a kind of template (class template, function template, etc.) or
05617 /// a member of a class template (member function, static data member,
05618 /// member class).
05619 ///
05620 /// \param PrevDecl the previous declaration of this entity, if any.
05621 ///
05622 /// \param Loc the location of the explicit specialization or instantiation of
05623 /// this entity.
05624 ///
05625 /// \param IsPartialSpecialization whether this is a partial specialization of
05626 /// a class template.
05627 ///
05628 /// \returns true if there was an error that we cannot recover from, false
05629 /// otherwise.
05630 static bool CheckTemplateSpecializationScope(Sema &S,
05631                                              NamedDecl *Specialized,
05632                                              NamedDecl *PrevDecl,
05633                                              SourceLocation Loc,
05634                                              bool IsPartialSpecialization) {
05635   // Keep these "kind" numbers in sync with the %select statements in the
05636   // various diagnostics emitted by this routine.
05637   int EntityKind = 0;
05638   if (isa<ClassTemplateDecl>(Specialized))
05639     EntityKind = IsPartialSpecialization? 1 : 0;
05640   else if (isa<VarTemplateDecl>(Specialized))
05641     EntityKind = IsPartialSpecialization ? 3 : 2;
05642   else if (isa<FunctionTemplateDecl>(Specialized))
05643     EntityKind = 4;
05644   else if (isa<CXXMethodDecl>(Specialized))
05645     EntityKind = 5;
05646   else if (isa<VarDecl>(Specialized))
05647     EntityKind = 6;
05648   else if (isa<RecordDecl>(Specialized))
05649     EntityKind = 7;
05650   else if (isa<EnumDecl>(Specialized) && S.getLangOpts().CPlusPlus11)
05651     EntityKind = 8;
05652   else {
05653     S.Diag(Loc, diag::err_template_spec_unknown_kind)
05654       << S.getLangOpts().CPlusPlus11;
05655     S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
05656     return true;
05657   }
05658 
05659   // C++ [temp.expl.spec]p2:
05660   //   An explicit specialization shall be declared in the namespace
05661   //   of which the template is a member, or, for member templates, in
05662   //   the namespace of which the enclosing class or enclosing class
05663   //   template is a member. An explicit specialization of a member
05664   //   function, member class or static data member of a class
05665   //   template shall be declared in the namespace of which the class
05666   //   template is a member. Such a declaration may also be a
05667   //   definition. If the declaration is not a definition, the
05668   //   specialization may be defined later in the name- space in which
05669   //   the explicit specialization was declared, or in a namespace
05670   //   that encloses the one in which the explicit specialization was
05671   //   declared.
05672   if (S.CurContext->getRedeclContext()->isFunctionOrMethod()) {
05673     S.Diag(Loc, diag::err_template_spec_decl_function_scope)
05674       << Specialized;
05675     return true;
05676   }
05677 
05678   if (S.CurContext->isRecord() && !IsPartialSpecialization) {
05679     if (S.getLangOpts().MicrosoftExt) {
05680       // Do not warn for class scope explicit specialization during
05681       // instantiation, warning was already emitted during pattern
05682       // semantic analysis.
05683       if (!S.ActiveTemplateInstantiations.size())
05684         S.Diag(Loc, diag::ext_function_specialization_in_class)
05685           << Specialized;
05686     } else {
05687       S.Diag(Loc, diag::err_template_spec_decl_class_scope)
05688         << Specialized;
05689       return true;
05690     }
05691   }
05692 
05693   if (S.CurContext->isRecord() &&
05694       !S.CurContext->Equals(Specialized->getDeclContext())) {
05695     // Make sure that we're specializing in the right record context.
05696     // Otherwise, things can go horribly wrong.
05697     S.Diag(Loc, diag::err_template_spec_decl_class_scope)
05698       << Specialized;
05699     return true;
05700   }
05701   
05702   // C++ [temp.class.spec]p6:
05703   //   A class template partial specialization may be declared or redeclared
05704   //   in any namespace scope in which its definition may be defined (14.5.1
05705   //   and 14.5.2).
05706   DeclContext *SpecializedContext
05707     = Specialized->getDeclContext()->getEnclosingNamespaceContext();
05708   DeclContext *DC = S.CurContext->getEnclosingNamespaceContext();
05709 
05710   // Make sure that this redeclaration (or definition) occurs in an enclosing
05711   // namespace.
05712   // Note that HandleDeclarator() performs this check for explicit
05713   // specializations of function templates, static data members, and member
05714   // functions, so we skip the check here for those kinds of entities.
05715   // FIXME: HandleDeclarator's diagnostics aren't quite as good, though.
05716   // Should we refactor that check, so that it occurs later?
05717   if (!DC->Encloses(SpecializedContext) &&
05718       !(isa<FunctionTemplateDecl>(Specialized) ||
05719         isa<FunctionDecl>(Specialized) ||
05720         isa<VarTemplateDecl>(Specialized) ||
05721         isa<VarDecl>(Specialized))) {
05722     if (isa<TranslationUnitDecl>(SpecializedContext))
05723       S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
05724         << EntityKind << Specialized;
05725     else if (isa<NamespaceDecl>(SpecializedContext))
05726       S.Diag(Loc, diag::err_template_spec_redecl_out_of_scope)
05727         << EntityKind << Specialized
05728         << cast<NamedDecl>(SpecializedContext);
05729     else
05730       llvm_unreachable("unexpected namespace context for specialization");
05731 
05732     S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
05733   } else if ((!PrevDecl ||
05734               getTemplateSpecializationKind(PrevDecl) == TSK_Undeclared ||
05735               getTemplateSpecializationKind(PrevDecl) ==
05736                   TSK_ImplicitInstantiation)) {
05737     // C++ [temp.exp.spec]p2:
05738     //   An explicit specialization shall be declared in the namespace of which
05739     //   the template is a member, or, for member templates, in the namespace
05740     //   of which the enclosing class or enclosing class template is a member.
05741     //   An explicit specialization of a member function, member class or
05742     //   static data member of a class template shall be declared in the
05743     //   namespace of which the class template is a member.
05744     //
05745     // C++11 [temp.expl.spec]p2:
05746     //   An explicit specialization shall be declared in a namespace enclosing
05747     //   the specialized template.
05748     // C++11 [temp.explicit]p3:
05749     //   An explicit instantiation shall appear in an enclosing namespace of its
05750     //   template.
05751     if (!DC->InEnclosingNamespaceSetOf(SpecializedContext)) {
05752       bool IsCPlusPlus11Extension = DC->Encloses(SpecializedContext);
05753       if (isa<TranslationUnitDecl>(SpecializedContext)) {
05754         assert(!IsCPlusPlus11Extension &&
05755                "DC encloses TU but isn't in enclosing namespace set");
05756         S.Diag(Loc, diag::err_template_spec_decl_out_of_scope_global)
05757           << EntityKind << Specialized;
05758       } else if (isa<NamespaceDecl>(SpecializedContext)) {
05759         int Diag;
05760         if (!IsCPlusPlus11Extension)
05761           Diag = diag::err_template_spec_decl_out_of_scope;
05762         else if (!S.getLangOpts().CPlusPlus11)
05763           Diag = diag::ext_template_spec_decl_out_of_scope;
05764         else
05765           Diag = diag::warn_cxx98_compat_template_spec_decl_out_of_scope;
05766         S.Diag(Loc, Diag)
05767           << EntityKind << Specialized << cast<NamedDecl>(SpecializedContext);
05768       }
05769 
05770       S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
05771     }
05772   }
05773 
05774   return false;
05775 }
05776 
05777 static SourceRange findTemplateParameter(unsigned Depth, Expr *E) {
05778   if (!E->isInstantiationDependent())
05779     return SourceLocation();
05780   DependencyChecker Checker(Depth);
05781   Checker.TraverseStmt(E);
05782   if (Checker.Match && Checker.MatchLoc.isInvalid())
05783     return E->getSourceRange();
05784   return Checker.MatchLoc;
05785 }
05786 
05787 static SourceRange findTemplateParameter(unsigned Depth, TypeLoc TL) {
05788   if (!TL.getType()->isDependentType())
05789     return SourceLocation();
05790   DependencyChecker Checker(Depth);
05791   Checker.TraverseTypeLoc(TL);
05792   if (Checker.Match && Checker.MatchLoc.isInvalid())
05793     return TL.getSourceRange();
05794   return Checker.MatchLoc;
05795 }
05796 
05797 /// \brief Subroutine of Sema::CheckTemplatePartialSpecializationArgs
05798 /// that checks non-type template partial specialization arguments.
05799 static bool CheckNonTypeTemplatePartialSpecializationArgs(
05800     Sema &S, SourceLocation TemplateNameLoc, NonTypeTemplateParmDecl *Param,
05801     const TemplateArgument *Args, unsigned NumArgs, bool IsDefaultArgument) {
05802   for (unsigned I = 0; I != NumArgs; ++I) {
05803     if (Args[I].getKind() == TemplateArgument::Pack) {
05804       if (CheckNonTypeTemplatePartialSpecializationArgs(
05805               S, TemplateNameLoc, Param, Args[I].pack_begin(),
05806               Args[I].pack_size(), IsDefaultArgument))
05807         return true;
05808 
05809       continue;
05810     }
05811 
05812     if (Args[I].getKind() != TemplateArgument::Expression)
05813       continue;
05814 
05815     Expr *ArgExpr = Args[I].getAsExpr();
05816 
05817     // We can have a pack expansion of any of the bullets below.
05818     if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(ArgExpr))
05819       ArgExpr = Expansion->getPattern();
05820 
05821     // Strip off any implicit casts we added as part of type checking.
05822     while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
05823       ArgExpr = ICE->getSubExpr();
05824 
05825     // C++ [temp.class.spec]p8:
05826     //   A non-type argument is non-specialized if it is the name of a
05827     //   non-type parameter. All other non-type arguments are
05828     //   specialized.
05829     //
05830     // Below, we check the two conditions that only apply to
05831     // specialized non-type arguments, so skip any non-specialized
05832     // arguments.
05833     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
05834       if (isa<NonTypeTemplateParmDecl>(DRE->getDecl()))
05835         continue;
05836 
05837     // C++ [temp.class.spec]p9:
05838     //   Within the argument list of a class template partial
05839     //   specialization, the following restrictions apply:
05840     //     -- A partially specialized non-type argument expression
05841     //        shall not involve a template parameter of the partial
05842     //        specialization except when the argument expression is a
05843     //        simple identifier.
05844     SourceRange ParamUseRange =
05845         findTemplateParameter(Param->getDepth(), ArgExpr);
05846     if (ParamUseRange.isValid()) {
05847       if (IsDefaultArgument) {
05848         S.Diag(TemplateNameLoc,
05849                diag::err_dependent_non_type_arg_in_partial_spec);
05850         S.Diag(ParamUseRange.getBegin(),
05851                diag::note_dependent_non_type_default_arg_in_partial_spec)
05852           << ParamUseRange;
05853       } else {
05854         S.Diag(ParamUseRange.getBegin(),
05855                diag::err_dependent_non_type_arg_in_partial_spec)
05856           << ParamUseRange;
05857       }
05858       return true;
05859     }
05860 
05861     //     -- The type of a template parameter corresponding to a
05862     //        specialized non-type argument shall not be dependent on a
05863     //        parameter of the specialization.
05864     //
05865     // FIXME: We need to delay this check until instantiation in some cases:
05866     //
05867     //   template<template<typename> class X> struct A {
05868     //     template<typename T, X<T> N> struct B;
05869     //     template<typename T> struct B<T, 0>;
05870     //   };
05871     //   template<typename> using X = int;
05872     //   A<X>::B<int, 0> b;
05873     ParamUseRange = findTemplateParameter(
05874             Param->getDepth(), Param->getTypeSourceInfo()->getTypeLoc());
05875     if (ParamUseRange.isValid()) {
05876       S.Diag(IsDefaultArgument ? TemplateNameLoc : ArgExpr->getLocStart(),
05877              diag::err_dependent_typed_non_type_arg_in_partial_spec)
05878         << Param->getType() << ParamUseRange;
05879       S.Diag(Param->getLocation(), diag::note_template_param_here)
05880         << (IsDefaultArgument ? ParamUseRange : SourceRange());
05881       return true;
05882     }
05883   }
05884 
05885   return false;
05886 }
05887 
05888 /// \brief Check the non-type template arguments of a class template
05889 /// partial specialization according to C++ [temp.class.spec]p9.
05890 ///
05891 /// \param TemplateNameLoc the location of the template name.
05892 /// \param TemplateParams the template parameters of the primary class
05893 ///        template.
05894 /// \param NumExplicit the number of explicitly-specified template arguments.
05895 /// \param TemplateArgs the template arguments of the class template
05896 ///        partial specialization.
05897 ///
05898 /// \returns \c true if there was an error, \c false otherwise.
05899 static bool CheckTemplatePartialSpecializationArgs(
05900     Sema &S, SourceLocation TemplateNameLoc,
05901     TemplateParameterList *TemplateParams, unsigned NumExplicit,
05902     SmallVectorImpl<TemplateArgument> &TemplateArgs) {
05903   const TemplateArgument *ArgList = TemplateArgs.data();
05904 
05905   for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
05906     NonTypeTemplateParmDecl *Param
05907       = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
05908     if (!Param)
05909       continue;
05910 
05911     if (CheckNonTypeTemplatePartialSpecializationArgs(
05912             S, TemplateNameLoc, Param, &ArgList[I], 1, I >= NumExplicit))
05913       return true;
05914   }
05915 
05916   return false;
05917 }
05918 
05919 DeclResult
05920 Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec,
05921                                        TagUseKind TUK,
05922                                        SourceLocation KWLoc,
05923                                        SourceLocation ModulePrivateLoc,
05924                                        TemplateIdAnnotation &TemplateId,
05925                                        AttributeList *Attr,
05926                                MultiTemplateParamsArg TemplateParameterLists) {
05927   assert(TUK != TUK_Reference && "References are not specializations");
05928 
05929   CXXScopeSpec &SS = TemplateId.SS;
05930 
05931   // NOTE: KWLoc is the location of the tag keyword. This will instead
05932   // store the location of the outermost template keyword in the declaration.
05933   SourceLocation TemplateKWLoc = TemplateParameterLists.size() > 0
05934     ? TemplateParameterLists[0]->getTemplateLoc() : KWLoc;
05935   SourceLocation TemplateNameLoc = TemplateId.TemplateNameLoc;
05936   SourceLocation LAngleLoc = TemplateId.LAngleLoc;
05937   SourceLocation RAngleLoc = TemplateId.RAngleLoc;
05938 
05939   // Find the class template we're specializing
05940   TemplateName Name = TemplateId.Template.get();
05941   ClassTemplateDecl *ClassTemplate
05942     = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
05943 
05944   if (!ClassTemplate) {
05945     Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
05946       << (Name.getAsTemplateDecl() &&
05947           isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
05948     return true;
05949   }
05950 
05951   bool isExplicitSpecialization = false;
05952   bool isPartialSpecialization = false;
05953 
05954   // Check the validity of the template headers that introduce this
05955   // template.
05956   // FIXME: We probably shouldn't complain about these headers for
05957   // friend declarations.
05958   bool Invalid = false;
05959   TemplateParameterList *TemplateParams =
05960       MatchTemplateParametersToScopeSpecifier(
05961           KWLoc, TemplateNameLoc, SS, &TemplateId,
05962           TemplateParameterLists, TUK == TUK_Friend, isExplicitSpecialization,
05963           Invalid);
05964   if (Invalid)
05965     return true;
05966 
05967   if (TemplateParams && TemplateParams->size() > 0) {
05968     isPartialSpecialization = true;
05969 
05970     if (TUK == TUK_Friend) {
05971       Diag(KWLoc, diag::err_partial_specialization_friend)
05972         << SourceRange(LAngleLoc, RAngleLoc);
05973       return true;
05974     }
05975 
05976     // C++ [temp.class.spec]p10:
05977     //   The template parameter list of a specialization shall not
05978     //   contain default template argument values.
05979     for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
05980       Decl *Param = TemplateParams->getParam(I);
05981       if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
05982         if (TTP->hasDefaultArgument()) {
05983           Diag(TTP->getDefaultArgumentLoc(),
05984                diag::err_default_arg_in_partial_spec);
05985           TTP->removeDefaultArgument();
05986         }
05987       } else if (NonTypeTemplateParmDecl *NTTP
05988                    = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
05989         if (Expr *DefArg = NTTP->getDefaultArgument()) {
05990           Diag(NTTP->getDefaultArgumentLoc(),
05991                diag::err_default_arg_in_partial_spec)
05992             << DefArg->getSourceRange();
05993           NTTP->removeDefaultArgument();
05994         }
05995       } else {
05996         TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
05997         if (TTP->hasDefaultArgument()) {
05998           Diag(TTP->getDefaultArgument().getLocation(),
05999                diag::err_default_arg_in_partial_spec)
06000             << TTP->getDefaultArgument().getSourceRange();
06001           TTP->removeDefaultArgument();
06002         }
06003       }
06004     }
06005   } else if (TemplateParams) {
06006     if (TUK == TUK_Friend)
06007       Diag(KWLoc, diag::err_template_spec_friend)
06008         << FixItHint::CreateRemoval(
06009                                 SourceRange(TemplateParams->getTemplateLoc(),
06010                                             TemplateParams->getRAngleLoc()))
06011         << SourceRange(LAngleLoc, RAngleLoc);
06012     else
06013       isExplicitSpecialization = true;
06014   } else {
06015     assert(TUK == TUK_Friend && "should have a 'template<>' for this decl");
06016   }
06017 
06018   // Check that the specialization uses the same tag kind as the
06019   // original template.
06020   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
06021   assert(Kind != TTK_Enum && "Invalid enum tag in class template spec!");
06022   if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
06023                                     Kind, TUK == TUK_Definition, KWLoc,
06024                                     *ClassTemplate->getIdentifier())) {
06025     Diag(KWLoc, diag::err_use_with_wrong_tag)
06026       << ClassTemplate
06027       << FixItHint::CreateReplacement(KWLoc,
06028                             ClassTemplate->getTemplatedDecl()->getKindName());
06029     Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
06030          diag::note_previous_use);
06031     Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
06032   }
06033 
06034   // Translate the parser's template argument list in our AST format.
06035   TemplateArgumentListInfo TemplateArgs =
06036       makeTemplateArgumentListInfo(*this, TemplateId);
06037 
06038   // Check for unexpanded parameter packs in any of the template arguments.
06039   for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
06040     if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
06041                                         UPPC_PartialSpecialization))
06042       return true;
06043 
06044   // Check that the template argument list is well-formed for this
06045   // template.
06046   SmallVector<TemplateArgument, 4> Converted;
06047   if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
06048                                 TemplateArgs, false, Converted))
06049     return true;
06050 
06051   // Find the class template (partial) specialization declaration that
06052   // corresponds to these arguments.
06053   if (isPartialSpecialization) {
06054     if (CheckTemplatePartialSpecializationArgs(
06055             *this, TemplateNameLoc, ClassTemplate->getTemplateParameters(),
06056             TemplateArgs.size(), Converted))
06057       return true;
06058 
06059     bool InstantiationDependent;
06060     if (!Name.isDependent() &&
06061         !TemplateSpecializationType::anyDependentTemplateArguments(
06062                                              TemplateArgs.getArgumentArray(),
06063                                                          TemplateArgs.size(),
06064                                                      InstantiationDependent)) {
06065       Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
06066         << ClassTemplate->getDeclName();
06067       isPartialSpecialization = false;
06068     }
06069   }
06070 
06071   void *InsertPos = nullptr;
06072   ClassTemplateSpecializationDecl *PrevDecl = nullptr;
06073 
06074   if (isPartialSpecialization)
06075     // FIXME: Template parameter list matters, too
06076     PrevDecl = ClassTemplate->findPartialSpecialization(Converted, InsertPos);
06077   else
06078     PrevDecl = ClassTemplate->findSpecialization(Converted, InsertPos);
06079 
06080   ClassTemplateSpecializationDecl *Specialization = nullptr;
06081 
06082   // Check whether we can declare a class template specialization in
06083   // the current scope.
06084   if (TUK != TUK_Friend &&
06085       CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
06086                                        TemplateNameLoc,
06087                                        isPartialSpecialization))
06088     return true;
06089 
06090   // The canonical type
06091   QualType CanonType;
06092   if (isPartialSpecialization) {
06093     // Build the canonical type that describes the converted template
06094     // arguments of the class template partial specialization.
06095     TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
06096     CanonType = Context.getTemplateSpecializationType(CanonTemplate,
06097                                                       Converted.data(),
06098                                                       Converted.size());
06099 
06100     if (Context.hasSameType(CanonType,
06101                         ClassTemplate->getInjectedClassNameSpecialization())) {
06102       // C++ [temp.class.spec]p9b3:
06103       //
06104       //   -- The argument list of the specialization shall not be identical
06105       //      to the implicit argument list of the primary template.
06106       Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
06107         << /*class template*/0 << (TUK == TUK_Definition)
06108         << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
06109       return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
06110                                 ClassTemplate->getIdentifier(),
06111                                 TemplateNameLoc,
06112                                 Attr,
06113                                 TemplateParams,
06114                                 AS_none, /*ModulePrivateLoc=*/SourceLocation(),
06115                                 /*FriendLoc*/SourceLocation(),
06116                                 TemplateParameterLists.size() - 1,
06117                                 TemplateParameterLists.data());
06118     }
06119 
06120     // Create a new class template partial specialization declaration node.
06121     ClassTemplatePartialSpecializationDecl *PrevPartial
06122       = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
06123     ClassTemplatePartialSpecializationDecl *Partial
06124       = ClassTemplatePartialSpecializationDecl::Create(Context, Kind,
06125                                              ClassTemplate->getDeclContext(),
06126                                                        KWLoc, TemplateNameLoc,
06127                                                        TemplateParams,
06128                                                        ClassTemplate,
06129                                                        Converted.data(),
06130                                                        Converted.size(),
06131                                                        TemplateArgs,
06132                                                        CanonType,
06133                                                        PrevPartial);
06134     SetNestedNameSpecifier(Partial, SS);
06135     if (TemplateParameterLists.size() > 1 && SS.isSet()) {
06136       Partial->setTemplateParameterListsInfo(Context,
06137                                              TemplateParameterLists.size() - 1,
06138                                              TemplateParameterLists.data());
06139     }
06140 
06141     if (!PrevPartial)
06142       ClassTemplate->AddPartialSpecialization(Partial, InsertPos);
06143     Specialization = Partial;
06144 
06145     // If we are providing an explicit specialization of a member class
06146     // template specialization, make a note of that.
06147     if (PrevPartial && PrevPartial->getInstantiatedFromMember())
06148       PrevPartial->setMemberSpecialization();
06149 
06150     // Check that all of the template parameters of the class template
06151     // partial specialization are deducible from the template
06152     // arguments. If not, this class template partial specialization
06153     // will never be used.
06154     llvm::SmallBitVector DeducibleParams(TemplateParams->size());
06155     MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
06156                                TemplateParams->getDepth(),
06157                                DeducibleParams);
06158 
06159     if (!DeducibleParams.all()) {
06160       unsigned NumNonDeducible = DeducibleParams.size()-DeducibleParams.count();
06161       Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
06162         << /*class template*/0 << (NumNonDeducible > 1)
06163         << SourceRange(TemplateNameLoc, RAngleLoc);
06164       for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
06165         if (!DeducibleParams[I]) {
06166           NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
06167           if (Param->getDeclName())
06168             Diag(Param->getLocation(),
06169                  diag::note_partial_spec_unused_parameter)
06170               << Param->getDeclName();
06171           else
06172             Diag(Param->getLocation(),
06173                  diag::note_partial_spec_unused_parameter)
06174               << "(anonymous)";
06175         }
06176       }
06177     }
06178   } else {
06179     // Create a new class template specialization declaration node for
06180     // this explicit specialization or friend declaration.
06181     Specialization
06182       = ClassTemplateSpecializationDecl::Create(Context, Kind,
06183                                              ClassTemplate->getDeclContext(),
06184                                                 KWLoc, TemplateNameLoc,
06185                                                 ClassTemplate,
06186                                                 Converted.data(),
06187                                                 Converted.size(),
06188                                                 PrevDecl);
06189     SetNestedNameSpecifier(Specialization, SS);
06190     if (TemplateParameterLists.size() > 0) {
06191       Specialization->setTemplateParameterListsInfo(Context,
06192                                               TemplateParameterLists.size(),
06193                                               TemplateParameterLists.data());
06194     }
06195 
06196     if (!PrevDecl)
06197       ClassTemplate->AddSpecialization(Specialization, InsertPos);
06198 
06199     CanonType = Context.getTypeDeclType(Specialization);
06200   }
06201 
06202   // C++ [temp.expl.spec]p6:
06203   //   If a template, a member template or the member of a class template is
06204   //   explicitly specialized then that specialization shall be declared
06205   //   before the first use of that specialization that would cause an implicit
06206   //   instantiation to take place, in every translation unit in which such a
06207   //   use occurs; no diagnostic is required.
06208   if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
06209     bool Okay = false;
06210     for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
06211       // Is there any previous explicit specialization declaration?
06212       if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
06213         Okay = true;
06214         break;
06215       }
06216     }
06217 
06218     if (!Okay) {
06219       SourceRange Range(TemplateNameLoc, RAngleLoc);
06220       Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
06221         << Context.getTypeDeclType(Specialization) << Range;
06222 
06223       Diag(PrevDecl->getPointOfInstantiation(),
06224            diag::note_instantiation_required_here)
06225         << (PrevDecl->getTemplateSpecializationKind()
06226                                                 != TSK_ImplicitInstantiation);
06227       return true;
06228     }
06229   }
06230 
06231   // If this is not a friend, note that this is an explicit specialization.
06232   if (TUK != TUK_Friend)
06233     Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
06234 
06235   // Check that this isn't a redefinition of this specialization.
06236   if (TUK == TUK_Definition) {
06237     if (RecordDecl *Def = Specialization->getDefinition()) {
06238       SourceRange Range(TemplateNameLoc, RAngleLoc);
06239       Diag(TemplateNameLoc, diag::err_redefinition)
06240         << Context.getTypeDeclType(Specialization) << Range;
06241       Diag(Def->getLocation(), diag::note_previous_definition);
06242       Specialization->setInvalidDecl();
06243       return true;
06244     }
06245   }
06246 
06247   if (Attr)
06248     ProcessDeclAttributeList(S, Specialization, Attr);
06249 
06250   // Add alignment attributes if necessary; these attributes are checked when
06251   // the ASTContext lays out the structure.
06252   if (TUK == TUK_Definition) {
06253     AddAlignmentAttributesForRecord(Specialization);
06254     AddMsStructLayoutForRecord(Specialization);
06255   }
06256 
06257   if (ModulePrivateLoc.isValid())
06258     Diag(Specialization->getLocation(), diag::err_module_private_specialization)
06259       << (isPartialSpecialization? 1 : 0)
06260       << FixItHint::CreateRemoval(ModulePrivateLoc);
06261   
06262   // Build the fully-sugared type for this class template
06263   // specialization as the user wrote in the specialization
06264   // itself. This means that we'll pretty-print the type retrieved
06265   // from the specialization's declaration the way that the user
06266   // actually wrote the specialization, rather than formatting the
06267   // name based on the "canonical" representation used to store the
06268   // template arguments in the specialization.
06269   TypeSourceInfo *WrittenTy
06270     = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
06271                                                 TemplateArgs, CanonType);
06272   if (TUK != TUK_Friend) {
06273     Specialization->setTypeAsWritten(WrittenTy);
06274     Specialization->setTemplateKeywordLoc(TemplateKWLoc);
06275   }
06276 
06277   // C++ [temp.expl.spec]p9:
06278   //   A template explicit specialization is in the scope of the
06279   //   namespace in which the template was defined.
06280   //
06281   // We actually implement this paragraph where we set the semantic
06282   // context (in the creation of the ClassTemplateSpecializationDecl),
06283   // but we also maintain the lexical context where the actual
06284   // definition occurs.
06285   Specialization->setLexicalDeclContext(CurContext);
06286 
06287   // We may be starting the definition of this specialization.
06288   if (TUK == TUK_Definition)
06289     Specialization->startDefinition();
06290 
06291   if (TUK == TUK_Friend) {
06292     FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
06293                                             TemplateNameLoc,
06294                                             WrittenTy,
06295                                             /*FIXME:*/KWLoc);
06296     Friend->setAccess(AS_public);
06297     CurContext->addDecl(Friend);
06298   } else {
06299     // Add the specialization into its lexical context, so that it can
06300     // be seen when iterating through the list of declarations in that
06301     // context. However, specializations are not found by name lookup.
06302     CurContext->addDecl(Specialization);
06303   }
06304   return Specialization;
06305 }
06306 
06307 Decl *Sema::ActOnTemplateDeclarator(Scope *S,
06308                               MultiTemplateParamsArg TemplateParameterLists,
06309                                     Declarator &D) {
06310   Decl *NewDecl = HandleDeclarator(S, D, TemplateParameterLists);
06311   ActOnDocumentableDecl(NewDecl);
06312   return NewDecl;
06313 }
06314 
06315 Decl *Sema::ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope,
06316                                MultiTemplateParamsArg TemplateParameterLists,
06317                                             Declarator &D) {
06318   assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
06319   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
06320 
06321   if (FTI.hasPrototype) {
06322     // FIXME: Diagnose arguments without names in C.
06323   }
06324 
06325   Scope *ParentScope = FnBodyScope->getParent();
06326 
06327   D.setFunctionDefinitionKind(FDK_Definition);
06328   Decl *DP = HandleDeclarator(ParentScope, D,
06329                               TemplateParameterLists);
06330   return ActOnStartOfFunctionDef(FnBodyScope, DP);
06331 }
06332 
06333 /// \brief Strips various properties off an implicit instantiation
06334 /// that has just been explicitly specialized.
06335 static void StripImplicitInstantiation(NamedDecl *D) {
06336   D->dropAttrs();
06337 
06338   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
06339     FD->setInlineSpecified(false);
06340 
06341     for (auto I : FD->params())
06342       I->dropAttrs();
06343   }
06344 }
06345 
06346 /// \brief Compute the diagnostic location for an explicit instantiation
06347 //  declaration or definition.
06348 static SourceLocation DiagLocForExplicitInstantiation(
06349     NamedDecl* D, SourceLocation PointOfInstantiation) {
06350   // Explicit instantiations following a specialization have no effect and
06351   // hence no PointOfInstantiation. In that case, walk decl backwards
06352   // until a valid name loc is found.
06353   SourceLocation PrevDiagLoc = PointOfInstantiation;
06354   for (Decl *Prev = D; Prev && !PrevDiagLoc.isValid();
06355        Prev = Prev->getPreviousDecl()) {
06356     PrevDiagLoc = Prev->getLocation();
06357   }
06358   assert(PrevDiagLoc.isValid() &&
06359          "Explicit instantiation without point of instantiation?");
06360   return PrevDiagLoc;
06361 }
06362 
06363 /// \brief Diagnose cases where we have an explicit template specialization
06364 /// before/after an explicit template instantiation, producing diagnostics
06365 /// for those cases where they are required and determining whether the
06366 /// new specialization/instantiation will have any effect.
06367 ///
06368 /// \param NewLoc the location of the new explicit specialization or
06369 /// instantiation.
06370 ///
06371 /// \param NewTSK the kind of the new explicit specialization or instantiation.
06372 ///
06373 /// \param PrevDecl the previous declaration of the entity.
06374 ///
06375 /// \param PrevTSK the kind of the old explicit specialization or instantiatin.
06376 ///
06377 /// \param PrevPointOfInstantiation if valid, indicates where the previus
06378 /// declaration was instantiated (either implicitly or explicitly).
06379 ///
06380 /// \param HasNoEffect will be set to true to indicate that the new
06381 /// specialization or instantiation has no effect and should be ignored.
06382 ///
06383 /// \returns true if there was an error that should prevent the introduction of
06384 /// the new declaration into the AST, false otherwise.
06385 bool
06386 Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
06387                                              TemplateSpecializationKind NewTSK,
06388                                              NamedDecl *PrevDecl,
06389                                              TemplateSpecializationKind PrevTSK,
06390                                         SourceLocation PrevPointOfInstantiation,
06391                                              bool &HasNoEffect) {
06392   HasNoEffect = false;
06393 
06394   switch (NewTSK) {
06395   case TSK_Undeclared:
06396   case TSK_ImplicitInstantiation:
06397     assert(
06398         (PrevTSK == TSK_Undeclared || PrevTSK == TSK_ImplicitInstantiation) &&
06399         "previous declaration must be implicit!");
06400     return false;
06401 
06402   case TSK_ExplicitSpecialization:
06403     switch (PrevTSK) {
06404     case TSK_Undeclared:
06405     case TSK_ExplicitSpecialization:
06406       // Okay, we're just specializing something that is either already
06407       // explicitly specialized or has merely been mentioned without any
06408       // instantiation.
06409       return false;
06410 
06411     case TSK_ImplicitInstantiation:
06412       if (PrevPointOfInstantiation.isInvalid()) {
06413         // The declaration itself has not actually been instantiated, so it is
06414         // still okay to specialize it.
06415         StripImplicitInstantiation(PrevDecl);
06416         return false;
06417       }
06418       // Fall through
06419 
06420     case TSK_ExplicitInstantiationDeclaration:
06421     case TSK_ExplicitInstantiationDefinition:
06422       assert((PrevTSK == TSK_ImplicitInstantiation ||
06423               PrevPointOfInstantiation.isValid()) &&
06424              "Explicit instantiation without point of instantiation?");
06425 
06426       // C++ [temp.expl.spec]p6:
06427       //   If a template, a member template or the member of a class template
06428       //   is explicitly specialized then that specialization shall be declared
06429       //   before the first use of that specialization that would cause an
06430       //   implicit instantiation to take place, in every translation unit in
06431       //   which such a use occurs; no diagnostic is required.
06432       for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
06433         // Is there any previous explicit specialization declaration?
06434         if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization)
06435           return false;
06436       }
06437 
06438       Diag(NewLoc, diag::err_specialization_after_instantiation)
06439         << PrevDecl;
06440       Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
06441         << (PrevTSK != TSK_ImplicitInstantiation);
06442 
06443       return true;
06444     }
06445 
06446   case TSK_ExplicitInstantiationDeclaration:
06447     switch (PrevTSK) {
06448     case TSK_ExplicitInstantiationDeclaration:
06449       // This explicit instantiation declaration is redundant (that's okay).
06450       HasNoEffect = true;
06451       return false;
06452 
06453     case TSK_Undeclared:
06454     case TSK_ImplicitInstantiation:
06455       // We're explicitly instantiating something that may have already been
06456       // implicitly instantiated; that's fine.
06457       return false;
06458 
06459     case TSK_ExplicitSpecialization:
06460       // C++0x [temp.explicit]p4:
06461       //   For a given set of template parameters, if an explicit instantiation
06462       //   of a template appears after a declaration of an explicit
06463       //   specialization for that template, the explicit instantiation has no
06464       //   effect.
06465       HasNoEffect = true;
06466       return false;
06467 
06468     case TSK_ExplicitInstantiationDefinition:
06469       // C++0x [temp.explicit]p10:
06470       //   If an entity is the subject of both an explicit instantiation
06471       //   declaration and an explicit instantiation definition in the same
06472       //   translation unit, the definition shall follow the declaration.
06473       Diag(NewLoc,
06474            diag::err_explicit_instantiation_declaration_after_definition);
06475 
06476       // Explicit instantiations following a specialization have no effect and
06477       // hence no PrevPointOfInstantiation. In that case, walk decl backwards
06478       // until a valid name loc is found.
06479       Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
06480            diag::note_explicit_instantiation_definition_here);
06481       HasNoEffect = true;
06482       return false;
06483     }
06484 
06485   case TSK_ExplicitInstantiationDefinition:
06486     switch (PrevTSK) {
06487     case TSK_Undeclared:
06488     case TSK_ImplicitInstantiation:
06489       // We're explicitly instantiating something that may have already been
06490       // implicitly instantiated; that's fine.
06491       return false;
06492 
06493     case TSK_ExplicitSpecialization:
06494       // C++ DR 259, C++0x [temp.explicit]p4:
06495       //   For a given set of template parameters, if an explicit
06496       //   instantiation of a template appears after a declaration of
06497       //   an explicit specialization for that template, the explicit
06498       //   instantiation has no effect.
06499       //
06500       // In C++98/03 mode, we only give an extension warning here, because it
06501       // is not harmful to try to explicitly instantiate something that
06502       // has been explicitly specialized.
06503       Diag(NewLoc, getLangOpts().CPlusPlus11 ?
06504            diag::warn_cxx98_compat_explicit_instantiation_after_specialization :
06505            diag::ext_explicit_instantiation_after_specialization)
06506         << PrevDecl;
06507       Diag(PrevDecl->getLocation(),
06508            diag::note_previous_template_specialization);
06509       HasNoEffect = true;
06510       return false;
06511 
06512     case TSK_ExplicitInstantiationDeclaration:
06513       // We're explicity instantiating a definition for something for which we
06514       // were previously asked to suppress instantiations. That's fine.
06515 
06516       // C++0x [temp.explicit]p4:
06517       //   For a given set of template parameters, if an explicit instantiation
06518       //   of a template appears after a declaration of an explicit
06519       //   specialization for that template, the explicit instantiation has no
06520       //   effect.
06521       for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
06522         // Is there any previous explicit specialization declaration?
06523         if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
06524           HasNoEffect = true;
06525           break;
06526         }
06527       }
06528 
06529       return false;
06530 
06531     case TSK_ExplicitInstantiationDefinition:
06532       // C++0x [temp.spec]p5:
06533       //   For a given template and a given set of template-arguments,
06534       //     - an explicit instantiation definition shall appear at most once
06535       //       in a program,
06536 
06537       // MSVCCompat: MSVC silently ignores duplicate explicit instantiations.
06538       Diag(NewLoc, (getLangOpts().MSVCCompat)
06539                        ? diag::ext_explicit_instantiation_duplicate
06540                        : diag::err_explicit_instantiation_duplicate)
06541           << PrevDecl;
06542       Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
06543            diag::note_previous_explicit_instantiation);
06544       HasNoEffect = true;
06545       return false;
06546     }
06547   }
06548 
06549   llvm_unreachable("Missing specialization/instantiation case?");
06550 }
06551 
06552 /// \brief Perform semantic analysis for the given dependent function
06553 /// template specialization.
06554 ///
06555 /// The only possible way to get a dependent function template specialization
06556 /// is with a friend declaration, like so:
06557 ///
06558 /// \code
06559 ///   template <class T> void foo(T);
06560 ///   template <class T> class A {
06561 ///     friend void foo<>(T);
06562 ///   };
06563 /// \endcode
06564 ///
06565 /// There really isn't any useful analysis we can do here, so we
06566 /// just store the information.
06567 bool
06568 Sema::CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
06569                    const TemplateArgumentListInfo &ExplicitTemplateArgs,
06570                                                    LookupResult &Previous) {
06571   // Remove anything from Previous that isn't a function template in
06572   // the correct context.
06573   DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
06574   LookupResult::Filter F = Previous.makeFilter();
06575   while (F.hasNext()) {
06576     NamedDecl *D = F.next()->getUnderlyingDecl();
06577     if (!isa<FunctionTemplateDecl>(D) ||
06578         !FDLookupContext->InEnclosingNamespaceSetOf(
06579                               D->getDeclContext()->getRedeclContext()))
06580       F.erase();
06581   }
06582   F.done();
06583 
06584   // Should this be diagnosed here?
06585   if (Previous.empty()) return true;
06586 
06587   FD->setDependentTemplateSpecialization(Context, Previous.asUnresolvedSet(),
06588                                          ExplicitTemplateArgs);
06589   return false;
06590 }
06591 
06592 /// \brief Perform semantic analysis for the given function template
06593 /// specialization.
06594 ///
06595 /// This routine performs all of the semantic analysis required for an
06596 /// explicit function template specialization. On successful completion,
06597 /// the function declaration \p FD will become a function template
06598 /// specialization.
06599 ///
06600 /// \param FD the function declaration, which will be updated to become a
06601 /// function template specialization.
06602 ///
06603 /// \param ExplicitTemplateArgs the explicitly-provided template arguments,
06604 /// if any. Note that this may be valid info even when 0 arguments are
06605 /// explicitly provided as in, e.g., \c void sort<>(char*, char*);
06606 /// as it anyway contains info on the angle brackets locations.
06607 ///
06608 /// \param Previous the set of declarations that may be specialized by
06609 /// this function specialization.
06610 bool Sema::CheckFunctionTemplateSpecialization(
06611     FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs,
06612     LookupResult &Previous) {
06613   // The set of function template specializations that could match this
06614   // explicit function template specialization.
06615   UnresolvedSet<8> Candidates;
06616   TemplateSpecCandidateSet FailedCandidates(FD->getLocation());
06617 
06618   DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
06619   for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
06620          I != E; ++I) {
06621     NamedDecl *Ovl = (*I)->getUnderlyingDecl();
06622     if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
06623       // Only consider templates found within the same semantic lookup scope as
06624       // FD.
06625       if (!FDLookupContext->InEnclosingNamespaceSetOf(
06626                                 Ovl->getDeclContext()->getRedeclContext()))
06627         continue;
06628 
06629       // When matching a constexpr member function template specialization
06630       // against the primary template, we don't yet know whether the
06631       // specialization has an implicit 'const' (because we don't know whether
06632       // it will be a static member function until we know which template it
06633       // specializes), so adjust it now assuming it specializes this template.
06634       QualType FT = FD->getType();
06635       if (FD->isConstexpr()) {
06636         CXXMethodDecl *OldMD =
06637           dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
06638         if (OldMD && OldMD->isConst()) {
06639           const FunctionProtoType *FPT = FT->castAs<FunctionProtoType>();
06640           FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
06641           EPI.TypeQuals |= Qualifiers::Const;
06642           FT = Context.getFunctionType(FPT->getReturnType(),
06643                                        FPT->getParamTypes(), EPI);
06644         }
06645       }
06646 
06647       // C++ [temp.expl.spec]p11:
06648       //   A trailing template-argument can be left unspecified in the
06649       //   template-id naming an explicit function template specialization
06650       //   provided it can be deduced from the function argument type.
06651       // Perform template argument deduction to determine whether we may be
06652       // specializing this template.
06653       // FIXME: It is somewhat wasteful to build
06654       TemplateDeductionInfo Info(FailedCandidates.getLocation());
06655       FunctionDecl *Specialization = nullptr;
06656       if (TemplateDeductionResult TDK = DeduceTemplateArguments(
06657               cast<FunctionTemplateDecl>(FunTmpl->getFirstDecl()),
06658               ExplicitTemplateArgs, FT, Specialization, Info)) {
06659         // Template argument deduction failed; record why it failed, so
06660         // that we can provide nifty diagnostics.
06661         FailedCandidates.addCandidate()
06662             .set(FunTmpl->getTemplatedDecl(),
06663                  MakeDeductionFailureInfo(Context, TDK, Info));
06664         (void)TDK;
06665         continue;
06666       }
06667 
06668       // Record this candidate.
06669       Candidates.addDecl(Specialization, I.getAccess());
06670     }
06671   }
06672 
06673   // Find the most specialized function template.
06674   UnresolvedSetIterator Result = getMostSpecialized(
06675       Candidates.begin(), Candidates.end(), FailedCandidates,
06676       FD->getLocation(),
06677       PDiag(diag::err_function_template_spec_no_match) << FD->getDeclName(),
06678       PDiag(diag::err_function_template_spec_ambiguous)
06679           << FD->getDeclName() << (ExplicitTemplateArgs != nullptr),
06680       PDiag(diag::note_function_template_spec_matched));
06681 
06682   if (Result == Candidates.end())
06683     return true;
06684 
06685   // Ignore access information;  it doesn't figure into redeclaration checking.
06686   FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
06687 
06688   FunctionTemplateSpecializationInfo *SpecInfo
06689     = Specialization->getTemplateSpecializationInfo();
06690   assert(SpecInfo && "Function template specialization info missing?");
06691 
06692   // Note: do not overwrite location info if previous template
06693   // specialization kind was explicit.
06694   TemplateSpecializationKind TSK = SpecInfo->getTemplateSpecializationKind();
06695   if (TSK == TSK_Undeclared || TSK == TSK_ImplicitInstantiation) {
06696     Specialization->setLocation(FD->getLocation());
06697     // C++11 [dcl.constexpr]p1: An explicit specialization of a constexpr
06698     // function can differ from the template declaration with respect to
06699     // the constexpr specifier.
06700     Specialization->setConstexpr(FD->isConstexpr());
06701   }
06702 
06703   // FIXME: Check if the prior specialization has a point of instantiation.
06704   // If so, we have run afoul of .
06705 
06706   // If this is a friend declaration, then we're not really declaring
06707   // an explicit specialization.
06708   bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
06709 
06710   // Check the scope of this explicit specialization.
06711   if (!isFriend &&
06712       CheckTemplateSpecializationScope(*this,
06713                                        Specialization->getPrimaryTemplate(),
06714                                        Specialization, FD->getLocation(),
06715                                        false))
06716     return true;
06717 
06718   // C++ [temp.expl.spec]p6:
06719   //   If a template, a member template or the member of a class template is
06720   //   explicitly specialized then that specialization shall be declared
06721   //   before the first use of that specialization that would cause an implicit
06722   //   instantiation to take place, in every translation unit in which such a
06723   //   use occurs; no diagnostic is required.
06724   bool HasNoEffect = false;
06725   if (!isFriend &&
06726       CheckSpecializationInstantiationRedecl(FD->getLocation(),
06727                                              TSK_ExplicitSpecialization,
06728                                              Specialization,
06729                                    SpecInfo->getTemplateSpecializationKind(),
06730                                          SpecInfo->getPointOfInstantiation(),
06731                                              HasNoEffect))
06732     return true;
06733   
06734   // Mark the prior declaration as an explicit specialization, so that later
06735   // clients know that this is an explicit specialization.
06736   if (!isFriend) {
06737     SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
06738     MarkUnusedFileScopedDecl(Specialization);
06739   }
06740 
06741   // Turn the given function declaration into a function template
06742   // specialization, with the template arguments from the previous
06743   // specialization.
06744   // Take copies of (semantic and syntactic) template argument lists.
06745   const TemplateArgumentList* TemplArgs = new (Context)
06746     TemplateArgumentList(Specialization->getTemplateSpecializationArgs());
06747   FD->setFunctionTemplateSpecialization(Specialization->getPrimaryTemplate(),
06748                                         TemplArgs, /*InsertPos=*/nullptr,
06749                                     SpecInfo->getTemplateSpecializationKind(),
06750                                         ExplicitTemplateArgs);
06751 
06752   // The "previous declaration" for this function template specialization is
06753   // the prior function template specialization.
06754   Previous.clear();
06755   Previous.addDecl(Specialization);
06756   return false;
06757 }
06758 
06759 /// \brief Perform semantic analysis for the given non-template member
06760 /// specialization.
06761 ///
06762 /// This routine performs all of the semantic analysis required for an
06763 /// explicit member function specialization. On successful completion,
06764 /// the function declaration \p FD will become a member function
06765 /// specialization.
06766 ///
06767 /// \param Member the member declaration, which will be updated to become a
06768 /// specialization.
06769 ///
06770 /// \param Previous the set of declarations, one of which may be specialized
06771 /// by this function specialization;  the set will be modified to contain the
06772 /// redeclared member.
06773 bool
06774 Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
06775   assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
06776 
06777   // Try to find the member we are instantiating.
06778   NamedDecl *Instantiation = nullptr;
06779   NamedDecl *InstantiatedFrom = nullptr;
06780   MemberSpecializationInfo *MSInfo = nullptr;
06781 
06782   if (Previous.empty()) {
06783     // Nowhere to look anyway.
06784   } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
06785     for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
06786            I != E; ++I) {
06787       NamedDecl *D = (*I)->getUnderlyingDecl();
06788       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
06789         QualType Adjusted = Function->getType();
06790         if (!hasExplicitCallingConv(Adjusted))
06791           Adjusted = adjustCCAndNoReturn(Adjusted, Method->getType());
06792         if (Context.hasSameType(Adjusted, Method->getType())) {
06793           Instantiation = Method;
06794           InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
06795           MSInfo = Method->getMemberSpecializationInfo();
06796           break;
06797         }
06798       }
06799     }
06800   } else if (isa<VarDecl>(Member)) {
06801     VarDecl *PrevVar;
06802     if (Previous.isSingleResult() &&
06803         (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
06804       if (PrevVar->isStaticDataMember()) {
06805         Instantiation = PrevVar;
06806         InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
06807         MSInfo = PrevVar->getMemberSpecializationInfo();
06808       }
06809   } else if (isa<RecordDecl>(Member)) {
06810     CXXRecordDecl *PrevRecord;
06811     if (Previous.isSingleResult() &&
06812         (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
06813       Instantiation = PrevRecord;
06814       InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
06815       MSInfo = PrevRecord->getMemberSpecializationInfo();
06816     }
06817   } else if (isa<EnumDecl>(Member)) {
06818     EnumDecl *PrevEnum;
06819     if (Previous.isSingleResult() &&
06820         (PrevEnum = dyn_cast<EnumDecl>(Previous.getFoundDecl()))) {
06821       Instantiation = PrevEnum;
06822       InstantiatedFrom = PrevEnum->getInstantiatedFromMemberEnum();
06823       MSInfo = PrevEnum->getMemberSpecializationInfo();
06824     }
06825   }
06826 
06827   if (!Instantiation) {
06828     // There is no previous declaration that matches. Since member
06829     // specializations are always out-of-line, the caller will complain about
06830     // this mismatch later.
06831     return false;
06832   }
06833 
06834   // If this is a friend, just bail out here before we start turning
06835   // things into explicit specializations.
06836   if (Member->getFriendObjectKind() != Decl::FOK_None) {
06837     // Preserve instantiation information.
06838     if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) {
06839       cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction(
06840                                       cast<CXXMethodDecl>(InstantiatedFrom),
06841         cast<CXXMethodDecl>(Instantiation)->getTemplateSpecializationKind());
06842     } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) {
06843       cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
06844                                       cast<CXXRecordDecl>(InstantiatedFrom),
06845         cast<CXXRecordDecl>(Instantiation)->getTemplateSpecializationKind());
06846     }
06847 
06848     Previous.clear();
06849     Previous.addDecl(Instantiation);
06850     return false;
06851   }
06852 
06853   // Make sure that this is a specialization of a member.
06854   if (!InstantiatedFrom) {
06855     Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
06856       << Member;
06857     Diag(Instantiation->getLocation(), diag::note_specialized_decl);
06858     return true;
06859   }
06860 
06861   // C++ [temp.expl.spec]p6:
06862   //   If a template, a member template or the member of a class template is
06863   //   explicitly specialized then that specialization shall be declared
06864   //   before the first use of that specialization that would cause an implicit
06865   //   instantiation to take place, in every translation unit in which such a
06866   //   use occurs; no diagnostic is required.
06867   assert(MSInfo && "Member specialization info missing?");
06868 
06869   bool HasNoEffect = false;
06870   if (CheckSpecializationInstantiationRedecl(Member->getLocation(),
06871                                              TSK_ExplicitSpecialization,
06872                                              Instantiation,
06873                                      MSInfo->getTemplateSpecializationKind(),
06874                                            MSInfo->getPointOfInstantiation(),
06875                                              HasNoEffect))
06876     return true;
06877 
06878   // Check the scope of this explicit specialization.
06879   if (CheckTemplateSpecializationScope(*this,
06880                                        InstantiatedFrom,
06881                                        Instantiation, Member->getLocation(),
06882                                        false))
06883     return true;
06884 
06885   // Note that this is an explicit instantiation of a member.
06886   // the original declaration to note that it is an explicit specialization
06887   // (if it was previously an implicit instantiation). This latter step
06888   // makes bookkeeping easier.
06889   if (isa<FunctionDecl>(Member)) {
06890     FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
06891     if (InstantiationFunction->getTemplateSpecializationKind() ==
06892           TSK_ImplicitInstantiation) {
06893       InstantiationFunction->setTemplateSpecializationKind(
06894                                                   TSK_ExplicitSpecialization);
06895       InstantiationFunction->setLocation(Member->getLocation());
06896     }
06897 
06898     cast<FunctionDecl>(Member)->setInstantiationOfMemberFunction(
06899                                         cast<CXXMethodDecl>(InstantiatedFrom),
06900                                                   TSK_ExplicitSpecialization);
06901     MarkUnusedFileScopedDecl(InstantiationFunction);
06902   } else if (isa<VarDecl>(Member)) {
06903     VarDecl *InstantiationVar = cast<VarDecl>(Instantiation);
06904     if (InstantiationVar->getTemplateSpecializationKind() ==
06905           TSK_ImplicitInstantiation) {
06906       InstantiationVar->setTemplateSpecializationKind(
06907                                                   TSK_ExplicitSpecialization);
06908       InstantiationVar->setLocation(Member->getLocation());
06909     }
06910 
06911     cast<VarDecl>(Member)->setInstantiationOfStaticDataMember(
06912         cast<VarDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
06913     MarkUnusedFileScopedDecl(InstantiationVar);
06914   } else if (isa<CXXRecordDecl>(Member)) {
06915     CXXRecordDecl *InstantiationClass = cast<CXXRecordDecl>(Instantiation);
06916     if (InstantiationClass->getTemplateSpecializationKind() ==
06917           TSK_ImplicitInstantiation) {
06918       InstantiationClass->setTemplateSpecializationKind(
06919                                                    TSK_ExplicitSpecialization);
06920       InstantiationClass->setLocation(Member->getLocation());
06921     }
06922 
06923     cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
06924                                         cast<CXXRecordDecl>(InstantiatedFrom),
06925                                                    TSK_ExplicitSpecialization);
06926   } else {
06927     assert(isa<EnumDecl>(Member) && "Only member enums remain");
06928     EnumDecl *InstantiationEnum = cast<EnumDecl>(Instantiation);
06929     if (InstantiationEnum->getTemplateSpecializationKind() ==
06930           TSK_ImplicitInstantiation) {
06931       InstantiationEnum->setTemplateSpecializationKind(
06932                                                    TSK_ExplicitSpecialization);
06933       InstantiationEnum->setLocation(Member->getLocation());
06934     }
06935 
06936     cast<EnumDecl>(Member)->setInstantiationOfMemberEnum(
06937         cast<EnumDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
06938   }
06939 
06940   // Save the caller the trouble of having to figure out which declaration
06941   // this specialization matches.
06942   Previous.clear();
06943   Previous.addDecl(Instantiation);
06944   return false;
06945 }
06946 
06947 /// \brief Check the scope of an explicit instantiation.
06948 ///
06949 /// \returns true if a serious error occurs, false otherwise.
06950 static bool CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
06951                                             SourceLocation InstLoc,
06952                                             bool WasQualifiedName) {
06953   DeclContext *OrigContext= D->getDeclContext()->getEnclosingNamespaceContext();
06954   DeclContext *CurContext = S.CurContext->getRedeclContext();
06955 
06956   if (CurContext->isRecord()) {
06957     S.Diag(InstLoc, diag::err_explicit_instantiation_in_class)
06958       << D;
06959     return true;
06960   }
06961 
06962   // C++11 [temp.explicit]p3:
06963   //   An explicit instantiation shall appear in an enclosing namespace of its
06964   //   template. If the name declared in the explicit instantiation is an
06965   //   unqualified name, the explicit instantiation shall appear in the
06966   //   namespace where its template is declared or, if that namespace is inline
06967   //   (7.3.1), any namespace from its enclosing namespace set.
06968   //
06969   // This is DR275, which we do not retroactively apply to C++98/03.
06970   if (WasQualifiedName) {
06971     if (CurContext->Encloses(OrigContext))
06972       return false;
06973   } else {
06974     if (CurContext->InEnclosingNamespaceSetOf(OrigContext))
06975       return false;
06976   }
06977 
06978   if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(OrigContext)) {
06979     if (WasQualifiedName)
06980       S.Diag(InstLoc,
06981              S.getLangOpts().CPlusPlus11?
06982                diag::err_explicit_instantiation_out_of_scope :
06983                diag::warn_explicit_instantiation_out_of_scope_0x)
06984         << D << NS;
06985     else
06986       S.Diag(InstLoc,
06987              S.getLangOpts().CPlusPlus11?
06988                diag::err_explicit_instantiation_unqualified_wrong_namespace :
06989                diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
06990         << D << NS;
06991   } else
06992     S.Diag(InstLoc,
06993            S.getLangOpts().CPlusPlus11?
06994              diag::err_explicit_instantiation_must_be_global :
06995              diag::warn_explicit_instantiation_must_be_global_0x)
06996       << D;
06997   S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
06998   return false;
06999 }
07000 
07001 /// \brief Determine whether the given scope specifier has a template-id in it.
07002 static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
07003   if (!SS.isSet())
07004     return false;
07005 
07006   // C++11 [temp.explicit]p3:
07007   //   If the explicit instantiation is for a member function, a member class
07008   //   or a static data member of a class template specialization, the name of
07009   //   the class template specialization in the qualified-id for the member
07010   //   name shall be a simple-template-id.
07011   //
07012   // C++98 has the same restriction, just worded differently.
07013   for (NestedNameSpecifier *NNS = SS.getScopeRep(); NNS;
07014        NNS = NNS->getPrefix())
07015     if (const Type *T = NNS->getAsType())
07016       if (isa<TemplateSpecializationType>(T))
07017         return true;
07018 
07019   return false;
07020 }
07021 
07022 // Explicit instantiation of a class template specialization
07023 DeclResult
07024 Sema::ActOnExplicitInstantiation(Scope *S,
07025                                  SourceLocation ExternLoc,
07026                                  SourceLocation TemplateLoc,
07027                                  unsigned TagSpec,
07028                                  SourceLocation KWLoc,
07029                                  const CXXScopeSpec &SS,
07030                                  TemplateTy TemplateD,
07031                                  SourceLocation TemplateNameLoc,
07032                                  SourceLocation LAngleLoc,
07033                                  ASTTemplateArgsPtr TemplateArgsIn,
07034                                  SourceLocation RAngleLoc,
07035                                  AttributeList *Attr) {
07036   // Find the class template we're specializing
07037   TemplateName Name = TemplateD.get();
07038   TemplateDecl *TD = Name.getAsTemplateDecl();
07039   // Check that the specialization uses the same tag kind as the
07040   // original template.
07041   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
07042   assert(Kind != TTK_Enum &&
07043          "Invalid enum tag in class template explicit instantiation!");
07044 
07045   if (isa<TypeAliasTemplateDecl>(TD)) {
07046       Diag(KWLoc, diag::err_tag_reference_non_tag) << Kind;
07047       Diag(TD->getTemplatedDecl()->getLocation(),
07048            diag::note_previous_use);
07049     return true;
07050   }
07051 
07052   ClassTemplateDecl *ClassTemplate = cast<ClassTemplateDecl>(TD);
07053 
07054   if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
07055                                     Kind, /*isDefinition*/false, KWLoc,
07056                                     *ClassTemplate->getIdentifier())) {
07057     Diag(KWLoc, diag::err_use_with_wrong_tag)
07058       << ClassTemplate
07059       << FixItHint::CreateReplacement(KWLoc,
07060                             ClassTemplate->getTemplatedDecl()->getKindName());
07061     Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
07062          diag::note_previous_use);
07063     Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
07064   }
07065 
07066   // C++0x [temp.explicit]p2:
07067   //   There are two forms of explicit instantiation: an explicit instantiation
07068   //   definition and an explicit instantiation declaration. An explicit
07069   //   instantiation declaration begins with the extern keyword. [...]
07070   TemplateSpecializationKind TSK
07071     = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
07072                            : TSK_ExplicitInstantiationDeclaration;
07073 
07074   // Translate the parser's template argument list in our AST format.
07075   TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
07076   translateTemplateArguments(TemplateArgsIn, TemplateArgs);
07077 
07078   // Check that the template argument list is well-formed for this
07079   // template.
07080   SmallVector<TemplateArgument, 4> Converted;
07081   if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
07082                                 TemplateArgs, false, Converted))
07083     return true;
07084 
07085   // Find the class template specialization declaration that
07086   // corresponds to these arguments.
07087   void *InsertPos = nullptr;
07088   ClassTemplateSpecializationDecl *PrevDecl
07089     = ClassTemplate->findSpecialization(Converted, InsertPos);
07090 
07091   TemplateSpecializationKind PrevDecl_TSK
07092     = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared;
07093 
07094   // C++0x [temp.explicit]p2:
07095   //   [...] An explicit instantiation shall appear in an enclosing
07096   //   namespace of its template. [...]
07097   //
07098   // This is C++ DR 275.
07099   if (CheckExplicitInstantiationScope(*this, ClassTemplate, TemplateNameLoc,
07100                                       SS.isSet()))
07101     return true;
07102 
07103   ClassTemplateSpecializationDecl *Specialization = nullptr;
07104 
07105   bool HasNoEffect = false;
07106   if (PrevDecl) {
07107     if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
07108                                                PrevDecl, PrevDecl_TSK,
07109                                             PrevDecl->getPointOfInstantiation(),
07110                                                HasNoEffect))
07111       return PrevDecl;
07112 
07113     // Even though HasNoEffect == true means that this explicit instantiation
07114     // has no effect on semantics, we go on to put its syntax in the AST.
07115 
07116     if (PrevDecl_TSK == TSK_ImplicitInstantiation ||
07117         PrevDecl_TSK == TSK_Undeclared) {
07118       // Since the only prior class template specialization with these
07119       // arguments was referenced but not declared, reuse that
07120       // declaration node as our own, updating the source location
07121       // for the template name to reflect our new declaration.
07122       // (Other source locations will be updated later.)
07123       Specialization = PrevDecl;
07124       Specialization->setLocation(TemplateNameLoc);
07125       PrevDecl = nullptr;
07126     }
07127   }
07128 
07129   if (!Specialization) {
07130     // Create a new class template specialization declaration node for
07131     // this explicit specialization.
07132     Specialization
07133       = ClassTemplateSpecializationDecl::Create(Context, Kind,
07134                                              ClassTemplate->getDeclContext(),
07135                                                 KWLoc, TemplateNameLoc,
07136                                                 ClassTemplate,
07137                                                 Converted.data(),
07138                                                 Converted.size(),
07139                                                 PrevDecl);
07140     SetNestedNameSpecifier(Specialization, SS);
07141 
07142     if (!HasNoEffect && !PrevDecl) {
07143       // Insert the new specialization.
07144       ClassTemplate->AddSpecialization(Specialization, InsertPos);
07145     }
07146   }
07147 
07148   // Build the fully-sugared type for this explicit instantiation as
07149   // the user wrote in the explicit instantiation itself. This means
07150   // that we'll pretty-print the type retrieved from the
07151   // specialization's declaration the way that the user actually wrote
07152   // the explicit instantiation, rather than formatting the name based
07153   // on the "canonical" representation used to store the template
07154   // arguments in the specialization.
07155   TypeSourceInfo *WrittenTy
07156     = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
07157                                                 TemplateArgs,
07158                                   Context.getTypeDeclType(Specialization));
07159   Specialization->setTypeAsWritten(WrittenTy);
07160 
07161   // Set source locations for keywords.
07162   Specialization->setExternLoc(ExternLoc);
07163   Specialization->setTemplateKeywordLoc(TemplateLoc);
07164   Specialization->setRBraceLoc(SourceLocation());
07165 
07166   if (Attr)
07167     ProcessDeclAttributeList(S, Specialization, Attr);
07168 
07169   // Add the explicit instantiation into its lexical context. However,
07170   // since explicit instantiations are never found by name lookup, we
07171   // just put it into the declaration context directly.
07172   Specialization->setLexicalDeclContext(CurContext);
07173   CurContext->addDecl(Specialization);
07174 
07175   // Syntax is now OK, so return if it has no other effect on semantics.
07176   if (HasNoEffect) {
07177     // Set the template specialization kind.
07178     Specialization->setTemplateSpecializationKind(TSK);
07179     return Specialization;
07180   }
07181 
07182   // C++ [temp.explicit]p3:
07183   //   A definition of a class template or class member template
07184   //   shall be in scope at the point of the explicit instantiation of
07185   //   the class template or class member template.
07186   //
07187   // This check comes when we actually try to perform the
07188   // instantiation.
07189   ClassTemplateSpecializationDecl *Def
07190     = cast_or_null<ClassTemplateSpecializationDecl>(
07191                                               Specialization->getDefinition());
07192   if (!Def)
07193     InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK);
07194   else if (TSK == TSK_ExplicitInstantiationDefinition) {
07195     MarkVTableUsed(TemplateNameLoc, Specialization, true);
07196     Specialization->setPointOfInstantiation(Def->getPointOfInstantiation());
07197   }
07198 
07199   // Instantiate the members of this class template specialization.
07200   Def = cast_or_null<ClassTemplateSpecializationDecl>(
07201                                        Specialization->getDefinition());
07202   if (Def) {
07203     TemplateSpecializationKind Old_TSK = Def->getTemplateSpecializationKind();
07204 
07205     // Fix a TSK_ExplicitInstantiationDeclaration followed by a
07206     // TSK_ExplicitInstantiationDefinition
07207     if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
07208         TSK == TSK_ExplicitInstantiationDefinition)
07209       // FIXME: Need to notify the ASTMutationListener that we did this.
07210       Def->setTemplateSpecializationKind(TSK);
07211 
07212     InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
07213   }
07214 
07215   // Set the template specialization kind.
07216   Specialization->setTemplateSpecializationKind(TSK);
07217   return Specialization;
07218 }
07219 
07220 // Explicit instantiation of a member class of a class template.
07221 DeclResult
07222 Sema::ActOnExplicitInstantiation(Scope *S,
07223                                  SourceLocation ExternLoc,
07224                                  SourceLocation TemplateLoc,
07225                                  unsigned TagSpec,
07226                                  SourceLocation KWLoc,
07227                                  CXXScopeSpec &SS,
07228                                  IdentifierInfo *Name,
07229                                  SourceLocation NameLoc,
07230                                  AttributeList *Attr) {
07231 
07232   bool Owned = false;
07233   bool IsDependent = false;
07234   Decl *TagD = ActOnTag(S, TagSpec, Sema::TUK_Reference,
07235                         KWLoc, SS, Name, NameLoc, Attr, AS_none,
07236                         /*ModulePrivateLoc=*/SourceLocation(),
07237                         MultiTemplateParamsArg(), Owned, IsDependent,
07238                         SourceLocation(), false, TypeResult(),
07239                         /*IsTypeSpecifier*/false);
07240   assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
07241 
07242   if (!TagD)
07243     return true;
07244 
07245   TagDecl *Tag = cast<TagDecl>(TagD);
07246   assert(!Tag->isEnum() && "shouldn't see enumerations here");
07247 
07248   if (Tag->isInvalidDecl())
07249     return true;
07250 
07251   CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
07252   CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
07253   if (!Pattern) {
07254     Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
07255       << Context.getTypeDeclType(Record);
07256     Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
07257     return true;
07258   }
07259 
07260   // C++0x [temp.explicit]p2:
07261   //   If the explicit instantiation is for a class or member class, the
07262   //   elaborated-type-specifier in the declaration shall include a
07263   //   simple-template-id.
07264   //
07265   // C++98 has the same restriction, just worded differently.
07266   if (!ScopeSpecifierHasTemplateId(SS))
07267     Diag(TemplateLoc, diag::ext_explicit_instantiation_without_qualified_id)
07268       << Record << SS.getRange();
07269 
07270   // C++0x [temp.explicit]p2:
07271   //   There are two forms of explicit instantiation: an explicit instantiation
07272   //   definition and an explicit instantiation declaration. An explicit
07273   //   instantiation declaration begins with the extern keyword. [...]
07274   TemplateSpecializationKind TSK
07275     = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
07276                            : TSK_ExplicitInstantiationDeclaration;
07277 
07278   // C++0x [temp.explicit]p2:
07279   //   [...] An explicit instantiation shall appear in an enclosing
07280   //   namespace of its template. [...]
07281   //
07282   // This is C++ DR 275.
07283   CheckExplicitInstantiationScope(*this, Record, NameLoc, true);
07284 
07285   // Verify that it is okay to explicitly instantiate here.
07286   CXXRecordDecl *PrevDecl
07287     = cast_or_null<CXXRecordDecl>(Record->getPreviousDecl());
07288   if (!PrevDecl && Record->getDefinition())
07289     PrevDecl = Record;
07290   if (PrevDecl) {
07291     MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
07292     bool HasNoEffect = false;
07293     assert(MSInfo && "No member specialization information?");
07294     if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
07295                                                PrevDecl,
07296                                         MSInfo->getTemplateSpecializationKind(),
07297                                              MSInfo->getPointOfInstantiation(),
07298                                                HasNoEffect))
07299       return true;
07300     if (HasNoEffect)
07301       return TagD;
07302   }
07303 
07304   CXXRecordDecl *RecordDef
07305     = cast_or_null<CXXRecordDecl>(Record->getDefinition());
07306   if (!RecordDef) {
07307     // C++ [temp.explicit]p3:
07308     //   A definition of a member class of a class template shall be in scope
07309     //   at the point of an explicit instantiation of the member class.
07310     CXXRecordDecl *Def
07311       = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
07312     if (!Def) {
07313       Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
07314         << 0 << Record->getDeclName() << Record->getDeclContext();
07315       Diag(Pattern->getLocation(), diag::note_forward_declaration)
07316         << Pattern;
07317       return true;
07318     } else {
07319       if (InstantiateClass(NameLoc, Record, Def,
07320                            getTemplateInstantiationArgs(Record),
07321                            TSK))
07322         return true;
07323 
07324       RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition());
07325       if (!RecordDef)
07326         return true;
07327     }
07328   }
07329 
07330   // Instantiate all of the members of the class.
07331   InstantiateClassMembers(NameLoc, RecordDef,
07332                           getTemplateInstantiationArgs(Record), TSK);
07333 
07334   if (TSK == TSK_ExplicitInstantiationDefinition)
07335     MarkVTableUsed(NameLoc, RecordDef, true);
07336 
07337   // FIXME: We don't have any representation for explicit instantiations of
07338   // member classes. Such a representation is not needed for compilation, but it
07339   // should be available for clients that want to see all of the declarations in
07340   // the source code.
07341   return TagD;
07342 }
07343 
07344 DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
07345                                             SourceLocation ExternLoc,
07346                                             SourceLocation TemplateLoc,
07347                                             Declarator &D) {
07348   // Explicit instantiations always require a name.
07349   // TODO: check if/when DNInfo should replace Name.
07350   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
07351   DeclarationName Name = NameInfo.getName();
07352   if (!Name) {
07353     if (!D.isInvalidType())
07354       Diag(D.getDeclSpec().getLocStart(),
07355            diag::err_explicit_instantiation_requires_name)
07356         << D.getDeclSpec().getSourceRange()
07357         << D.getSourceRange();
07358 
07359     return true;
07360   }
07361 
07362   // The scope passed in may not be a decl scope.  Zip up the scope tree until
07363   // we find one that is.
07364   while ((S->getFlags() & Scope::DeclScope) == 0 ||
07365          (S->getFlags() & Scope::TemplateParamScope) != 0)
07366     S = S->getParent();
07367 
07368   // Determine the type of the declaration.
07369   TypeSourceInfo *T = GetTypeForDeclarator(D, S);
07370   QualType R = T->getType();
07371   if (R.isNull())
07372     return true;
07373 
07374   // C++ [dcl.stc]p1:
07375   //   A storage-class-specifier shall not be specified in [...] an explicit 
07376   //   instantiation (14.7.2) directive.
07377   if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
07378     Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
07379       << Name;
07380     return true;
07381   } else if (D.getDeclSpec().getStorageClassSpec() 
07382                                                 != DeclSpec::SCS_unspecified) {
07383     // Complain about then remove the storage class specifier.
07384     Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_storage_class)
07385       << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
07386     
07387     D.getMutableDeclSpec().ClearStorageClassSpecs();
07388   }
07389 
07390   // C++0x [temp.explicit]p1:
07391   //   [...] An explicit instantiation of a function template shall not use the
07392   //   inline or constexpr specifiers.
07393   // Presumably, this also applies to member functions of class templates as
07394   // well.
07395   if (D.getDeclSpec().isInlineSpecified())
07396     Diag(D.getDeclSpec().getInlineSpecLoc(),
07397          getLangOpts().CPlusPlus11 ?
07398            diag::err_explicit_instantiation_inline :
07399            diag::warn_explicit_instantiation_inline_0x)
07400       << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
07401   if (D.getDeclSpec().isConstexprSpecified() && R->isFunctionType())
07402     // FIXME: Add a fix-it to remove the 'constexpr' and add a 'const' if one is
07403     // not already specified.
07404     Diag(D.getDeclSpec().getConstexprSpecLoc(),
07405          diag::err_explicit_instantiation_constexpr);
07406 
07407   // C++0x [temp.explicit]p2:
07408   //   There are two forms of explicit instantiation: an explicit instantiation
07409   //   definition and an explicit instantiation declaration. An explicit
07410   //   instantiation declaration begins with the extern keyword. [...]
07411   TemplateSpecializationKind TSK
07412     = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
07413                            : TSK_ExplicitInstantiationDeclaration;
07414 
07415   LookupResult Previous(*this, NameInfo, LookupOrdinaryName);
07416   LookupParsedName(Previous, S, &D.getCXXScopeSpec());
07417 
07418   if (!R->isFunctionType()) {
07419     // C++ [temp.explicit]p1:
07420     //   A [...] static data member of a class template can be explicitly
07421     //   instantiated from the member definition associated with its class
07422     //   template.
07423     // C++1y [temp.explicit]p1:
07424     //   A [...] variable [...] template specialization can be explicitly
07425     //   instantiated from its template.
07426     if (Previous.isAmbiguous())
07427       return true;
07428 
07429     VarDecl *Prev = Previous.getAsSingle<VarDecl>();
07430     VarTemplateDecl *PrevTemplate = Previous.getAsSingle<VarTemplateDecl>();
07431 
07432     if (!PrevTemplate) {
07433       if (!Prev || !Prev->isStaticDataMember()) {
07434         // We expect to see a data data member here.
07435         Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
07436             << Name;
07437         for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
07438              P != PEnd; ++P)
07439           Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
07440         return true;
07441       }
07442 
07443       if (!Prev->getInstantiatedFromStaticDataMember()) {
07444         // FIXME: Check for explicit specialization?
07445         Diag(D.getIdentifierLoc(),
07446              diag::err_explicit_instantiation_data_member_not_instantiated)
07447             << Prev;
07448         Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
07449         // FIXME: Can we provide a note showing where this was declared?
07450         return true;
07451       }
07452     } else {
07453       // Explicitly instantiate a variable template.
07454 
07455       // C++1y [dcl.spec.auto]p6:
07456       //   ... A program that uses auto or decltype(auto) in a context not
07457       //   explicitly allowed in this section is ill-formed.
07458       //
07459       // This includes auto-typed variable template instantiations.
07460       if (R->isUndeducedType()) {
07461         Diag(T->getTypeLoc().getLocStart(),
07462              diag::err_auto_not_allowed_var_inst);
07463         return true;
07464       }
07465 
07466       if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
07467         // C++1y [temp.explicit]p3:
07468         //   If the explicit instantiation is for a variable, the unqualified-id
07469         //   in the declaration shall be a template-id.
07470         Diag(D.getIdentifierLoc(),
07471              diag::err_explicit_instantiation_without_template_id)
07472           << PrevTemplate;
07473         Diag(PrevTemplate->getLocation(),
07474              diag::note_explicit_instantiation_here);
07475         return true;
07476       }
07477 
07478       // Translate the parser's template argument list into our AST format.
07479       TemplateArgumentListInfo TemplateArgs =
07480           makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
07481 
07482       DeclResult Res = CheckVarTemplateId(PrevTemplate, TemplateLoc,
07483                                           D.getIdentifierLoc(), TemplateArgs);
07484       if (Res.isInvalid())
07485         return true;
07486 
07487       // Ignore access control bits, we don't need them for redeclaration
07488       // checking.
07489       Prev = cast<VarDecl>(Res.get());
07490     }
07491 
07492     // C++0x [temp.explicit]p2:
07493     //   If the explicit instantiation is for a member function, a member class
07494     //   or a static data member of a class template specialization, the name of
07495     //   the class template specialization in the qualified-id for the member
07496     //   name shall be a simple-template-id.
07497     //
07498     // C++98 has the same restriction, just worded differently.
07499     //
07500     // This does not apply to variable template specializations, where the
07501     // template-id is in the unqualified-id instead.
07502     if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()) && !PrevTemplate)
07503       Diag(D.getIdentifierLoc(),
07504            diag::ext_explicit_instantiation_without_qualified_id)
07505         << Prev << D.getCXXScopeSpec().getRange();
07506 
07507     // Check the scope of this explicit instantiation.
07508     CheckExplicitInstantiationScope(*this, Prev, D.getIdentifierLoc(), true);
07509 
07510     // Verify that it is okay to explicitly instantiate here.
07511     TemplateSpecializationKind PrevTSK = Prev->getTemplateSpecializationKind();
07512     SourceLocation POI = Prev->getPointOfInstantiation();
07513     bool HasNoEffect = false;
07514     if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
07515                                                PrevTSK, POI, HasNoEffect))
07516       return true;
07517 
07518     if (!HasNoEffect) {
07519       // Instantiate static data member or variable template.
07520 
07521       Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
07522       if (PrevTemplate) {
07523         // Merge attributes.
07524         if (AttributeList *Attr = D.getDeclSpec().getAttributes().getList())
07525           ProcessDeclAttributeList(S, Prev, Attr);
07526       }
07527       if (TSK == TSK_ExplicitInstantiationDefinition)
07528         InstantiateVariableDefinition(D.getIdentifierLoc(), Prev);
07529     }
07530 
07531     // Check the new variable specialization against the parsed input.
07532     if (PrevTemplate && Prev && !Context.hasSameType(Prev->getType(), R)) {
07533       Diag(T->getTypeLoc().getLocStart(),
07534            diag::err_invalid_var_template_spec_type)
07535           << 0 << PrevTemplate << R << Prev->getType();
07536       Diag(PrevTemplate->getLocation(), diag::note_template_declared_here)
07537           << 2 << PrevTemplate->getDeclName();
07538       return true;
07539     }
07540 
07541     // FIXME: Create an ExplicitInstantiation node?
07542     return (Decl*) nullptr;
07543   }
07544 
07545   // If the declarator is a template-id, translate the parser's template
07546   // argument list into our AST format.
07547   bool HasExplicitTemplateArgs = false;
07548   TemplateArgumentListInfo TemplateArgs;
07549   if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
07550     TemplateArgs = makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
07551     HasExplicitTemplateArgs = true;
07552   }
07553 
07554   // C++ [temp.explicit]p1:
07555   //   A [...] function [...] can be explicitly instantiated from its template.
07556   //   A member function [...] of a class template can be explicitly
07557   //  instantiated from the member definition associated with its class
07558   //  template.
07559   UnresolvedSet<8> Matches;
07560   TemplateSpecCandidateSet FailedCandidates(D.getIdentifierLoc());
07561   for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
07562        P != PEnd; ++P) {
07563     NamedDecl *Prev = *P;
07564     if (!HasExplicitTemplateArgs) {
07565       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
07566         QualType Adjusted = adjustCCAndNoReturn(R, Method->getType());
07567         if (Context.hasSameUnqualifiedType(Method->getType(), Adjusted)) {
07568           Matches.clear();
07569 
07570           Matches.addDecl(Method, P.getAccess());
07571           if (Method->getTemplateSpecializationKind() == TSK_Undeclared)
07572             break;
07573         }
07574       }
07575     }
07576 
07577     FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
07578     if (!FunTmpl)
07579       continue;
07580 
07581     TemplateDeductionInfo Info(FailedCandidates.getLocation());
07582     FunctionDecl *Specialization = nullptr;
07583     if (TemplateDeductionResult TDK
07584           = DeduceTemplateArguments(FunTmpl,
07585                                (HasExplicitTemplateArgs ? &TemplateArgs
07586                                                         : nullptr),
07587                                     R, Specialization, Info)) {
07588       // Keep track of almost-matches.
07589       FailedCandidates.addCandidate()
07590           .set(FunTmpl->getTemplatedDecl(),
07591                MakeDeductionFailureInfo(Context, TDK, Info));
07592       (void)TDK;
07593       continue;
07594     }
07595 
07596     Matches.addDecl(Specialization, P.getAccess());
07597   }
07598 
07599   // Find the most specialized function template specialization.
07600   UnresolvedSetIterator Result = getMostSpecialized(
07601       Matches.begin(), Matches.end(), FailedCandidates,
07602       D.getIdentifierLoc(),
07603       PDiag(diag::err_explicit_instantiation_not_known) << Name,
07604       PDiag(diag::err_explicit_instantiation_ambiguous) << Name,
07605       PDiag(diag::note_explicit_instantiation_candidate));
07606 
07607   if (Result == Matches.end())
07608     return true;
07609 
07610   // Ignore access control bits, we don't need them for redeclaration checking.
07611   FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
07612 
07613   // C++11 [except.spec]p4
07614   // In an explicit instantiation an exception-specification may be specified,
07615   // but is not required.
07616   // If an exception-specification is specified in an explicit instantiation
07617   // directive, it shall be compatible with the exception-specifications of
07618   // other declarations of that function.
07619   if (auto *FPT = R->getAs<FunctionProtoType>())
07620     if (FPT->hasExceptionSpec()) {
07621       unsigned DiagID =
07622           diag::err_mismatched_exception_spec_explicit_instantiation;
07623       if (getLangOpts().MicrosoftExt)
07624         DiagID = diag::ext_mismatched_exception_spec_explicit_instantiation;
07625       bool Result = CheckEquivalentExceptionSpec(
07626           PDiag(DiagID) << Specialization->getType(),
07627           PDiag(diag::note_explicit_instantiation_here),
07628           Specialization->getType()->getAs<FunctionProtoType>(),
07629           Specialization->getLocation(), FPT, D.getLocStart());
07630       // In Microsoft mode, mismatching exception specifications just cause a
07631       // warning.
07632       if (!getLangOpts().MicrosoftExt && Result)
07633         return true;
07634     }
07635 
07636   if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
07637     Diag(D.getIdentifierLoc(),
07638          diag::err_explicit_instantiation_member_function_not_instantiated)
07639       << Specialization
07640       << (Specialization->getTemplateSpecializationKind() ==
07641           TSK_ExplicitSpecialization);
07642     Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
07643     return true;
07644   }
07645 
07646   FunctionDecl *PrevDecl = Specialization->getPreviousDecl();
07647   if (!PrevDecl && Specialization->isThisDeclarationADefinition())
07648     PrevDecl = Specialization;
07649 
07650   if (PrevDecl) {
07651     bool HasNoEffect = false;
07652     if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
07653                                                PrevDecl,
07654                                      PrevDecl->getTemplateSpecializationKind(),
07655                                           PrevDecl->getPointOfInstantiation(),
07656                                                HasNoEffect))
07657       return true;
07658 
07659     // FIXME: We may still want to build some representation of this
07660     // explicit specialization.
07661     if (HasNoEffect)
07662       return (Decl*) nullptr;
07663   }
07664 
07665   Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
07666   AttributeList *Attr = D.getDeclSpec().getAttributes().getList();
07667   if (Attr)
07668     ProcessDeclAttributeList(S, Specialization, Attr);
07669 
07670   if (Specialization->isDefined()) {
07671     // Let the ASTConsumer know that this function has been explicitly
07672     // instantiated now, and its linkage might have changed.
07673     Consumer.HandleTopLevelDecl(DeclGroupRef(Specialization));
07674   } else if (TSK == TSK_ExplicitInstantiationDefinition)
07675     InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization);
07676 
07677   // C++0x [temp.explicit]p2:
07678   //   If the explicit instantiation is for a member function, a member class
07679   //   or a static data member of a class template specialization, the name of
07680   //   the class template specialization in the qualified-id for the member
07681   //   name shall be a simple-template-id.
07682   //
07683   // C++98 has the same restriction, just worded differently.
07684   FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
07685   if (D.getName().getKind() != UnqualifiedId::IK_TemplateId && !FunTmpl &&
07686       D.getCXXScopeSpec().isSet() &&
07687       !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
07688     Diag(D.getIdentifierLoc(),
07689          diag::ext_explicit_instantiation_without_qualified_id)
07690     << Specialization << D.getCXXScopeSpec().getRange();
07691 
07692   CheckExplicitInstantiationScope(*this,
07693                    FunTmpl? (NamedDecl *)FunTmpl
07694                           : Specialization->getInstantiatedFromMemberFunction(),
07695                                   D.getIdentifierLoc(),
07696                                   D.getCXXScopeSpec().isSet());
07697 
07698   // FIXME: Create some kind of ExplicitInstantiationDecl here.
07699   return (Decl*) nullptr;
07700 }
07701 
07702 TypeResult
07703 Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
07704                         const CXXScopeSpec &SS, IdentifierInfo *Name,
07705                         SourceLocation TagLoc, SourceLocation NameLoc) {
07706   // This has to hold, because SS is expected to be defined.
07707   assert(Name && "Expected a name in a dependent tag");
07708 
07709   NestedNameSpecifier *NNS = SS.getScopeRep();
07710   if (!NNS)
07711     return true;
07712 
07713   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
07714 
07715   if (TUK == TUK_Declaration || TUK == TUK_Definition) {
07716     Diag(NameLoc, diag::err_dependent_tag_decl)
07717       << (TUK == TUK_Definition) << Kind << SS.getRange();
07718     return true;
07719   }
07720 
07721   // Create the resulting type.
07722   ElaboratedTypeKeyword Kwd = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
07723   QualType Result = Context.getDependentNameType(Kwd, NNS, Name);
07724   
07725   // Create type-source location information for this type.
07726   TypeLocBuilder TLB;
07727   DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(Result);
07728   TL.setElaboratedKeywordLoc(TagLoc);
07729   TL.setQualifierLoc(SS.getWithLocInContext(Context));
07730   TL.setNameLoc(NameLoc);
07731   return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
07732 }
07733 
07734 TypeResult
07735 Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
07736                         const CXXScopeSpec &SS, const IdentifierInfo &II,
07737                         SourceLocation IdLoc) {
07738   if (SS.isInvalid())
07739     return true;
07740   
07741   if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
07742     Diag(TypenameLoc,
07743          getLangOpts().CPlusPlus11 ?
07744            diag::warn_cxx98_compat_typename_outside_of_template :
07745            diag::ext_typename_outside_of_template)
07746       << FixItHint::CreateRemoval(TypenameLoc);
07747 
07748   NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
07749   QualType T = CheckTypenameType(TypenameLoc.isValid()? ETK_Typename : ETK_None,
07750                                  TypenameLoc, QualifierLoc, II, IdLoc);
07751   if (T.isNull())
07752     return true;
07753 
07754   TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
07755   if (isa<DependentNameType>(T)) {
07756     DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
07757     TL.setElaboratedKeywordLoc(TypenameLoc);
07758     TL.setQualifierLoc(QualifierLoc);
07759     TL.setNameLoc(IdLoc);
07760   } else {
07761     ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
07762     TL.setElaboratedKeywordLoc(TypenameLoc);
07763     TL.setQualifierLoc(QualifierLoc);
07764     TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
07765   }
07766 
07767   return CreateParsedType(T, TSI);
07768 }
07769 
07770 TypeResult
07771 Sema::ActOnTypenameType(Scope *S,
07772                         SourceLocation TypenameLoc,
07773                         const CXXScopeSpec &SS,
07774                         SourceLocation TemplateKWLoc,
07775                         TemplateTy TemplateIn,
07776                         SourceLocation TemplateNameLoc,
07777                         SourceLocation LAngleLoc,
07778                         ASTTemplateArgsPtr TemplateArgsIn,
07779                         SourceLocation RAngleLoc) {
07780   if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
07781     Diag(TypenameLoc,
07782          getLangOpts().CPlusPlus11 ?
07783            diag::warn_cxx98_compat_typename_outside_of_template :
07784            diag::ext_typename_outside_of_template)
07785       << FixItHint::CreateRemoval(TypenameLoc);
07786   
07787   // Translate the parser's template argument list in our AST format.
07788   TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
07789   translateTemplateArguments(TemplateArgsIn, TemplateArgs);
07790   
07791   TemplateName Template = TemplateIn.get();
07792   if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
07793     // Construct a dependent template specialization type.
07794     assert(DTN && "dependent template has non-dependent name?");
07795     assert(DTN->getQualifier() == SS.getScopeRep());
07796     QualType T = Context.getDependentTemplateSpecializationType(ETK_Typename,
07797                                                           DTN->getQualifier(),
07798                                                           DTN->getIdentifier(),
07799                                                                 TemplateArgs);
07800     
07801     // Create source-location information for this type.
07802     TypeLocBuilder Builder;
07803     DependentTemplateSpecializationTypeLoc SpecTL 
07804     = Builder.push<DependentTemplateSpecializationTypeLoc>(T);
07805     SpecTL.setElaboratedKeywordLoc(TypenameLoc);
07806     SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
07807     SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
07808     SpecTL.setTemplateNameLoc(TemplateNameLoc);
07809     SpecTL.setLAngleLoc(LAngleLoc);
07810     SpecTL.setRAngleLoc(RAngleLoc);
07811     for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
07812       SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
07813     return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
07814   }
07815   
07816   QualType T = CheckTemplateIdType(Template, TemplateNameLoc, TemplateArgs);
07817   if (T.isNull())
07818     return true;
07819   
07820   // Provide source-location information for the template specialization type.
07821   TypeLocBuilder Builder;
07822   TemplateSpecializationTypeLoc SpecTL
07823     = Builder.push<TemplateSpecializationTypeLoc>(T);
07824   SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
07825   SpecTL.setTemplateNameLoc(TemplateNameLoc);
07826   SpecTL.setLAngleLoc(LAngleLoc);
07827   SpecTL.setRAngleLoc(RAngleLoc);
07828   for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
07829     SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
07830   
07831   T = Context.getElaboratedType(ETK_Typename, SS.getScopeRep(), T);
07832   ElaboratedTypeLoc TL = Builder.push<ElaboratedTypeLoc>(T);
07833   TL.setElaboratedKeywordLoc(TypenameLoc);
07834   TL.setQualifierLoc(SS.getWithLocInContext(Context));
07835   
07836   TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T);
07837   return CreateParsedType(T, TSI);
07838 }
07839 
07840 
07841 /// Determine whether this failed name lookup should be treated as being
07842 /// disabled by a usage of std::enable_if.
07843 static bool isEnableIf(NestedNameSpecifierLoc NNS, const IdentifierInfo &II,
07844                        SourceRange &CondRange) {
07845   // We must be looking for a ::type...
07846   if (!II.isStr("type"))
07847     return false;
07848 
07849   // ... within an explicitly-written template specialization...
07850   if (!NNS || !NNS.getNestedNameSpecifier()->getAsType())
07851     return false;
07852   TypeLoc EnableIfTy = NNS.getTypeLoc();
07853   TemplateSpecializationTypeLoc EnableIfTSTLoc =
07854       EnableIfTy.getAs<TemplateSpecializationTypeLoc>();
07855   if (!EnableIfTSTLoc || EnableIfTSTLoc.getNumArgs() == 0)
07856     return false;
07857   const TemplateSpecializationType *EnableIfTST =
07858     cast<TemplateSpecializationType>(EnableIfTSTLoc.getTypePtr());
07859 
07860   // ... which names a complete class template declaration...
07861   const TemplateDecl *EnableIfDecl =
07862     EnableIfTST->getTemplateName().getAsTemplateDecl();
07863   if (!EnableIfDecl || EnableIfTST->isIncompleteType())
07864     return false;
07865 
07866   // ... called "enable_if".
07867   const IdentifierInfo *EnableIfII =
07868     EnableIfDecl->getDeclName().getAsIdentifierInfo();
07869   if (!EnableIfII || !EnableIfII->isStr("enable_if"))
07870     return false;
07871 
07872   // Assume the first template argument is the condition.
07873   CondRange = EnableIfTSTLoc.getArgLoc(0).getSourceRange();
07874   return true;
07875 }
07876 
07877 /// \brief Build the type that describes a C++ typename specifier,
07878 /// e.g., "typename T::type".
07879 QualType
07880 Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword, 
07881                         SourceLocation KeywordLoc,
07882                         NestedNameSpecifierLoc QualifierLoc, 
07883                         const IdentifierInfo &II,
07884                         SourceLocation IILoc) {
07885   CXXScopeSpec SS;
07886   SS.Adopt(QualifierLoc);
07887 
07888   DeclContext *Ctx = computeDeclContext(SS);
07889   if (!Ctx) {
07890     // If the nested-name-specifier is dependent and couldn't be
07891     // resolved to a type, build a typename type.
07892     assert(QualifierLoc.getNestedNameSpecifier()->isDependent());
07893     return Context.getDependentNameType(Keyword, 
07894                                         QualifierLoc.getNestedNameSpecifier(), 
07895                                         &II);
07896   }
07897 
07898   // If the nested-name-specifier refers to the current instantiation,
07899   // the "typename" keyword itself is superfluous. In C++03, the
07900   // program is actually ill-formed. However, DR 382 (in C++0x CD1)
07901   // allows such extraneous "typename" keywords, and we retroactively
07902   // apply this DR to C++03 code with only a warning. In any case we continue.
07903 
07904   if (RequireCompleteDeclContext(SS, Ctx))
07905     return QualType();
07906 
07907   DeclarationName Name(&II);
07908   LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
07909   NestedNameSpecifier *NNS = SS.getScopeRep();
07910   if (NNS->getKind() == NestedNameSpecifier::Super)
07911     LookupInSuper(Result, NNS->getAsRecordDecl());
07912   else
07913     LookupQualifiedName(Result, Ctx);
07914   unsigned DiagID = 0;
07915   Decl *Referenced = nullptr;
07916   switch (Result.getResultKind()) {
07917   case LookupResult::NotFound: {
07918     // If we're looking up 'type' within a template named 'enable_if', produce
07919     // a more specific diagnostic.
07920     SourceRange CondRange;
07921     if (isEnableIf(QualifierLoc, II, CondRange)) {
07922       Diag(CondRange.getBegin(), diag::err_typename_nested_not_found_enable_if)
07923         << Ctx << CondRange;
07924       return QualType();
07925     }
07926 
07927     DiagID = diag::err_typename_nested_not_found;
07928     break;
07929   }
07930 
07931   case LookupResult::FoundUnresolvedValue: {
07932     // We found a using declaration that is a value. Most likely, the using
07933     // declaration itself is meant to have the 'typename' keyword.
07934     SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
07935                           IILoc);
07936     Diag(IILoc, diag::err_typename_refers_to_using_value_decl)
07937       << Name << Ctx << FullRange;
07938     if (UnresolvedUsingValueDecl *Using
07939           = dyn_cast<UnresolvedUsingValueDecl>(Result.getRepresentativeDecl())){
07940       SourceLocation Loc = Using->getQualifierLoc().getBeginLoc();
07941       Diag(Loc, diag::note_using_value_decl_missing_typename)
07942         << FixItHint::CreateInsertion(Loc, "typename ");
07943     }
07944   }
07945   // Fall through to create a dependent typename type, from which we can recover
07946   // better.
07947 
07948   case LookupResult::NotFoundInCurrentInstantiation:
07949     // Okay, it's a member of an unknown instantiation.
07950     return Context.getDependentNameType(Keyword, 
07951                                         QualifierLoc.getNestedNameSpecifier(), 
07952                                         &II);
07953 
07954   case LookupResult::Found:
07955     if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
07956       // We found a type. Build an ElaboratedType, since the
07957       // typename-specifier was just sugar.
07958       MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
07959       return Context.getElaboratedType(ETK_Typename, 
07960                                        QualifierLoc.getNestedNameSpecifier(),
07961                                        Context.getTypeDeclType(Type));
07962     }
07963 
07964     DiagID = diag::err_typename_nested_not_type;
07965     Referenced = Result.getFoundDecl();
07966     break;
07967 
07968   case LookupResult::FoundOverloaded:
07969     DiagID = diag::err_typename_nested_not_type;
07970     Referenced = *Result.begin();
07971     break;
07972 
07973   case LookupResult::Ambiguous:
07974     return QualType();
07975   }
07976 
07977   // If we get here, it's because name lookup did not find a
07978   // type. Emit an appropriate diagnostic and return an error.
07979   SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
07980                         IILoc);
07981   Diag(IILoc, DiagID) << FullRange << Name << Ctx;
07982   if (Referenced)
07983     Diag(Referenced->getLocation(), diag::note_typename_refers_here)
07984       << Name;
07985   return QualType();
07986 }
07987 
07988 namespace {
07989   // See Sema::RebuildTypeInCurrentInstantiation
07990   class CurrentInstantiationRebuilder
07991     : public TreeTransform<CurrentInstantiationRebuilder> {
07992     SourceLocation Loc;
07993     DeclarationName Entity;
07994 
07995   public:
07996     typedef TreeTransform<CurrentInstantiationRebuilder> inherited;
07997 
07998     CurrentInstantiationRebuilder(Sema &SemaRef,
07999                                   SourceLocation Loc,
08000                                   DeclarationName Entity)
08001     : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
08002       Loc(Loc), Entity(Entity) { }
08003 
08004     /// \brief Determine whether the given type \p T has already been
08005     /// transformed.
08006     ///
08007     /// For the purposes of type reconstruction, a type has already been
08008     /// transformed if it is NULL or if it is not dependent.
08009     bool AlreadyTransformed(QualType T) {
08010       return T.isNull() || !T->isDependentType();
08011     }
08012 
08013     /// \brief Returns the location of the entity whose type is being
08014     /// rebuilt.
08015     SourceLocation getBaseLocation() { return Loc; }
08016 
08017     /// \brief Returns the name of the entity whose type is being rebuilt.
08018     DeclarationName getBaseEntity() { return Entity; }
08019 
08020     /// \brief Sets the "base" location and entity when that
08021     /// information is known based on another transformation.
08022     void setBase(SourceLocation Loc, DeclarationName Entity) {
08023       this->Loc = Loc;
08024       this->Entity = Entity;
08025     }
08026       
08027     ExprResult TransformLambdaExpr(LambdaExpr *E) {
08028       // Lambdas never need to be transformed.
08029       return E;
08030     }
08031   };
08032 }
08033 
08034 /// \brief Rebuilds a type within the context of the current instantiation.
08035 ///
08036 /// The type \p T is part of the type of an out-of-line member definition of
08037 /// a class template (or class template partial specialization) that was parsed
08038 /// and constructed before we entered the scope of the class template (or
08039 /// partial specialization thereof). This routine will rebuild that type now
08040 /// that we have entered the declarator's scope, which may produce different
08041 /// canonical types, e.g.,
08042 ///
08043 /// \code
08044 /// template<typename T>
08045 /// struct X {
08046 ///   typedef T* pointer;
08047 ///   pointer data();
08048 /// };
08049 ///
08050 /// template<typename T>
08051 /// typename X<T>::pointer X<T>::data() { ... }
08052 /// \endcode
08053 ///
08054 /// Here, the type "typename X<T>::pointer" will be created as a DependentNameType,
08055 /// since we do not know that we can look into X<T> when we parsed the type.
08056 /// This function will rebuild the type, performing the lookup of "pointer"
08057 /// in X<T> and returning an ElaboratedType whose canonical type is the same
08058 /// as the canonical type of T*, allowing the return types of the out-of-line
08059 /// definition and the declaration to match.
08060 TypeSourceInfo *Sema::RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
08061                                                         SourceLocation Loc,
08062                                                         DeclarationName Name) {
08063   if (!T || !T->getType()->isDependentType())
08064     return T;
08065 
08066   CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
08067   return Rebuilder.TransformType(T);
08068 }
08069 
08070 ExprResult Sema::RebuildExprInCurrentInstantiation(Expr *E) {
08071   CurrentInstantiationRebuilder Rebuilder(*this, E->getExprLoc(),
08072                                           DeclarationName());
08073   return Rebuilder.TransformExpr(E);
08074 }
08075 
08076 bool Sema::RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS) {
08077   if (SS.isInvalid()) 
08078     return true;
08079 
08080   NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
08081   CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
08082                                           DeclarationName());
08083   NestedNameSpecifierLoc Rebuilt 
08084     = Rebuilder.TransformNestedNameSpecifierLoc(QualifierLoc);
08085   if (!Rebuilt) 
08086     return true;
08087 
08088   SS.Adopt(Rebuilt);
08089   return false;
08090 }
08091 
08092 /// \brief Rebuild the template parameters now that we know we're in a current
08093 /// instantiation.
08094 bool Sema::RebuildTemplateParamsInCurrentInstantiation(
08095                                                TemplateParameterList *Params) {
08096   for (unsigned I = 0, N = Params->size(); I != N; ++I) {
08097     Decl *Param = Params->getParam(I);
08098     
08099     // There is nothing to rebuild in a type parameter.
08100     if (isa<TemplateTypeParmDecl>(Param))
08101       continue;
08102     
08103     // Rebuild the template parameter list of a template template parameter.
08104     if (TemplateTemplateParmDecl *TTP 
08105         = dyn_cast<TemplateTemplateParmDecl>(Param)) {
08106       if (RebuildTemplateParamsInCurrentInstantiation(
08107             TTP->getTemplateParameters()))
08108         return true;
08109       
08110       continue;
08111     }
08112     
08113     // Rebuild the type of a non-type template parameter.
08114     NonTypeTemplateParmDecl *NTTP = cast<NonTypeTemplateParmDecl>(Param);
08115     TypeSourceInfo *NewTSI 
08116       = RebuildTypeInCurrentInstantiation(NTTP->getTypeSourceInfo(), 
08117                                           NTTP->getLocation(), 
08118                                           NTTP->getDeclName());
08119     if (!NewTSI)
08120       return true;
08121     
08122     if (NewTSI != NTTP->getTypeSourceInfo()) {
08123       NTTP->setTypeSourceInfo(NewTSI);
08124       NTTP->setType(NewTSI->getType());
08125     }
08126   }
08127   
08128   return false;
08129 }
08130 
08131 /// \brief Produces a formatted string that describes the binding of
08132 /// template parameters to template arguments.
08133 std::string
08134 Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
08135                                       const TemplateArgumentList &Args) {
08136   return getTemplateArgumentBindingsText(Params, Args.data(), Args.size());
08137 }
08138 
08139 std::string
08140 Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
08141                                       const TemplateArgument *Args,
08142                                       unsigned NumArgs) {
08143   SmallString<128> Str;
08144   llvm::raw_svector_ostream Out(Str);
08145 
08146   if (!Params || Params->size() == 0 || NumArgs == 0)
08147     return std::string();
08148 
08149   for (unsigned I = 0, N = Params->size(); I != N; ++I) {
08150     if (I >= NumArgs)
08151       break;
08152 
08153     if (I == 0)
08154       Out << "[with ";
08155     else
08156       Out << ", ";
08157 
08158     if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
08159       Out << Id->getName();
08160     } else {
08161       Out << '$' << I;
08162     }
08163 
08164     Out << " = ";
08165     Args[I].print(getPrintingPolicy(), Out);
08166   }
08167 
08168   Out << ']';
08169   return Out.str();
08170 }
08171 
08172 void Sema::MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD,
08173                                     CachedTokens &Toks) {
08174   if (!FD)
08175     return;
08176 
08177   LateParsedTemplate *LPT = new LateParsedTemplate;
08178 
08179   // Take tokens to avoid allocations
08180   LPT->Toks.swap(Toks);
08181   LPT->D = FnD;
08182   LateParsedTemplateMap[FD] = LPT;
08183 
08184   FD->setLateTemplateParsed(true);
08185 }
08186 
08187 void Sema::UnmarkAsLateParsedTemplate(FunctionDecl *FD) {
08188   if (!FD)
08189     return;
08190   FD->setLateTemplateParsed(false);
08191 }
08192 
08193 bool Sema::IsInsideALocalClassWithinATemplateFunction() {
08194   DeclContext *DC = CurContext;
08195 
08196   while (DC) {
08197     if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(CurContext)) {
08198       const FunctionDecl *FD = RD->isLocalClass();
08199       return (FD && FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate);
08200     } else if (DC->isTranslationUnit() || DC->isNamespace())
08201       return false;
08202 
08203     DC = DC->getParent();
08204   }
08205   return false;
08206 }