clang API Documentation

SemaTemplateInstantiate.cpp
Go to the documentation of this file.
00001 //===------- SemaTemplateInstantiate.cpp - C++ Template Instantiation ------===/
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 C++ template instantiation.
00010 //
00011 //===----------------------------------------------------------------------===/
00012 
00013 #include "clang/Sema/SemaInternal.h"
00014 #include "TreeTransform.h"
00015 #include "clang/AST/ASTConsumer.h"
00016 #include "clang/AST/ASTContext.h"
00017 #include "clang/AST/ASTLambda.h"
00018 #include "clang/AST/DeclTemplate.h"
00019 #include "clang/AST/Expr.h"
00020 #include "clang/Basic/LangOptions.h"
00021 #include "clang/Sema/DeclSpec.h"
00022 #include "clang/Sema/Initialization.h"
00023 #include "clang/Sema/Lookup.h"
00024 #include "clang/Sema/Template.h"
00025 #include "clang/Sema/TemplateDeduction.h"
00026 
00027 using namespace clang;
00028 using namespace sema;
00029 
00030 //===----------------------------------------------------------------------===/
00031 // Template Instantiation Support
00032 //===----------------------------------------------------------------------===/
00033 
00034 /// \brief Retrieve the template argument list(s) that should be used to
00035 /// instantiate the definition of the given declaration.
00036 ///
00037 /// \param D the declaration for which we are computing template instantiation
00038 /// arguments.
00039 ///
00040 /// \param Innermost if non-NULL, the innermost template argument list.
00041 ///
00042 /// \param RelativeToPrimary true if we should get the template
00043 /// arguments relative to the primary template, even when we're
00044 /// dealing with a specialization. This is only relevant for function
00045 /// template specializations.
00046 ///
00047 /// \param Pattern If non-NULL, indicates the pattern from which we will be
00048 /// instantiating the definition of the given declaration, \p D. This is
00049 /// used to determine the proper set of template instantiation arguments for
00050 /// friend function template specializations.
00051 MultiLevelTemplateArgumentList
00052 Sema::getTemplateInstantiationArgs(NamedDecl *D, 
00053                                    const TemplateArgumentList *Innermost,
00054                                    bool RelativeToPrimary,
00055                                    const FunctionDecl *Pattern) {
00056   // Accumulate the set of template argument lists in this structure.
00057   MultiLevelTemplateArgumentList Result;
00058 
00059   if (Innermost)
00060     Result.addOuterTemplateArguments(Innermost);
00061   
00062   DeclContext *Ctx = dyn_cast<DeclContext>(D);
00063   if (!Ctx) {
00064     Ctx = D->getDeclContext();
00065 
00066     // Add template arguments from a variable template instantiation.
00067     if (VarTemplateSpecializationDecl *Spec =
00068             dyn_cast<VarTemplateSpecializationDecl>(D)) {
00069       // We're done when we hit an explicit specialization.
00070       if (Spec->getSpecializationKind() == TSK_ExplicitSpecialization &&
00071           !isa<VarTemplatePartialSpecializationDecl>(Spec))
00072         return Result;
00073 
00074       Result.addOuterTemplateArguments(&Spec->getTemplateInstantiationArgs());
00075 
00076       // If this variable template specialization was instantiated from a
00077       // specialized member that is a variable template, we're done.
00078       assert(Spec->getSpecializedTemplate() && "No variable template?");
00079       llvm::PointerUnion<VarTemplateDecl*,
00080                          VarTemplatePartialSpecializationDecl*> Specialized
00081                              = Spec->getSpecializedTemplateOrPartial();
00082       if (VarTemplatePartialSpecializationDecl *Partial =
00083               Specialized.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
00084         if (Partial->isMemberSpecialization())
00085           return Result;
00086       } else {
00087         VarTemplateDecl *Tmpl = Specialized.get<VarTemplateDecl *>();
00088         if (Tmpl->isMemberSpecialization())
00089           return Result;
00090       }
00091     }
00092 
00093     // If we have a template template parameter with translation unit context,
00094     // then we're performing substitution into a default template argument of
00095     // this template template parameter before we've constructed the template
00096     // that will own this template template parameter. In this case, we
00097     // use empty template parameter lists for all of the outer templates
00098     // to avoid performing any substitutions.
00099     if (Ctx->isTranslationUnit()) {
00100       if (TemplateTemplateParmDecl *TTP 
00101                                       = dyn_cast<TemplateTemplateParmDecl>(D)) {
00102         for (unsigned I = 0, N = TTP->getDepth() + 1; I != N; ++I)
00103           Result.addOuterTemplateArguments(None);
00104         return Result;
00105       }
00106     }
00107   }
00108   
00109   while (!Ctx->isFileContext()) {
00110     // Add template arguments from a class template instantiation.
00111     if (ClassTemplateSpecializationDecl *Spec
00112           = dyn_cast<ClassTemplateSpecializationDecl>(Ctx)) {
00113       // We're done when we hit an explicit specialization.
00114       if (Spec->getSpecializationKind() == TSK_ExplicitSpecialization &&
00115           !isa<ClassTemplatePartialSpecializationDecl>(Spec))
00116         break;
00117 
00118       Result.addOuterTemplateArguments(&Spec->getTemplateInstantiationArgs());
00119       
00120       // If this class template specialization was instantiated from a 
00121       // specialized member that is a class template, we're done.
00122       assert(Spec->getSpecializedTemplate() && "No class template?");
00123       if (Spec->getSpecializedTemplate()->isMemberSpecialization())
00124         break;
00125     }
00126     // Add template arguments from a function template specialization.
00127     else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Ctx)) {
00128       if (!RelativeToPrimary &&
00129           (Function->getTemplateSpecializationKind() == 
00130                                                   TSK_ExplicitSpecialization &&
00131            !Function->getClassScopeSpecializationPattern()))
00132         break;
00133           
00134       if (const TemplateArgumentList *TemplateArgs
00135             = Function->getTemplateSpecializationArgs()) {
00136         // Add the template arguments for this specialization.
00137         Result.addOuterTemplateArguments(TemplateArgs);
00138 
00139         // If this function was instantiated from a specialized member that is
00140         // a function template, we're done.
00141         assert(Function->getPrimaryTemplate() && "No function template?");
00142         if (Function->getPrimaryTemplate()->isMemberSpecialization())
00143           break;
00144 
00145         // If this function is a generic lambda specialization, we are done.
00146         if (isGenericLambdaCallOperatorSpecialization(Function))
00147           break;
00148 
00149       } else if (FunctionTemplateDecl *FunTmpl
00150                                    = Function->getDescribedFunctionTemplate()) {
00151         // Add the "injected" template arguments.
00152         Result.addOuterTemplateArguments(FunTmpl->getInjectedTemplateArgs());
00153       }
00154       
00155       // If this is a friend declaration and it declares an entity at
00156       // namespace scope, take arguments from its lexical parent
00157       // instead of its semantic parent, unless of course the pattern we're
00158       // instantiating actually comes from the file's context!
00159       if (Function->getFriendObjectKind() &&
00160           Function->getDeclContext()->isFileContext() &&
00161           (!Pattern || !Pattern->getLexicalDeclContext()->isFileContext())) {
00162         Ctx = Function->getLexicalDeclContext();
00163         RelativeToPrimary = false;
00164         continue;
00165       }
00166     } else if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Ctx)) {
00167       if (ClassTemplateDecl *ClassTemplate = Rec->getDescribedClassTemplate()) {
00168         QualType T = ClassTemplate->getInjectedClassNameSpecialization();
00169         const TemplateSpecializationType *TST =
00170             cast<TemplateSpecializationType>(Context.getCanonicalType(T));
00171         Result.addOuterTemplateArguments(
00172             llvm::makeArrayRef(TST->getArgs(), TST->getNumArgs()));
00173         if (ClassTemplate->isMemberSpecialization())
00174           break;
00175       }
00176     }
00177 
00178     Ctx = Ctx->getParent();
00179     RelativeToPrimary = false;
00180   }
00181 
00182   return Result;
00183 }
00184 
00185 bool Sema::ActiveTemplateInstantiation::isInstantiationRecord() const {
00186   switch (Kind) {
00187   case TemplateInstantiation:
00188   case ExceptionSpecInstantiation:
00189   case DefaultTemplateArgumentInstantiation:
00190   case DefaultFunctionArgumentInstantiation:
00191   case ExplicitTemplateArgumentSubstitution:
00192   case DeducedTemplateArgumentSubstitution:
00193   case PriorTemplateArgumentSubstitution:
00194     return true;
00195 
00196   case DefaultTemplateArgumentChecking:
00197     return false;
00198   }
00199 
00200   llvm_unreachable("Invalid InstantiationKind!");
00201 }
00202 
00203 void Sema::InstantiatingTemplate::Initialize(
00204     ActiveTemplateInstantiation::InstantiationKind Kind,
00205     SourceLocation PointOfInstantiation, SourceRange InstantiationRange,
00206     Decl *Entity, NamedDecl *Template, ArrayRef<TemplateArgument> TemplateArgs,
00207     sema::TemplateDeductionInfo *DeductionInfo) {
00208   SavedInNonInstantiationSFINAEContext =
00209       SemaRef.InNonInstantiationSFINAEContext;
00210   Invalid = CheckInstantiationDepth(PointOfInstantiation, InstantiationRange);
00211   if (!Invalid) {
00212     ActiveTemplateInstantiation Inst;
00213     Inst.Kind = Kind;
00214     Inst.PointOfInstantiation = PointOfInstantiation;
00215     Inst.Entity = Entity;
00216     Inst.Template = Template;
00217     Inst.TemplateArgs = TemplateArgs.data();
00218     Inst.NumTemplateArgs = TemplateArgs.size();
00219     Inst.DeductionInfo = DeductionInfo;
00220     Inst.InstantiationRange = InstantiationRange;
00221     SemaRef.InNonInstantiationSFINAEContext = false;
00222     SemaRef.ActiveTemplateInstantiations.push_back(Inst);
00223     if (!Inst.isInstantiationRecord())
00224       ++SemaRef.NonInstantiationEntries;
00225   }
00226 }
00227 
00228 Sema::InstantiatingTemplate::
00229 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
00230                       Decl *Entity,
00231                       SourceRange InstantiationRange)
00232   : SemaRef(SemaRef)
00233 {
00234   Initialize(ActiveTemplateInstantiation::TemplateInstantiation,
00235              PointOfInstantiation, InstantiationRange, Entity);
00236 }
00237 
00238 Sema::InstantiatingTemplate::
00239 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
00240                       FunctionDecl *Entity, ExceptionSpecification,
00241                       SourceRange InstantiationRange)
00242   : SemaRef(SemaRef)
00243 {
00244   Initialize(ActiveTemplateInstantiation::ExceptionSpecInstantiation,
00245              PointOfInstantiation, InstantiationRange, Entity);
00246 }
00247 
00248 Sema::InstantiatingTemplate::
00249 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
00250                       TemplateDecl *Template,
00251                       ArrayRef<TemplateArgument> TemplateArgs,
00252                       SourceRange InstantiationRange)
00253   : SemaRef(SemaRef)
00254 {
00255   Initialize(ActiveTemplateInstantiation::DefaultTemplateArgumentInstantiation,
00256              PointOfInstantiation, InstantiationRange,
00257              Template, nullptr, TemplateArgs);
00258 }
00259 
00260 Sema::InstantiatingTemplate::
00261 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
00262                       FunctionTemplateDecl *FunctionTemplate,
00263                       ArrayRef<TemplateArgument> TemplateArgs,
00264                       ActiveTemplateInstantiation::InstantiationKind Kind,
00265                       sema::TemplateDeductionInfo &DeductionInfo,
00266                       SourceRange InstantiationRange)
00267   : SemaRef(SemaRef)
00268 {
00269   Initialize(Kind, PointOfInstantiation, InstantiationRange,
00270              FunctionTemplate, nullptr, TemplateArgs, &DeductionInfo);
00271 }
00272 
00273 Sema::InstantiatingTemplate::
00274 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
00275                       ClassTemplatePartialSpecializationDecl *PartialSpec,
00276                       ArrayRef<TemplateArgument> TemplateArgs,
00277                       sema::TemplateDeductionInfo &DeductionInfo,
00278                       SourceRange InstantiationRange)
00279   : SemaRef(SemaRef)
00280 {
00281   Initialize(ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution,
00282              PointOfInstantiation, InstantiationRange,
00283              PartialSpec, nullptr, TemplateArgs, &DeductionInfo);
00284 }
00285 
00286 Sema::InstantiatingTemplate::InstantiatingTemplate(
00287     Sema &SemaRef, SourceLocation PointOfInstantiation,
00288     VarTemplatePartialSpecializationDecl *PartialSpec,
00289     ArrayRef<TemplateArgument> TemplateArgs,
00290     sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
00291   : SemaRef(SemaRef)
00292 {
00293   Initialize(ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution,
00294              PointOfInstantiation, InstantiationRange,
00295              PartialSpec, nullptr, TemplateArgs, &DeductionInfo);
00296 }
00297 
00298 Sema::InstantiatingTemplate::
00299 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
00300                       ParmVarDecl *Param,
00301                       ArrayRef<TemplateArgument> TemplateArgs,
00302                       SourceRange InstantiationRange)
00303   : SemaRef(SemaRef)
00304 {
00305   Initialize(ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation,
00306              PointOfInstantiation, InstantiationRange,
00307              Param, nullptr, TemplateArgs);
00308 }
00309 
00310 
00311 Sema::InstantiatingTemplate::
00312 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
00313                       NamedDecl *Template, NonTypeTemplateParmDecl *Param,
00314                       ArrayRef<TemplateArgument> TemplateArgs,
00315                       SourceRange InstantiationRange)
00316   : SemaRef(SemaRef)
00317 {
00318   Initialize(ActiveTemplateInstantiation::PriorTemplateArgumentSubstitution,
00319              PointOfInstantiation, InstantiationRange,
00320              Param, Template, TemplateArgs);
00321 }
00322 
00323 Sema::InstantiatingTemplate::
00324 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
00325                       NamedDecl *Template, TemplateTemplateParmDecl *Param,
00326                       ArrayRef<TemplateArgument> TemplateArgs,
00327                       SourceRange InstantiationRange)
00328   : SemaRef(SemaRef)
00329 {
00330   Initialize(ActiveTemplateInstantiation::PriorTemplateArgumentSubstitution,
00331              PointOfInstantiation, InstantiationRange,
00332              Param, Template, TemplateArgs);
00333 }
00334 
00335 Sema::InstantiatingTemplate::
00336 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
00337                       TemplateDecl *Template, NamedDecl *Param,
00338                       ArrayRef<TemplateArgument> TemplateArgs,
00339                       SourceRange InstantiationRange)
00340   : SemaRef(SemaRef)
00341 {
00342   Initialize(ActiveTemplateInstantiation::DefaultTemplateArgumentChecking,
00343              PointOfInstantiation, InstantiationRange,
00344              Param, Template, TemplateArgs);
00345 }
00346 
00347 void Sema::InstantiatingTemplate::Clear() {
00348   if (!Invalid) {
00349     if (!SemaRef.ActiveTemplateInstantiations.back().isInstantiationRecord()) {
00350       assert(SemaRef.NonInstantiationEntries > 0);
00351       --SemaRef.NonInstantiationEntries;
00352     }
00353     SemaRef.InNonInstantiationSFINAEContext
00354       = SavedInNonInstantiationSFINAEContext;
00355 
00356     // Name lookup no longer looks in this template's defining module.
00357     assert(SemaRef.ActiveTemplateInstantiations.size() >=
00358            SemaRef.ActiveTemplateInstantiationLookupModules.size() &&
00359            "forgot to remove a lookup module for a template instantiation");
00360     if (SemaRef.ActiveTemplateInstantiations.size() ==
00361         SemaRef.ActiveTemplateInstantiationLookupModules.size()) {
00362       if (Module *M = SemaRef.ActiveTemplateInstantiationLookupModules.back())
00363         SemaRef.LookupModulesCache.erase(M);
00364       SemaRef.ActiveTemplateInstantiationLookupModules.pop_back();
00365     }
00366 
00367     SemaRef.ActiveTemplateInstantiations.pop_back();
00368     Invalid = true;
00369   }
00370 }
00371 
00372 bool Sema::InstantiatingTemplate::CheckInstantiationDepth(
00373                                         SourceLocation PointOfInstantiation,
00374                                            SourceRange InstantiationRange) {
00375   assert(SemaRef.NonInstantiationEntries <=
00376                                    SemaRef.ActiveTemplateInstantiations.size());
00377   if ((SemaRef.ActiveTemplateInstantiations.size() - 
00378           SemaRef.NonInstantiationEntries)
00379         <= SemaRef.getLangOpts().InstantiationDepth)
00380     return false;
00381 
00382   SemaRef.Diag(PointOfInstantiation,
00383                diag::err_template_recursion_depth_exceeded)
00384     << SemaRef.getLangOpts().InstantiationDepth
00385     << InstantiationRange;
00386   SemaRef.Diag(PointOfInstantiation, diag::note_template_recursion_depth)
00387     << SemaRef.getLangOpts().InstantiationDepth;
00388   return true;
00389 }
00390 
00391 /// \brief Prints the current instantiation stack through a series of
00392 /// notes.
00393 void Sema::PrintInstantiationStack() {
00394   // Determine which template instantiations to skip, if any.
00395   unsigned SkipStart = ActiveTemplateInstantiations.size(), SkipEnd = SkipStart;
00396   unsigned Limit = Diags.getTemplateBacktraceLimit();
00397   if (Limit && Limit < ActiveTemplateInstantiations.size()) {
00398     SkipStart = Limit / 2 + Limit % 2;
00399     SkipEnd = ActiveTemplateInstantiations.size() - Limit / 2;
00400   }
00401 
00402   // FIXME: In all of these cases, we need to show the template arguments
00403   unsigned InstantiationIdx = 0;
00404   for (SmallVectorImpl<ActiveTemplateInstantiation>::reverse_iterator
00405          Active = ActiveTemplateInstantiations.rbegin(),
00406          ActiveEnd = ActiveTemplateInstantiations.rend();
00407        Active != ActiveEnd;
00408        ++Active, ++InstantiationIdx) {
00409     // Skip this instantiation?
00410     if (InstantiationIdx >= SkipStart && InstantiationIdx < SkipEnd) {
00411       if (InstantiationIdx == SkipStart) {
00412         // Note that we're skipping instantiations.
00413         Diags.Report(Active->PointOfInstantiation,
00414                      diag::note_instantiation_contexts_suppressed)
00415           << unsigned(ActiveTemplateInstantiations.size() - Limit);
00416       }
00417       continue;
00418     }
00419 
00420     switch (Active->Kind) {
00421     case ActiveTemplateInstantiation::TemplateInstantiation: {
00422       Decl *D = Active->Entity;
00423       if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
00424         unsigned DiagID = diag::note_template_member_class_here;
00425         if (isa<ClassTemplateSpecializationDecl>(Record))
00426           DiagID = diag::note_template_class_instantiation_here;
00427         Diags.Report(Active->PointOfInstantiation, DiagID)
00428           << Context.getTypeDeclType(Record)
00429           << Active->InstantiationRange;
00430       } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
00431         unsigned DiagID;
00432         if (Function->getPrimaryTemplate())
00433           DiagID = diag::note_function_template_spec_here;
00434         else
00435           DiagID = diag::note_template_member_function_here;
00436         Diags.Report(Active->PointOfInstantiation, DiagID)
00437           << Function
00438           << Active->InstantiationRange;
00439       } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
00440         Diags.Report(Active->PointOfInstantiation,
00441                      VD->isStaticDataMember()?
00442                        diag::note_template_static_data_member_def_here
00443                      : diag::note_template_variable_def_here)
00444           << VD
00445           << Active->InstantiationRange;
00446       } else if (EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
00447         Diags.Report(Active->PointOfInstantiation,
00448                      diag::note_template_enum_def_here)
00449           << ED
00450           << Active->InstantiationRange;
00451       } else if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
00452         Diags.Report(Active->PointOfInstantiation,
00453                      diag::note_template_nsdmi_here)
00454             << FD << Active->InstantiationRange;
00455       } else {
00456         Diags.Report(Active->PointOfInstantiation,
00457                      diag::note_template_type_alias_instantiation_here)
00458           << cast<TypeAliasTemplateDecl>(D)
00459           << Active->InstantiationRange;
00460       }
00461       break;
00462     }
00463 
00464     case ActiveTemplateInstantiation::DefaultTemplateArgumentInstantiation: {
00465       TemplateDecl *Template = cast<TemplateDecl>(Active->Entity);
00466       SmallVector<char, 128> TemplateArgsStr;
00467       llvm::raw_svector_ostream OS(TemplateArgsStr);
00468       Template->printName(OS);
00469       TemplateSpecializationType::PrintTemplateArgumentList(OS,
00470                                                          Active->TemplateArgs,
00471                                                       Active->NumTemplateArgs,
00472                                                       getPrintingPolicy());
00473       Diags.Report(Active->PointOfInstantiation,
00474                    diag::note_default_arg_instantiation_here)
00475         << OS.str()
00476         << Active->InstantiationRange;
00477       break;
00478     }
00479 
00480     case ActiveTemplateInstantiation::ExplicitTemplateArgumentSubstitution: {
00481       FunctionTemplateDecl *FnTmpl = cast<FunctionTemplateDecl>(Active->Entity);
00482       Diags.Report(Active->PointOfInstantiation,
00483                    diag::note_explicit_template_arg_substitution_here)
00484         << FnTmpl 
00485         << getTemplateArgumentBindingsText(FnTmpl->getTemplateParameters(), 
00486                                            Active->TemplateArgs, 
00487                                            Active->NumTemplateArgs)
00488         << Active->InstantiationRange;
00489       break;
00490     }
00491 
00492     case ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution:
00493       if (ClassTemplatePartialSpecializationDecl *PartialSpec =
00494             dyn_cast<ClassTemplatePartialSpecializationDecl>(Active->Entity)) {
00495         Diags.Report(Active->PointOfInstantiation,
00496                      diag::note_partial_spec_deduct_instantiation_here)
00497           << Context.getTypeDeclType(PartialSpec)
00498           << getTemplateArgumentBindingsText(
00499                                          PartialSpec->getTemplateParameters(), 
00500                                              Active->TemplateArgs, 
00501                                              Active->NumTemplateArgs)
00502           << Active->InstantiationRange;
00503       } else {
00504         FunctionTemplateDecl *FnTmpl
00505           = cast<FunctionTemplateDecl>(Active->Entity);
00506         Diags.Report(Active->PointOfInstantiation,
00507                      diag::note_function_template_deduction_instantiation_here)
00508           << FnTmpl
00509           << getTemplateArgumentBindingsText(FnTmpl->getTemplateParameters(), 
00510                                              Active->TemplateArgs, 
00511                                              Active->NumTemplateArgs)
00512           << Active->InstantiationRange;
00513       }
00514       break;
00515 
00516     case ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation: {
00517       ParmVarDecl *Param = cast<ParmVarDecl>(Active->Entity);
00518       FunctionDecl *FD = cast<FunctionDecl>(Param->getDeclContext());
00519 
00520       SmallVector<char, 128> TemplateArgsStr;
00521       llvm::raw_svector_ostream OS(TemplateArgsStr);
00522       FD->printName(OS);
00523       TemplateSpecializationType::PrintTemplateArgumentList(OS,
00524                                                          Active->TemplateArgs,
00525                                                       Active->NumTemplateArgs,
00526                                                       getPrintingPolicy());
00527       Diags.Report(Active->PointOfInstantiation,
00528                    diag::note_default_function_arg_instantiation_here)
00529         << OS.str()
00530         << Active->InstantiationRange;
00531       break;
00532     }
00533 
00534     case ActiveTemplateInstantiation::PriorTemplateArgumentSubstitution: {
00535       NamedDecl *Parm = cast<NamedDecl>(Active->Entity);
00536       std::string Name;
00537       if (!Parm->getName().empty())
00538         Name = std::string(" '") + Parm->getName().str() + "'";
00539 
00540       TemplateParameterList *TemplateParams = nullptr;
00541       if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
00542         TemplateParams = Template->getTemplateParameters();
00543       else
00544         TemplateParams =
00545           cast<ClassTemplatePartialSpecializationDecl>(Active->Template)
00546                                                       ->getTemplateParameters();
00547       Diags.Report(Active->PointOfInstantiation,
00548                    diag::note_prior_template_arg_substitution)
00549         << isa<TemplateTemplateParmDecl>(Parm)
00550         << Name
00551         << getTemplateArgumentBindingsText(TemplateParams, 
00552                                            Active->TemplateArgs, 
00553                                            Active->NumTemplateArgs)
00554         << Active->InstantiationRange;
00555       break;
00556     }
00557 
00558     case ActiveTemplateInstantiation::DefaultTemplateArgumentChecking: {
00559       TemplateParameterList *TemplateParams = nullptr;
00560       if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
00561         TemplateParams = Template->getTemplateParameters();
00562       else
00563         TemplateParams =
00564           cast<ClassTemplatePartialSpecializationDecl>(Active->Template)
00565                                                       ->getTemplateParameters();
00566 
00567       Diags.Report(Active->PointOfInstantiation,
00568                    diag::note_template_default_arg_checking)
00569         << getTemplateArgumentBindingsText(TemplateParams, 
00570                                            Active->TemplateArgs, 
00571                                            Active->NumTemplateArgs)
00572         << Active->InstantiationRange;
00573       break;
00574     }
00575 
00576     case ActiveTemplateInstantiation::ExceptionSpecInstantiation:
00577       Diags.Report(Active->PointOfInstantiation,
00578                    diag::note_template_exception_spec_instantiation_here)
00579         << cast<FunctionDecl>(Active->Entity)
00580         << Active->InstantiationRange;
00581       break;
00582     }
00583   }
00584 }
00585 
00586 Optional<TemplateDeductionInfo *> Sema::isSFINAEContext() const {
00587   if (InNonInstantiationSFINAEContext)
00588     return Optional<TemplateDeductionInfo *>(nullptr);
00589 
00590   for (SmallVectorImpl<ActiveTemplateInstantiation>::const_reverse_iterator
00591          Active = ActiveTemplateInstantiations.rbegin(),
00592          ActiveEnd = ActiveTemplateInstantiations.rend();
00593        Active != ActiveEnd;
00594        ++Active) 
00595   {
00596     switch(Active->Kind) {
00597     case ActiveTemplateInstantiation::TemplateInstantiation:
00598       // An instantiation of an alias template may or may not be a SFINAE
00599       // context, depending on what else is on the stack.
00600       if (isa<TypeAliasTemplateDecl>(Active->Entity))
00601         break;
00602       // Fall through.
00603     case ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation:
00604     case ActiveTemplateInstantiation::ExceptionSpecInstantiation:
00605       // This is a template instantiation, so there is no SFINAE.
00606       return None;
00607 
00608     case ActiveTemplateInstantiation::DefaultTemplateArgumentInstantiation:
00609     case ActiveTemplateInstantiation::PriorTemplateArgumentSubstitution:
00610     case ActiveTemplateInstantiation::DefaultTemplateArgumentChecking:
00611       // A default template argument instantiation and substitution into
00612       // template parameters with arguments for prior parameters may or may 
00613       // not be a SFINAE context; look further up the stack.
00614       break;
00615 
00616     case ActiveTemplateInstantiation::ExplicitTemplateArgumentSubstitution:
00617     case ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution:
00618       // We're either substitution explicitly-specified template arguments
00619       // or deduced template arguments, so SFINAE applies.
00620       assert(Active->DeductionInfo && "Missing deduction info pointer");
00621       return Active->DeductionInfo;
00622     }
00623   }
00624 
00625   return None;
00626 }
00627 
00628 /// \brief Retrieve the depth and index of a parameter pack.
00629 static std::pair<unsigned, unsigned> 
00630 getDepthAndIndex(NamedDecl *ND) {
00631   if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ND))
00632     return std::make_pair(TTP->getDepth(), TTP->getIndex());
00633   
00634   if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(ND))
00635     return std::make_pair(NTTP->getDepth(), NTTP->getIndex());
00636   
00637   TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(ND);
00638   return std::make_pair(TTP->getDepth(), TTP->getIndex());
00639 }
00640 
00641 //===----------------------------------------------------------------------===/
00642 // Template Instantiation for Types
00643 //===----------------------------------------------------------------------===/
00644 namespace {
00645   class TemplateInstantiator : public TreeTransform<TemplateInstantiator> {
00646     const MultiLevelTemplateArgumentList &TemplateArgs;
00647     SourceLocation Loc;
00648     DeclarationName Entity;
00649 
00650   public:
00651     typedef TreeTransform<TemplateInstantiator> inherited;
00652 
00653     TemplateInstantiator(Sema &SemaRef,
00654                          const MultiLevelTemplateArgumentList &TemplateArgs,
00655                          SourceLocation Loc,
00656                          DeclarationName Entity)
00657       : inherited(SemaRef), TemplateArgs(TemplateArgs), Loc(Loc),
00658         Entity(Entity) { }
00659 
00660     /// \brief Determine whether the given type \p T has already been
00661     /// transformed.
00662     ///
00663     /// For the purposes of template instantiation, a type has already been
00664     /// transformed if it is NULL or if it is not dependent.
00665     bool AlreadyTransformed(QualType T);
00666 
00667     /// \brief Returns the location of the entity being instantiated, if known.
00668     SourceLocation getBaseLocation() { return Loc; }
00669 
00670     /// \brief Returns the name of the entity being instantiated, if any.
00671     DeclarationName getBaseEntity() { return Entity; }
00672 
00673     /// \brief Sets the "base" location and entity when that
00674     /// information is known based on another transformation.
00675     void setBase(SourceLocation Loc, DeclarationName Entity) {
00676       this->Loc = Loc;
00677       this->Entity = Entity;
00678     }
00679 
00680     bool TryExpandParameterPacks(SourceLocation EllipsisLoc,
00681                                  SourceRange PatternRange,
00682                                  ArrayRef<UnexpandedParameterPack> Unexpanded,
00683                                  bool &ShouldExpand, bool &RetainExpansion,
00684                                  Optional<unsigned> &NumExpansions) {
00685       return getSema().CheckParameterPacksForExpansion(EllipsisLoc, 
00686                                                        PatternRange, Unexpanded,
00687                                                        TemplateArgs, 
00688                                                        ShouldExpand,
00689                                                        RetainExpansion,
00690                                                        NumExpansions);
00691     }
00692 
00693     void ExpandingFunctionParameterPack(ParmVarDecl *Pack) { 
00694       SemaRef.CurrentInstantiationScope->MakeInstantiatedLocalArgPack(Pack);
00695     }
00696     
00697     TemplateArgument ForgetPartiallySubstitutedPack() {
00698       TemplateArgument Result;
00699       if (NamedDecl *PartialPack
00700             = SemaRef.CurrentInstantiationScope->getPartiallySubstitutedPack()){
00701         MultiLevelTemplateArgumentList &TemplateArgs
00702           = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
00703         unsigned Depth, Index;
00704         std::tie(Depth, Index) = getDepthAndIndex(PartialPack);
00705         if (TemplateArgs.hasTemplateArgument(Depth, Index)) {
00706           Result = TemplateArgs(Depth, Index);
00707           TemplateArgs.setArgument(Depth, Index, TemplateArgument());
00708         }
00709       }
00710       
00711       return Result;
00712     }
00713     
00714     void RememberPartiallySubstitutedPack(TemplateArgument Arg) {
00715       if (Arg.isNull())
00716         return;
00717       
00718       if (NamedDecl *PartialPack
00719             = SemaRef.CurrentInstantiationScope->getPartiallySubstitutedPack()){
00720         MultiLevelTemplateArgumentList &TemplateArgs
00721         = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
00722         unsigned Depth, Index;
00723         std::tie(Depth, Index) = getDepthAndIndex(PartialPack);
00724         TemplateArgs.setArgument(Depth, Index, Arg);
00725       }
00726     }
00727 
00728     /// \brief Transform the given declaration by instantiating a reference to
00729     /// this declaration.
00730     Decl *TransformDecl(SourceLocation Loc, Decl *D);
00731 
00732     void transformAttrs(Decl *Old, Decl *New) { 
00733       SemaRef.InstantiateAttrs(TemplateArgs, Old, New);
00734     }
00735 
00736     void transformedLocalDecl(Decl *Old, Decl *New) {
00737       SemaRef.CurrentInstantiationScope->InstantiatedLocal(Old, New);
00738     }
00739     
00740     /// \brief Transform the definition of the given declaration by
00741     /// instantiating it.
00742     Decl *TransformDefinition(SourceLocation Loc, Decl *D);
00743 
00744     /// \brief Transform the first qualifier within a scope by instantiating the
00745     /// declaration.
00746     NamedDecl *TransformFirstQualifierInScope(NamedDecl *D, SourceLocation Loc);
00747       
00748     /// \brief Rebuild the exception declaration and register the declaration
00749     /// as an instantiated local.
00750     VarDecl *RebuildExceptionDecl(VarDecl *ExceptionDecl, 
00751                                   TypeSourceInfo *Declarator,
00752                                   SourceLocation StartLoc,
00753                                   SourceLocation NameLoc,
00754                                   IdentifierInfo *Name);
00755 
00756     /// \brief Rebuild the Objective-C exception declaration and register the 
00757     /// declaration as an instantiated local.
00758     VarDecl *RebuildObjCExceptionDecl(VarDecl *ExceptionDecl, 
00759                                       TypeSourceInfo *TSInfo, QualType T);
00760       
00761     /// \brief Check for tag mismatches when instantiating an
00762     /// elaborated type.
00763     QualType RebuildElaboratedType(SourceLocation KeywordLoc,
00764                                    ElaboratedTypeKeyword Keyword,
00765                                    NestedNameSpecifierLoc QualifierLoc,
00766                                    QualType T);
00767 
00768     TemplateName
00769     TransformTemplateName(CXXScopeSpec &SS, TemplateName Name,
00770                           SourceLocation NameLoc,
00771                           QualType ObjectType = QualType(),
00772                           NamedDecl *FirstQualifierInScope = nullptr);
00773 
00774     const LoopHintAttr *TransformLoopHintAttr(const LoopHintAttr *LH);
00775 
00776     ExprResult TransformPredefinedExpr(PredefinedExpr *E);
00777     ExprResult TransformDeclRefExpr(DeclRefExpr *E);
00778     ExprResult TransformCXXDefaultArgExpr(CXXDefaultArgExpr *E);
00779 
00780     ExprResult TransformTemplateParmRefExpr(DeclRefExpr *E,
00781                                             NonTypeTemplateParmDecl *D);
00782     ExprResult TransformSubstNonTypeTemplateParmPackExpr(
00783                                            SubstNonTypeTemplateParmPackExpr *E);
00784 
00785     /// \brief Rebuild a DeclRefExpr for a ParmVarDecl reference.
00786     ExprResult RebuildParmVarDeclRefExpr(ParmVarDecl *PD, SourceLocation Loc);
00787 
00788     /// \brief Transform a reference to a function parameter pack.
00789     ExprResult TransformFunctionParmPackRefExpr(DeclRefExpr *E,
00790                                                 ParmVarDecl *PD);
00791 
00792     /// \brief Transform a FunctionParmPackExpr which was built when we couldn't
00793     /// expand a function parameter pack reference which refers to an expanded
00794     /// pack.
00795     ExprResult TransformFunctionParmPackExpr(FunctionParmPackExpr *E);
00796 
00797     QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
00798                                         FunctionProtoTypeLoc TL) {
00799       // Call the base version; it will forward to our overridden version below.
00800       return inherited::TransformFunctionProtoType(TLB, TL);
00801     }
00802 
00803     template<typename Fn>
00804     QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
00805                                         FunctionProtoTypeLoc TL,
00806                                         CXXRecordDecl *ThisContext,
00807                                         unsigned ThisTypeQuals,
00808                                         Fn TransformExceptionSpec);
00809 
00810     ParmVarDecl *TransformFunctionTypeParam(ParmVarDecl *OldParm,
00811                                             int indexAdjustment,
00812                                             Optional<unsigned> NumExpansions,
00813                                             bool ExpectParameterPack);
00814 
00815     /// \brief Transforms a template type parameter type by performing
00816     /// substitution of the corresponding template type argument.
00817     QualType TransformTemplateTypeParmType(TypeLocBuilder &TLB,
00818                                            TemplateTypeParmTypeLoc TL);
00819 
00820     /// \brief Transforms an already-substituted template type parameter pack
00821     /// into either itself (if we aren't substituting into its pack expansion)
00822     /// or the appropriate substituted argument.
00823     QualType TransformSubstTemplateTypeParmPackType(TypeLocBuilder &TLB,
00824                                            SubstTemplateTypeParmPackTypeLoc TL);
00825 
00826     ExprResult TransformCallExpr(CallExpr *CE) {
00827       getSema().CallsUndergoingInstantiation.push_back(CE);
00828       ExprResult Result =
00829           TreeTransform<TemplateInstantiator>::TransformCallExpr(CE);
00830       getSema().CallsUndergoingInstantiation.pop_back();
00831       return Result;
00832     }
00833 
00834     ExprResult TransformLambdaExpr(LambdaExpr *E) {
00835       LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
00836       return TreeTransform<TemplateInstantiator>::TransformLambdaExpr(E);
00837     }
00838 
00839     ExprResult TransformLambdaScope(LambdaExpr *E,
00840         CXXMethodDecl *NewCallOperator, 
00841         ArrayRef<InitCaptureInfoTy> InitCaptureExprsAndTypes) {
00842       CXXMethodDecl *const OldCallOperator = E->getCallOperator();   
00843       // In the generic lambda case, we set the NewTemplate to be considered
00844       // an "instantiation" of the OldTemplate.
00845       if (FunctionTemplateDecl *const NewCallOperatorTemplate = 
00846             NewCallOperator->getDescribedFunctionTemplate()) {
00847         
00848         FunctionTemplateDecl *const OldCallOperatorTemplate = 
00849                               OldCallOperator->getDescribedFunctionTemplate();
00850         NewCallOperatorTemplate->setInstantiatedFromMemberTemplate(
00851                                                      OldCallOperatorTemplate);
00852       } else 
00853         // For a non-generic lambda we set the NewCallOperator to 
00854         // be an instantiation of the OldCallOperator.
00855         NewCallOperator->setInstantiationOfMemberFunction(OldCallOperator,
00856                                                     TSK_ImplicitInstantiation);
00857       
00858       return inherited::TransformLambdaScope(E, NewCallOperator, 
00859           InitCaptureExprsAndTypes);
00860     }
00861     TemplateParameterList *TransformTemplateParameterList(
00862                               TemplateParameterList *OrigTPL)  {
00863       if (!OrigTPL || !OrigTPL->size()) return OrigTPL;
00864          
00865       DeclContext *Owner = OrigTPL->getParam(0)->getDeclContext();
00866       TemplateDeclInstantiator  DeclInstantiator(getSema(), 
00867                         /* DeclContext *Owner */ Owner, TemplateArgs);
00868       return DeclInstantiator.SubstTemplateParams(OrigTPL); 
00869     }
00870   private:
00871     ExprResult transformNonTypeTemplateParmRef(NonTypeTemplateParmDecl *parm,
00872                                                SourceLocation loc,
00873                                                TemplateArgument arg);
00874   };
00875 }
00876 
00877 bool TemplateInstantiator::AlreadyTransformed(QualType T) {
00878   if (T.isNull())
00879     return true;
00880   
00881   if (T->isInstantiationDependentType() || T->isVariablyModifiedType())
00882     return false;
00883   
00884   getSema().MarkDeclarationsReferencedInType(Loc, T);
00885   return true;
00886 }
00887 
00888 static TemplateArgument
00889 getPackSubstitutedTemplateArgument(Sema &S, TemplateArgument Arg) {
00890   assert(S.ArgumentPackSubstitutionIndex >= 0);        
00891   assert(S.ArgumentPackSubstitutionIndex < (int)Arg.pack_size());
00892   Arg = Arg.pack_begin()[S.ArgumentPackSubstitutionIndex];
00893   if (Arg.isPackExpansion())
00894     Arg = Arg.getPackExpansionPattern();
00895   return Arg;
00896 }
00897 
00898 Decl *TemplateInstantiator::TransformDecl(SourceLocation Loc, Decl *D) {
00899   if (!D)
00900     return nullptr;
00901 
00902   if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(D)) {
00903     if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
00904       // If the corresponding template argument is NULL or non-existent, it's
00905       // because we are performing instantiation from explicitly-specified
00906       // template arguments in a function template, but there were some
00907       // arguments left unspecified.
00908       if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
00909                                             TTP->getPosition()))
00910         return D;
00911 
00912       TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
00913       
00914       if (TTP->isParameterPack()) {
00915         assert(Arg.getKind() == TemplateArgument::Pack && 
00916                "Missing argument pack");
00917         Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
00918       }
00919 
00920       TemplateName Template = Arg.getAsTemplate();
00921       assert(!Template.isNull() && Template.getAsTemplateDecl() &&
00922              "Wrong kind of template template argument");
00923       return Template.getAsTemplateDecl();
00924     }
00925 
00926     // Fall through to find the instantiated declaration for this template
00927     // template parameter.
00928   }
00929 
00930   return SemaRef.FindInstantiatedDecl(Loc, cast<NamedDecl>(D), TemplateArgs);
00931 }
00932 
00933 Decl *TemplateInstantiator::TransformDefinition(SourceLocation Loc, Decl *D) {
00934   Decl *Inst = getSema().SubstDecl(D, getSema().CurContext, TemplateArgs);
00935   if (!Inst)
00936     return nullptr;
00937 
00938   getSema().CurrentInstantiationScope->InstantiatedLocal(D, Inst);
00939   return Inst;
00940 }
00941 
00942 NamedDecl *
00943 TemplateInstantiator::TransformFirstQualifierInScope(NamedDecl *D, 
00944                                                      SourceLocation Loc) {
00945   // If the first part of the nested-name-specifier was a template type 
00946   // parameter, instantiate that type parameter down to a tag type.
00947   if (TemplateTypeParmDecl *TTPD = dyn_cast_or_null<TemplateTypeParmDecl>(D)) {
00948     const TemplateTypeParmType *TTP 
00949       = cast<TemplateTypeParmType>(getSema().Context.getTypeDeclType(TTPD));
00950     
00951     if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
00952       // FIXME: This needs testing w/ member access expressions.
00953       TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getIndex());
00954       
00955       if (TTP->isParameterPack()) {
00956         assert(Arg.getKind() == TemplateArgument::Pack && 
00957                "Missing argument pack");
00958         
00959         if (getSema().ArgumentPackSubstitutionIndex == -1)
00960           return nullptr;
00961 
00962         Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
00963       }
00964 
00965       QualType T = Arg.getAsType();
00966       if (T.isNull())
00967         return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
00968       
00969       if (const TagType *Tag = T->getAs<TagType>())
00970         return Tag->getDecl();
00971       
00972       // The resulting type is not a tag; complain.
00973       getSema().Diag(Loc, diag::err_nested_name_spec_non_tag) << T;
00974       return nullptr;
00975     }
00976   }
00977   
00978   return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
00979 }
00980 
00981 VarDecl *
00982 TemplateInstantiator::RebuildExceptionDecl(VarDecl *ExceptionDecl,
00983                                            TypeSourceInfo *Declarator,
00984                                            SourceLocation StartLoc,
00985                                            SourceLocation NameLoc,
00986                                            IdentifierInfo *Name) {
00987   VarDecl *Var = inherited::RebuildExceptionDecl(ExceptionDecl, Declarator,
00988                                                  StartLoc, NameLoc, Name);
00989   if (Var)
00990     getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
00991   return Var;
00992 }
00993 
00994 VarDecl *TemplateInstantiator::RebuildObjCExceptionDecl(VarDecl *ExceptionDecl, 
00995                                                         TypeSourceInfo *TSInfo, 
00996                                                         QualType T) {
00997   VarDecl *Var = inherited::RebuildObjCExceptionDecl(ExceptionDecl, TSInfo, T);
00998   if (Var)
00999     getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
01000   return Var;
01001 }
01002 
01003 QualType
01004 TemplateInstantiator::RebuildElaboratedType(SourceLocation KeywordLoc,
01005                                             ElaboratedTypeKeyword Keyword,
01006                                             NestedNameSpecifierLoc QualifierLoc,
01007                                             QualType T) {
01008   if (const TagType *TT = T->getAs<TagType>()) {
01009     TagDecl* TD = TT->getDecl();
01010 
01011     SourceLocation TagLocation = KeywordLoc;
01012 
01013     IdentifierInfo *Id = TD->getIdentifier();
01014 
01015     // TODO: should we even warn on struct/class mismatches for this?  Seems
01016     // like it's likely to produce a lot of spurious errors.
01017     if (Id && Keyword != ETK_None && Keyword != ETK_Typename) {
01018       TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForKeyword(Keyword);
01019       if (!SemaRef.isAcceptableTagRedeclaration(TD, Kind, /*isDefinition*/false,
01020                                                 TagLocation, *Id)) {
01021         SemaRef.Diag(TagLocation, diag::err_use_with_wrong_tag)
01022           << Id
01023           << FixItHint::CreateReplacement(SourceRange(TagLocation),
01024                                           TD->getKindName());
01025         SemaRef.Diag(TD->getLocation(), diag::note_previous_use);
01026       }
01027     }
01028   }
01029 
01030   return TreeTransform<TemplateInstantiator>::RebuildElaboratedType(KeywordLoc,
01031                                                                     Keyword,
01032                                                                   QualifierLoc,
01033                                                                     T);
01034 }
01035 
01036 TemplateName TemplateInstantiator::TransformTemplateName(CXXScopeSpec &SS,
01037                                                          TemplateName Name,
01038                                                          SourceLocation NameLoc,
01039                                                          QualType ObjectType,
01040                                              NamedDecl *FirstQualifierInScope) {
01041   if (TemplateTemplateParmDecl *TTP
01042        = dyn_cast_or_null<TemplateTemplateParmDecl>(Name.getAsTemplateDecl())) {
01043     if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
01044       // If the corresponding template argument is NULL or non-existent, it's
01045       // because we are performing instantiation from explicitly-specified
01046       // template arguments in a function template, but there were some
01047       // arguments left unspecified.
01048       if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
01049                                             TTP->getPosition()))
01050         return Name;
01051       
01052       TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
01053       
01054       if (TTP->isParameterPack()) {
01055         assert(Arg.getKind() == TemplateArgument::Pack && 
01056                "Missing argument pack");
01057         
01058         if (getSema().ArgumentPackSubstitutionIndex == -1) {
01059           // We have the template argument pack to substitute, but we're not
01060           // actually expanding the enclosing pack expansion yet. So, just
01061           // keep the entire argument pack.
01062           return getSema().Context.getSubstTemplateTemplateParmPack(TTP, Arg);
01063         }
01064 
01065         Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
01066       }
01067       
01068       TemplateName Template = Arg.getAsTemplate();
01069       assert(!Template.isNull() && "Null template template argument");
01070 
01071       // We don't ever want to substitute for a qualified template name, since
01072       // the qualifier is handled separately. So, look through the qualified
01073       // template name to its underlying declaration.
01074       if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
01075         Template = TemplateName(QTN->getTemplateDecl());
01076 
01077       Template = getSema().Context.getSubstTemplateTemplateParm(TTP, Template);
01078       return Template;
01079     }
01080   }
01081   
01082   if (SubstTemplateTemplateParmPackStorage *SubstPack
01083       = Name.getAsSubstTemplateTemplateParmPack()) {
01084     if (getSema().ArgumentPackSubstitutionIndex == -1)
01085       return Name;
01086     
01087     TemplateArgument Arg = SubstPack->getArgumentPack();
01088     Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
01089     return Arg.getAsTemplate();
01090   }
01091   
01092   return inherited::TransformTemplateName(SS, Name, NameLoc, ObjectType, 
01093                                           FirstQualifierInScope);  
01094 }
01095 
01096 ExprResult 
01097 TemplateInstantiator::TransformPredefinedExpr(PredefinedExpr *E) {
01098   if (!E->isTypeDependent())
01099     return E;
01100 
01101   return getSema().BuildPredefinedExpr(E->getLocation(), E->getIdentType());
01102 }
01103 
01104 ExprResult
01105 TemplateInstantiator::TransformTemplateParmRefExpr(DeclRefExpr *E,
01106                                                NonTypeTemplateParmDecl *NTTP) {
01107   // If the corresponding template argument is NULL or non-existent, it's
01108   // because we are performing instantiation from explicitly-specified
01109   // template arguments in a function template, but there were some
01110   // arguments left unspecified.
01111   if (!TemplateArgs.hasTemplateArgument(NTTP->getDepth(),
01112                                         NTTP->getPosition()))
01113     return E;
01114 
01115   TemplateArgument Arg = TemplateArgs(NTTP->getDepth(), NTTP->getPosition());
01116   if (NTTP->isParameterPack()) {
01117     assert(Arg.getKind() == TemplateArgument::Pack && 
01118            "Missing argument pack");
01119     
01120     if (getSema().ArgumentPackSubstitutionIndex == -1) {
01121       // We have an argument pack, but we can't select a particular argument
01122       // out of it yet. Therefore, we'll build an expression to hold on to that
01123       // argument pack.
01124       QualType TargetType = SemaRef.SubstType(NTTP->getType(), TemplateArgs,
01125                                               E->getLocation(), 
01126                                               NTTP->getDeclName());
01127       if (TargetType.isNull())
01128         return ExprError();
01129       
01130       return new (SemaRef.Context) SubstNonTypeTemplateParmPackExpr(TargetType,
01131                                                                     NTTP, 
01132                                                               E->getLocation(),
01133                                                                     Arg);
01134     }
01135     
01136     Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
01137   }
01138 
01139   return transformNonTypeTemplateParmRef(NTTP, E->getLocation(), Arg);
01140 }
01141 
01142 const LoopHintAttr *
01143 TemplateInstantiator::TransformLoopHintAttr(const LoopHintAttr *LH) {
01144   Expr *TransformedExpr = getDerived().TransformExpr(LH->getValue()).get();
01145 
01146   if (TransformedExpr == LH->getValue())
01147     return LH;
01148 
01149   // Generate error if there is a problem with the value.
01150   if (getSema().CheckLoopHintExpr(TransformedExpr, LH->getLocation()))
01151     return LH;
01152 
01153   // Create new LoopHintValueAttr with integral expression in place of the
01154   // non-type template parameter.
01155   return LoopHintAttr::CreateImplicit(
01156       getSema().Context, LH->getSemanticSpelling(), LH->getOption(),
01157       LH->getState(), TransformedExpr, LH->getRange());
01158 }
01159 
01160 ExprResult TemplateInstantiator::transformNonTypeTemplateParmRef(
01161                                                  NonTypeTemplateParmDecl *parm,
01162                                                  SourceLocation loc,
01163                                                  TemplateArgument arg) {
01164   ExprResult result;
01165   QualType type;
01166 
01167   // The template argument itself might be an expression, in which
01168   // case we just return that expression.
01169   if (arg.getKind() == TemplateArgument::Expression) {
01170     Expr *argExpr = arg.getAsExpr();
01171     result = argExpr;
01172     type = argExpr->getType();
01173 
01174   } else if (arg.getKind() == TemplateArgument::Declaration ||
01175              arg.getKind() == TemplateArgument::NullPtr) {
01176     ValueDecl *VD;
01177     if (arg.getKind() == TemplateArgument::Declaration) {
01178       VD = cast<ValueDecl>(arg.getAsDecl());
01179 
01180       // Find the instantiation of the template argument.  This is
01181       // required for nested templates.
01182       VD = cast_or_null<ValueDecl>(
01183              getSema().FindInstantiatedDecl(loc, VD, TemplateArgs));
01184       if (!VD)
01185         return ExprError();
01186     } else {
01187       // Propagate NULL template argument.
01188       VD = nullptr;
01189     }
01190     
01191     // Derive the type we want the substituted decl to have.  This had
01192     // better be non-dependent, or these checks will have serious problems.
01193     if (parm->isExpandedParameterPack()) {
01194       type = parm->getExpansionType(SemaRef.ArgumentPackSubstitutionIndex);
01195     } else if (parm->isParameterPack() && 
01196                isa<PackExpansionType>(parm->getType())) {
01197       type = SemaRef.SubstType(
01198                         cast<PackExpansionType>(parm->getType())->getPattern(),
01199                                      TemplateArgs, loc, parm->getDeclName());
01200     } else {
01201       type = SemaRef.SubstType(parm->getType(), TemplateArgs, 
01202                                loc, parm->getDeclName());
01203     }
01204     assert(!type.isNull() && "type substitution failed for param type");
01205     assert(!type->isDependentType() && "param type still dependent");
01206     result = SemaRef.BuildExpressionFromDeclTemplateArgument(arg, type, loc);
01207 
01208     if (!result.isInvalid()) type = result.get()->getType();
01209   } else {
01210     result = SemaRef.BuildExpressionFromIntegralTemplateArgument(arg, loc);
01211 
01212     // Note that this type can be different from the type of 'result',
01213     // e.g. if it's an enum type.
01214     type = arg.getIntegralType();
01215   }
01216   if (result.isInvalid()) return ExprError();
01217 
01218   Expr *resultExpr = result.get();
01219   return new (SemaRef.Context) SubstNonTypeTemplateParmExpr(
01220       type, resultExpr->getValueKind(), loc, parm, resultExpr);
01221 }
01222                                                    
01223 ExprResult 
01224 TemplateInstantiator::TransformSubstNonTypeTemplateParmPackExpr(
01225                                           SubstNonTypeTemplateParmPackExpr *E) {
01226   if (getSema().ArgumentPackSubstitutionIndex == -1) {
01227     // We aren't expanding the parameter pack, so just return ourselves.
01228     return E;
01229   }
01230 
01231   TemplateArgument Arg = E->getArgumentPack();
01232   Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
01233   return transformNonTypeTemplateParmRef(E->getParameterPack(),
01234                                          E->getParameterPackLocation(),
01235                                          Arg);
01236 }
01237 
01238 ExprResult
01239 TemplateInstantiator::RebuildParmVarDeclRefExpr(ParmVarDecl *PD,
01240                                                 SourceLocation Loc) {
01241   DeclarationNameInfo NameInfo(PD->getDeclName(), Loc);
01242   return getSema().BuildDeclarationNameExpr(CXXScopeSpec(), NameInfo, PD);
01243 }
01244 
01245 ExprResult
01246 TemplateInstantiator::TransformFunctionParmPackExpr(FunctionParmPackExpr *E) {
01247   if (getSema().ArgumentPackSubstitutionIndex != -1) {
01248     // We can expand this parameter pack now.
01249     ParmVarDecl *D = E->getExpansion(getSema().ArgumentPackSubstitutionIndex);
01250     ValueDecl *VD = cast_or_null<ValueDecl>(TransformDecl(E->getExprLoc(), D));
01251     if (!VD)
01252       return ExprError();
01253     return RebuildParmVarDeclRefExpr(cast<ParmVarDecl>(VD), E->getExprLoc());
01254   }
01255 
01256   QualType T = TransformType(E->getType());
01257   if (T.isNull())
01258     return ExprError();
01259 
01260   // Transform each of the parameter expansions into the corresponding
01261   // parameters in the instantiation of the function decl.
01262   SmallVector<Decl *, 8> Parms;
01263   Parms.reserve(E->getNumExpansions());
01264   for (FunctionParmPackExpr::iterator I = E->begin(), End = E->end();
01265        I != End; ++I) {
01266     ParmVarDecl *D =
01267         cast_or_null<ParmVarDecl>(TransformDecl(E->getExprLoc(), *I));
01268     if (!D)
01269       return ExprError();
01270     Parms.push_back(D);
01271   }
01272 
01273   return FunctionParmPackExpr::Create(getSema().Context, T,
01274                                       E->getParameterPack(),
01275                                       E->getParameterPackLocation(), Parms);
01276 }
01277 
01278 ExprResult
01279 TemplateInstantiator::TransformFunctionParmPackRefExpr(DeclRefExpr *E,
01280                                                        ParmVarDecl *PD) {
01281   typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
01282   llvm::PointerUnion<Decl *, DeclArgumentPack *> *Found
01283     = getSema().CurrentInstantiationScope->findInstantiationOf(PD);
01284   assert(Found && "no instantiation for parameter pack");
01285 
01286   Decl *TransformedDecl;
01287   if (DeclArgumentPack *Pack = Found->dyn_cast<DeclArgumentPack *>()) {
01288     // If this is a reference to a function parameter pack which we can
01289     // substitute but can't yet expand, build a FunctionParmPackExpr for it.
01290     if (getSema().ArgumentPackSubstitutionIndex == -1) {
01291       QualType T = TransformType(E->getType());
01292       if (T.isNull())
01293         return ExprError();
01294       return FunctionParmPackExpr::Create(getSema().Context, T, PD,
01295                                           E->getExprLoc(), *Pack);
01296     }
01297 
01298     TransformedDecl = (*Pack)[getSema().ArgumentPackSubstitutionIndex];
01299   } else {
01300     TransformedDecl = Found->get<Decl*>();
01301   }
01302 
01303   // We have either an unexpanded pack or a specific expansion.
01304   return RebuildParmVarDeclRefExpr(cast<ParmVarDecl>(TransformedDecl),
01305                                    E->getExprLoc());
01306 }
01307 
01308 ExprResult
01309 TemplateInstantiator::TransformDeclRefExpr(DeclRefExpr *E) {
01310   NamedDecl *D = E->getDecl();
01311 
01312   // Handle references to non-type template parameters and non-type template
01313   // parameter packs.
01314   if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D)) {
01315     if (NTTP->getDepth() < TemplateArgs.getNumLevels())
01316       return TransformTemplateParmRefExpr(E, NTTP);
01317     
01318     // We have a non-type template parameter that isn't fully substituted;
01319     // FindInstantiatedDecl will find it in the local instantiation scope.
01320   }
01321 
01322   // Handle references to function parameter packs.
01323   if (ParmVarDecl *PD = dyn_cast<ParmVarDecl>(D))
01324     if (PD->isParameterPack())
01325       return TransformFunctionParmPackRefExpr(E, PD);
01326 
01327   return TreeTransform<TemplateInstantiator>::TransformDeclRefExpr(E);
01328 }
01329 
01330 ExprResult TemplateInstantiator::TransformCXXDefaultArgExpr(
01331     CXXDefaultArgExpr *E) {
01332   assert(!cast<FunctionDecl>(E->getParam()->getDeclContext())->
01333              getDescribedFunctionTemplate() &&
01334          "Default arg expressions are never formed in dependent cases.");
01335   return SemaRef.BuildCXXDefaultArgExpr(E->getUsedLocation(),
01336                            cast<FunctionDecl>(E->getParam()->getDeclContext()), 
01337                                         E->getParam());
01338 }
01339 
01340 template<typename Fn>
01341 QualType TemplateInstantiator::TransformFunctionProtoType(TypeLocBuilder &TLB,
01342                                  FunctionProtoTypeLoc TL,
01343                                  CXXRecordDecl *ThisContext,
01344                                  unsigned ThisTypeQuals,
01345                                  Fn TransformExceptionSpec) {
01346   // We need a local instantiation scope for this function prototype.
01347   LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
01348   return inherited::TransformFunctionProtoType(
01349       TLB, TL, ThisContext, ThisTypeQuals, TransformExceptionSpec);
01350 }
01351 
01352 ParmVarDecl *
01353 TemplateInstantiator::TransformFunctionTypeParam(ParmVarDecl *OldParm,
01354                                                  int indexAdjustment,
01355                                                Optional<unsigned> NumExpansions,
01356                                                  bool ExpectParameterPack) {
01357   return SemaRef.SubstParmVarDecl(OldParm, TemplateArgs, indexAdjustment,
01358                                   NumExpansions, ExpectParameterPack);
01359 }
01360 
01361 QualType
01362 TemplateInstantiator::TransformTemplateTypeParmType(TypeLocBuilder &TLB,
01363                                                 TemplateTypeParmTypeLoc TL) {
01364   const TemplateTypeParmType *T = TL.getTypePtr();
01365   if (T->getDepth() < TemplateArgs.getNumLevels()) {
01366     // Replace the template type parameter with its corresponding
01367     // template argument.
01368 
01369     // If the corresponding template argument is NULL or doesn't exist, it's
01370     // because we are performing instantiation from explicitly-specified
01371     // template arguments in a function template class, but there were some
01372     // arguments left unspecified.
01373     if (!TemplateArgs.hasTemplateArgument(T->getDepth(), T->getIndex())) {
01374       TemplateTypeParmTypeLoc NewTL
01375         = TLB.push<TemplateTypeParmTypeLoc>(TL.getType());
01376       NewTL.setNameLoc(TL.getNameLoc());
01377       return TL.getType();
01378     }
01379 
01380     TemplateArgument Arg = TemplateArgs(T->getDepth(), T->getIndex());
01381     
01382     if (T->isParameterPack()) {
01383       assert(Arg.getKind() == TemplateArgument::Pack && 
01384              "Missing argument pack");
01385       
01386       if (getSema().ArgumentPackSubstitutionIndex == -1) {
01387         // We have the template argument pack, but we're not expanding the
01388         // enclosing pack expansion yet. Just save the template argument
01389         // pack for later substitution.
01390         QualType Result
01391           = getSema().Context.getSubstTemplateTypeParmPackType(T, Arg);
01392         SubstTemplateTypeParmPackTypeLoc NewTL
01393           = TLB.push<SubstTemplateTypeParmPackTypeLoc>(Result);
01394         NewTL.setNameLoc(TL.getNameLoc());
01395         return Result;
01396       }
01397       
01398       Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
01399     }
01400     
01401     assert(Arg.getKind() == TemplateArgument::Type &&
01402            "Template argument kind mismatch");
01403 
01404     QualType Replacement = Arg.getAsType();
01405 
01406     // TODO: only do this uniquing once, at the start of instantiation.
01407     QualType Result
01408       = getSema().Context.getSubstTemplateTypeParmType(T, Replacement);
01409     SubstTemplateTypeParmTypeLoc NewTL
01410       = TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
01411     NewTL.setNameLoc(TL.getNameLoc());
01412     return Result;
01413   }
01414 
01415   // The template type parameter comes from an inner template (e.g.,
01416   // the template parameter list of a member template inside the
01417   // template we are instantiating). Create a new template type
01418   // parameter with the template "level" reduced by one.
01419   TemplateTypeParmDecl *NewTTPDecl = nullptr;
01420   if (TemplateTypeParmDecl *OldTTPDecl = T->getDecl())
01421     NewTTPDecl = cast_or_null<TemplateTypeParmDecl>(
01422                                   TransformDecl(TL.getNameLoc(), OldTTPDecl));
01423 
01424   QualType Result
01425     = getSema().Context.getTemplateTypeParmType(T->getDepth()
01426                                                  - TemplateArgs.getNumLevels(),
01427                                                 T->getIndex(),
01428                                                 T->isParameterPack(),
01429                                                 NewTTPDecl);
01430   TemplateTypeParmTypeLoc NewTL = TLB.push<TemplateTypeParmTypeLoc>(Result);
01431   NewTL.setNameLoc(TL.getNameLoc());
01432   return Result;
01433 }
01434 
01435 QualType 
01436 TemplateInstantiator::TransformSubstTemplateTypeParmPackType(
01437                                                             TypeLocBuilder &TLB,
01438                                          SubstTemplateTypeParmPackTypeLoc TL) {
01439   if (getSema().ArgumentPackSubstitutionIndex == -1) {
01440     // We aren't expanding the parameter pack, so just return ourselves.
01441     SubstTemplateTypeParmPackTypeLoc NewTL
01442       = TLB.push<SubstTemplateTypeParmPackTypeLoc>(TL.getType());
01443     NewTL.setNameLoc(TL.getNameLoc());
01444     return TL.getType();
01445   }
01446 
01447   TemplateArgument Arg = TL.getTypePtr()->getArgumentPack();
01448   Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
01449   QualType Result = Arg.getAsType();
01450 
01451   Result = getSema().Context.getSubstTemplateTypeParmType(
01452                                       TL.getTypePtr()->getReplacedParameter(),
01453                                                           Result);
01454   SubstTemplateTypeParmTypeLoc NewTL
01455     = TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
01456   NewTL.setNameLoc(TL.getNameLoc());
01457   return Result;
01458 }
01459 
01460 /// \brief Perform substitution on the type T with a given set of template
01461 /// arguments.
01462 ///
01463 /// This routine substitutes the given template arguments into the
01464 /// type T and produces the instantiated type.
01465 ///
01466 /// \param T the type into which the template arguments will be
01467 /// substituted. If this type is not dependent, it will be returned
01468 /// immediately.
01469 ///
01470 /// \param Args the template arguments that will be
01471 /// substituted for the top-level template parameters within T.
01472 ///
01473 /// \param Loc the location in the source code where this substitution
01474 /// is being performed. It will typically be the location of the
01475 /// declarator (if we're instantiating the type of some declaration)
01476 /// or the location of the type in the source code (if, e.g., we're
01477 /// instantiating the type of a cast expression).
01478 ///
01479 /// \param Entity the name of the entity associated with a declaration
01480 /// being instantiated (if any). May be empty to indicate that there
01481 /// is no such entity (if, e.g., this is a type that occurs as part of
01482 /// a cast expression) or that the entity has no name (e.g., an
01483 /// unnamed function parameter).
01484 ///
01485 /// \returns If the instantiation succeeds, the instantiated
01486 /// type. Otherwise, produces diagnostics and returns a NULL type.
01487 TypeSourceInfo *Sema::SubstType(TypeSourceInfo *T,
01488                                 const MultiLevelTemplateArgumentList &Args,
01489                                 SourceLocation Loc,
01490                                 DeclarationName Entity) {
01491   assert(!ActiveTemplateInstantiations.empty() &&
01492          "Cannot perform an instantiation without some context on the "
01493          "instantiation stack");
01494   
01495   if (!T->getType()->isInstantiationDependentType() && 
01496       !T->getType()->isVariablyModifiedType())
01497     return T;
01498 
01499   TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
01500   return Instantiator.TransformType(T);
01501 }
01502 
01503 TypeSourceInfo *Sema::SubstType(TypeLoc TL,
01504                                 const MultiLevelTemplateArgumentList &Args,
01505                                 SourceLocation Loc,
01506                                 DeclarationName Entity) {
01507   assert(!ActiveTemplateInstantiations.empty() &&
01508          "Cannot perform an instantiation without some context on the "
01509          "instantiation stack");
01510   
01511   if (TL.getType().isNull())
01512     return nullptr;
01513 
01514   if (!TL.getType()->isInstantiationDependentType() && 
01515       !TL.getType()->isVariablyModifiedType()) {
01516     // FIXME: Make a copy of the TypeLoc data here, so that we can
01517     // return a new TypeSourceInfo. Inefficient!
01518     TypeLocBuilder TLB;
01519     TLB.pushFullCopy(TL);
01520     return TLB.getTypeSourceInfo(Context, TL.getType());
01521   }
01522 
01523   TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
01524   TypeLocBuilder TLB;
01525   TLB.reserve(TL.getFullDataSize());
01526   QualType Result = Instantiator.TransformType(TLB, TL);
01527   if (Result.isNull())
01528     return nullptr;
01529 
01530   return TLB.getTypeSourceInfo(Context, Result);
01531 }
01532 
01533 /// Deprecated form of the above.
01534 QualType Sema::SubstType(QualType T,
01535                          const MultiLevelTemplateArgumentList &TemplateArgs,
01536                          SourceLocation Loc, DeclarationName Entity) {
01537   assert(!ActiveTemplateInstantiations.empty() &&
01538          "Cannot perform an instantiation without some context on the "
01539          "instantiation stack");
01540 
01541   // If T is not a dependent type or a variably-modified type, there
01542   // is nothing to do.
01543   if (!T->isInstantiationDependentType() && !T->isVariablyModifiedType())
01544     return T;
01545 
01546   TemplateInstantiator Instantiator(*this, TemplateArgs, Loc, Entity);
01547   return Instantiator.TransformType(T);
01548 }
01549 
01550 static bool NeedsInstantiationAsFunctionType(TypeSourceInfo *T) {
01551   if (T->getType()->isInstantiationDependentType() || 
01552       T->getType()->isVariablyModifiedType())
01553     return true;
01554 
01555   TypeLoc TL = T->getTypeLoc().IgnoreParens();
01556   if (!TL.getAs<FunctionProtoTypeLoc>())
01557     return false;
01558 
01559   FunctionProtoTypeLoc FP = TL.castAs<FunctionProtoTypeLoc>();
01560   for (unsigned I = 0, E = FP.getNumParams(); I != E; ++I) {
01561     ParmVarDecl *P = FP.getParam(I);
01562 
01563     // This must be synthesized from a typedef.
01564     if (!P) continue;
01565 
01566     // The parameter's type as written might be dependent even if the
01567     // decayed type was not dependent.
01568     if (TypeSourceInfo *TSInfo = P->getTypeSourceInfo())
01569       if (TSInfo->getType()->isInstantiationDependentType())
01570         return true;
01571 
01572     // TODO: currently we always rebuild expressions.  When we
01573     // properly get lazier about this, we should use the same
01574     // logic to avoid rebuilding prototypes here.
01575     if (P->hasDefaultArg())
01576       return true;
01577   }
01578 
01579   return false;
01580 }
01581 
01582 /// A form of SubstType intended specifically for instantiating the
01583 /// type of a FunctionDecl.  Its purpose is solely to force the
01584 /// instantiation of default-argument expressions and to avoid
01585 /// instantiating an exception-specification.
01586 TypeSourceInfo *Sema::SubstFunctionDeclType(TypeSourceInfo *T,
01587                                 const MultiLevelTemplateArgumentList &Args,
01588                                 SourceLocation Loc,
01589                                 DeclarationName Entity,
01590                                 CXXRecordDecl *ThisContext,
01591                                 unsigned ThisTypeQuals) {
01592   assert(!ActiveTemplateInstantiations.empty() &&
01593          "Cannot perform an instantiation without some context on the "
01594          "instantiation stack");
01595   
01596   if (!NeedsInstantiationAsFunctionType(T))
01597     return T;
01598 
01599   TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
01600 
01601   TypeLocBuilder TLB;
01602 
01603   TypeLoc TL = T->getTypeLoc();
01604   TLB.reserve(TL.getFullDataSize());
01605 
01606   QualType Result;
01607 
01608   if (FunctionProtoTypeLoc Proto =
01609           TL.IgnoreParens().getAs<FunctionProtoTypeLoc>()) {
01610     // Instantiate the type, other than its exception specification. The
01611     // exception specification is instantiated in InitFunctionInstantiation
01612     // once we've built the FunctionDecl.
01613     // FIXME: Set the exception specification to EST_Uninstantiated here,
01614     // instead of rebuilding the function type again later.
01615     Result = Instantiator.TransformFunctionProtoType(
01616         TLB, Proto, ThisContext, ThisTypeQuals,
01617         [](FunctionProtoType::ExceptionSpecInfo &ESI,
01618            bool &Changed) { return false; });
01619   } else {
01620     Result = Instantiator.TransformType(TLB, TL);
01621   }
01622   if (Result.isNull())
01623     return nullptr;
01624 
01625   return TLB.getTypeSourceInfo(Context, Result);
01626 }
01627 
01628 void Sema::SubstExceptionSpec(FunctionDecl *New, const FunctionProtoType *Proto,
01629                               const MultiLevelTemplateArgumentList &Args) {
01630   FunctionProtoType::ExceptionSpecInfo ESI =
01631       Proto->getExtProtoInfo().ExceptionSpec;
01632   assert(ESI.Type != EST_Uninstantiated);
01633 
01634   TemplateInstantiator Instantiator(*this, Args, New->getLocation(),
01635                                     New->getDeclName());
01636 
01637   SmallVector<QualType, 4> ExceptionStorage;
01638   bool Changed = false;
01639   if (Instantiator.TransformExceptionSpec(
01640           New->getTypeSourceInfo()->getTypeLoc().getLocEnd(), ESI,
01641           ExceptionStorage, Changed))
01642     // On error, recover by dropping the exception specification.
01643     ESI.Type = EST_None;
01644 
01645   UpdateExceptionSpec(New, ESI);
01646 }
01647 
01648 ParmVarDecl *Sema::SubstParmVarDecl(ParmVarDecl *OldParm, 
01649                             const MultiLevelTemplateArgumentList &TemplateArgs,
01650                                     int indexAdjustment,
01651                                     Optional<unsigned> NumExpansions,
01652                                     bool ExpectParameterPack) {
01653   TypeSourceInfo *OldDI = OldParm->getTypeSourceInfo();
01654   TypeSourceInfo *NewDI = nullptr;
01655 
01656   TypeLoc OldTL = OldDI->getTypeLoc();
01657   if (PackExpansionTypeLoc ExpansionTL = OldTL.getAs<PackExpansionTypeLoc>()) {
01658 
01659     // We have a function parameter pack. Substitute into the pattern of the 
01660     // expansion.
01661     NewDI = SubstType(ExpansionTL.getPatternLoc(), TemplateArgs, 
01662                       OldParm->getLocation(), OldParm->getDeclName());
01663     if (!NewDI)
01664       return nullptr;
01665 
01666     if (NewDI->getType()->containsUnexpandedParameterPack()) {
01667       // We still have unexpanded parameter packs, which means that
01668       // our function parameter is still a function parameter pack.
01669       // Therefore, make its type a pack expansion type.
01670       NewDI = CheckPackExpansion(NewDI, ExpansionTL.getEllipsisLoc(),
01671                                  NumExpansions);
01672     } else if (ExpectParameterPack) {
01673       // We expected to get a parameter pack but didn't (because the type
01674       // itself is not a pack expansion type), so complain. This can occur when
01675       // the substitution goes through an alias template that "loses" the
01676       // pack expansion.
01677       Diag(OldParm->getLocation(), 
01678            diag::err_function_parameter_pack_without_parameter_packs)
01679         << NewDI->getType();
01680       return nullptr;
01681     } 
01682   } else {
01683     NewDI = SubstType(OldDI, TemplateArgs, OldParm->getLocation(), 
01684                       OldParm->getDeclName());
01685   }
01686   
01687   if (!NewDI)
01688     return nullptr;
01689 
01690   if (NewDI->getType()->isVoidType()) {
01691     Diag(OldParm->getLocation(), diag::err_param_with_void_type);
01692     return nullptr;
01693   }
01694 
01695   ParmVarDecl *NewParm = CheckParameter(Context.getTranslationUnitDecl(),
01696                                         OldParm->getInnerLocStart(),
01697                                         OldParm->getLocation(),
01698                                         OldParm->getIdentifier(),
01699                                         NewDI->getType(), NewDI,
01700                                         OldParm->getStorageClass());
01701   if (!NewParm)
01702     return nullptr;
01703 
01704   // Mark the (new) default argument as uninstantiated (if any).
01705   if (OldParm->hasUninstantiatedDefaultArg()) {
01706     Expr *Arg = OldParm->getUninstantiatedDefaultArg();
01707     NewParm->setUninstantiatedDefaultArg(Arg);
01708   } else if (OldParm->hasUnparsedDefaultArg()) {
01709     NewParm->setUnparsedDefaultArg();
01710     UnparsedDefaultArgInstantiations[OldParm].push_back(NewParm);
01711   } else if (Expr *Arg = OldParm->getDefaultArg())
01712     // FIXME: if we non-lazily instantiated non-dependent default args for
01713     // non-dependent parameter types we could remove a bunch of duplicate
01714     // conversion warnings for such arguments.
01715     NewParm->setUninstantiatedDefaultArg(Arg);
01716 
01717   NewParm->setHasInheritedDefaultArg(OldParm->hasInheritedDefaultArg());
01718   
01719   if (OldParm->isParameterPack() && !NewParm->isParameterPack()) {
01720     // Add the new parameter to the instantiated parameter pack.
01721     CurrentInstantiationScope->InstantiatedLocalPackArg(OldParm, NewParm);
01722   } else {
01723     // Introduce an Old -> New mapping
01724     CurrentInstantiationScope->InstantiatedLocal(OldParm, NewParm);  
01725   }
01726   
01727   // FIXME: OldParm may come from a FunctionProtoType, in which case CurContext
01728   // can be anything, is this right ?
01729   NewParm->setDeclContext(CurContext);
01730 
01731   NewParm->setScopeInfo(OldParm->getFunctionScopeDepth(),
01732                         OldParm->getFunctionScopeIndex() + indexAdjustment);
01733 
01734   InstantiateAttrs(TemplateArgs, OldParm, NewParm);
01735 
01736   return NewParm;  
01737 }
01738 
01739 /// \brief Substitute the given template arguments into the given set of
01740 /// parameters, producing the set of parameter types that would be generated
01741 /// from such a substitution.
01742 bool Sema::SubstParmTypes(SourceLocation Loc, 
01743                           ParmVarDecl **Params, unsigned NumParams,
01744                           const MultiLevelTemplateArgumentList &TemplateArgs,
01745                           SmallVectorImpl<QualType> &ParamTypes,
01746                           SmallVectorImpl<ParmVarDecl *> *OutParams) {
01747   assert(!ActiveTemplateInstantiations.empty() &&
01748          "Cannot perform an instantiation without some context on the "
01749          "instantiation stack");
01750   
01751   TemplateInstantiator Instantiator(*this, TemplateArgs, Loc, 
01752                                     DeclarationName());
01753   return Instantiator.TransformFunctionTypeParams(Loc, Params, NumParams,
01754                                                   nullptr, ParamTypes,
01755                                                   OutParams);
01756 }
01757 
01758 /// \brief Perform substitution on the base class specifiers of the
01759 /// given class template specialization.
01760 ///
01761 /// Produces a diagnostic and returns true on error, returns false and
01762 /// attaches the instantiated base classes to the class template
01763 /// specialization if successful.
01764 bool
01765 Sema::SubstBaseSpecifiers(CXXRecordDecl *Instantiation,
01766                           CXXRecordDecl *Pattern,
01767                           const MultiLevelTemplateArgumentList &TemplateArgs) {
01768   bool Invalid = false;
01769   SmallVector<CXXBaseSpecifier*, 4> InstantiatedBases;
01770   for (const auto Base : Pattern->bases()) {
01771     if (!Base.getType()->isDependentType()) {
01772       if (const CXXRecordDecl *RD = Base.getType()->getAsCXXRecordDecl()) {
01773         if (RD->isInvalidDecl())
01774           Instantiation->setInvalidDecl();
01775       }
01776       InstantiatedBases.push_back(new (Context) CXXBaseSpecifier(Base));
01777       continue;
01778     }
01779 
01780     SourceLocation EllipsisLoc;
01781     TypeSourceInfo *BaseTypeLoc;
01782     if (Base.isPackExpansion()) {
01783       // This is a pack expansion. See whether we should expand it now, or
01784       // wait until later.
01785       SmallVector<UnexpandedParameterPack, 2> Unexpanded;
01786       collectUnexpandedParameterPacks(Base.getTypeSourceInfo()->getTypeLoc(),
01787                                       Unexpanded);
01788       bool ShouldExpand = false;
01789       bool RetainExpansion = false;
01790       Optional<unsigned> NumExpansions;
01791       if (CheckParameterPacksForExpansion(Base.getEllipsisLoc(), 
01792                                           Base.getSourceRange(),
01793                                           Unexpanded,
01794                                           TemplateArgs, ShouldExpand, 
01795                                           RetainExpansion,
01796                                           NumExpansions)) {
01797         Invalid = true;
01798         continue;
01799       }
01800       
01801       // If we should expand this pack expansion now, do so.
01802       if (ShouldExpand) {
01803         for (unsigned I = 0; I != *NumExpansions; ++I) {
01804             Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
01805           
01806           TypeSourceInfo *BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
01807                                                   TemplateArgs,
01808                                               Base.getSourceRange().getBegin(),
01809                                                   DeclarationName());
01810           if (!BaseTypeLoc) {
01811             Invalid = true;
01812             continue;
01813           }
01814           
01815           if (CXXBaseSpecifier *InstantiatedBase
01816                 = CheckBaseSpecifier(Instantiation,
01817                                      Base.getSourceRange(),
01818                                      Base.isVirtual(),
01819                                      Base.getAccessSpecifierAsWritten(),
01820                                      BaseTypeLoc,
01821                                      SourceLocation()))
01822             InstantiatedBases.push_back(InstantiatedBase);
01823           else
01824             Invalid = true;
01825         }
01826       
01827         continue;
01828       }
01829       
01830       // The resulting base specifier will (still) be a pack expansion.
01831       EllipsisLoc = Base.getEllipsisLoc();
01832       Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, -1);
01833       BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
01834                               TemplateArgs,
01835                               Base.getSourceRange().getBegin(),
01836                               DeclarationName());
01837     } else {
01838       BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
01839                               TemplateArgs,
01840                               Base.getSourceRange().getBegin(),
01841                               DeclarationName());
01842     }
01843     
01844     if (!BaseTypeLoc) {
01845       Invalid = true;
01846       continue;
01847     }
01848 
01849     if (CXXBaseSpecifier *InstantiatedBase
01850           = CheckBaseSpecifier(Instantiation,
01851                                Base.getSourceRange(),
01852                                Base.isVirtual(),
01853                                Base.getAccessSpecifierAsWritten(),
01854                                BaseTypeLoc,
01855                                EllipsisLoc))
01856       InstantiatedBases.push_back(InstantiatedBase);
01857     else
01858       Invalid = true;
01859   }
01860 
01861   if (!Invalid &&
01862       AttachBaseSpecifiers(Instantiation, InstantiatedBases.data(),
01863                            InstantiatedBases.size()))
01864     Invalid = true;
01865 
01866   return Invalid;
01867 }
01868 
01869 // Defined via #include from SemaTemplateInstantiateDecl.cpp
01870 namespace clang {
01871   namespace sema {
01872     Attr *instantiateTemplateAttribute(const Attr *At, ASTContext &C, Sema &S,
01873                             const MultiLevelTemplateArgumentList &TemplateArgs);
01874   }
01875 }
01876 
01877 /// Determine whether we would be unable to instantiate this template (because
01878 /// it either has no definition, or is in the process of being instantiated).
01879 static bool DiagnoseUninstantiableTemplate(Sema &S,
01880                                            SourceLocation PointOfInstantiation,
01881                                            TagDecl *Instantiation,
01882                                            bool InstantiatedFromMember,
01883                                            TagDecl *Pattern,
01884                                            TagDecl *PatternDef,
01885                                            TemplateSpecializationKind TSK,
01886                                            bool Complain = true) {
01887   if (PatternDef && !PatternDef->isBeingDefined())
01888     return false;
01889 
01890   if (!Complain || (PatternDef && PatternDef->isInvalidDecl())) {
01891     // Say nothing
01892   } else if (PatternDef) {
01893     assert(PatternDef->isBeingDefined());
01894     S.Diag(PointOfInstantiation,
01895            diag::err_template_instantiate_within_definition)
01896       << (TSK != TSK_ImplicitInstantiation)
01897       << S.Context.getTypeDeclType(Instantiation);
01898     // Not much point in noting the template declaration here, since
01899     // we're lexically inside it.
01900     Instantiation->setInvalidDecl();
01901   } else if (InstantiatedFromMember) {
01902     S.Diag(PointOfInstantiation,
01903            diag::err_implicit_instantiate_member_undefined)
01904       << S.Context.getTypeDeclType(Instantiation);
01905     S.Diag(Pattern->getLocation(), diag::note_member_declared_at);
01906   } else {
01907     S.Diag(PointOfInstantiation, diag::err_template_instantiate_undefined)
01908       << (TSK != TSK_ImplicitInstantiation)
01909       << S.Context.getTypeDeclType(Instantiation);
01910     S.Diag(Pattern->getLocation(), diag::note_template_decl_here);
01911   }
01912 
01913   // In general, Instantiation isn't marked invalid to get more than one
01914   // error for multiple undefined instantiations. But the code that does
01915   // explicit declaration -> explicit definition conversion can't handle
01916   // invalid declarations, so mark as invalid in that case.
01917   if (TSK == TSK_ExplicitInstantiationDeclaration)
01918     Instantiation->setInvalidDecl();
01919   return true;
01920 }
01921 
01922 /// \brief Instantiate the definition of a class from a given pattern.
01923 ///
01924 /// \param PointOfInstantiation The point of instantiation within the
01925 /// source code.
01926 ///
01927 /// \param Instantiation is the declaration whose definition is being
01928 /// instantiated. This will be either a class template specialization
01929 /// or a member class of a class template specialization.
01930 ///
01931 /// \param Pattern is the pattern from which the instantiation
01932 /// occurs. This will be either the declaration of a class template or
01933 /// the declaration of a member class of a class template.
01934 ///
01935 /// \param TemplateArgs The template arguments to be substituted into
01936 /// the pattern.
01937 ///
01938 /// \param TSK the kind of implicit or explicit instantiation to perform.
01939 ///
01940 /// \param Complain whether to complain if the class cannot be instantiated due
01941 /// to the lack of a definition.
01942 ///
01943 /// \returns true if an error occurred, false otherwise.
01944 bool
01945 Sema::InstantiateClass(SourceLocation PointOfInstantiation,
01946                        CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
01947                        const MultiLevelTemplateArgumentList &TemplateArgs,
01948                        TemplateSpecializationKind TSK,
01949                        bool Complain) {
01950   CXXRecordDecl *PatternDef
01951     = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
01952   if (DiagnoseUninstantiableTemplate(*this, PointOfInstantiation, Instantiation,
01953                                 Instantiation->getInstantiatedFromMemberClass(),
01954                                      Pattern, PatternDef, TSK, Complain))
01955     return true;
01956   Pattern = PatternDef;
01957 
01958   // \brief Record the point of instantiation.
01959   if (MemberSpecializationInfo *MSInfo 
01960         = Instantiation->getMemberSpecializationInfo()) {
01961     MSInfo->setTemplateSpecializationKind(TSK);
01962     MSInfo->setPointOfInstantiation(PointOfInstantiation);
01963   } else if (ClassTemplateSpecializationDecl *Spec 
01964         = dyn_cast<ClassTemplateSpecializationDecl>(Instantiation)) {
01965     Spec->setTemplateSpecializationKind(TSK);
01966     Spec->setPointOfInstantiation(PointOfInstantiation);
01967   }
01968 
01969   InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
01970   if (Inst.isInvalid())
01971     return true;
01972 
01973   // Enter the scope of this instantiation. We don't use
01974   // PushDeclContext because we don't have a scope.
01975   ContextRAII SavedContext(*this, Instantiation);
01976   EnterExpressionEvaluationContext EvalContext(*this, 
01977                                                Sema::PotentiallyEvaluated);
01978 
01979   // If this is an instantiation of a local class, merge this local
01980   // instantiation scope with the enclosing scope. Otherwise, every
01981   // instantiation of a class has its own local instantiation scope.
01982   bool MergeWithParentScope = !Instantiation->isDefinedOutsideFunctionOrMethod();
01983   LocalInstantiationScope Scope(*this, MergeWithParentScope);
01984 
01985   // Pull attributes from the pattern onto the instantiation.
01986   InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
01987 
01988   // Start the definition of this instantiation.
01989   Instantiation->startDefinition();
01990 
01991   // The instantiation is visible here, even if it was first declared in an
01992   // unimported module.
01993   Instantiation->setHidden(false);
01994 
01995   // FIXME: This loses the as-written tag kind for an explicit instantiation.
01996   Instantiation->setTagKind(Pattern->getTagKind());
01997 
01998   // Do substitution on the base class specifiers.
01999   if (SubstBaseSpecifiers(Instantiation, Pattern, TemplateArgs))
02000     Instantiation->setInvalidDecl();
02001 
02002   TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
02003   SmallVector<Decl*, 4> Fields;
02004   // Delay instantiation of late parsed attributes.
02005   LateInstantiatedAttrVec LateAttrs;
02006   Instantiator.enableLateAttributeInstantiation(&LateAttrs);
02007 
02008   for (auto *Member : Pattern->decls()) {
02009     // Don't instantiate members not belonging in this semantic context.
02010     // e.g. for:
02011     // @code
02012     //    template <int i> class A {
02013     //      class B *g;
02014     //    };
02015     // @endcode
02016     // 'class B' has the template as lexical context but semantically it is
02017     // introduced in namespace scope.
02018     if (Member->getDeclContext() != Pattern)
02019       continue;
02020 
02021     if (Member->isInvalidDecl()) {
02022       Instantiation->setInvalidDecl();
02023       continue;
02024     }
02025 
02026     Decl *NewMember = Instantiator.Visit(Member);
02027     if (NewMember) {
02028       if (FieldDecl *Field = dyn_cast<FieldDecl>(NewMember)) {
02029         Fields.push_back(Field);
02030       } else if (EnumDecl *Enum = dyn_cast<EnumDecl>(NewMember)) {
02031         // C++11 [temp.inst]p1: The implicit instantiation of a class template
02032         // specialization causes the implicit instantiation of the definitions
02033         // of unscoped member enumerations.
02034         // Record a point of instantiation for this implicit instantiation.
02035         if (TSK == TSK_ImplicitInstantiation && !Enum->isScoped() &&
02036             Enum->isCompleteDefinition()) {
02037           MemberSpecializationInfo *MSInfo =Enum->getMemberSpecializationInfo();
02038           assert(MSInfo && "no spec info for member enum specialization");
02039           MSInfo->setTemplateSpecializationKind(TSK_ImplicitInstantiation);
02040           MSInfo->setPointOfInstantiation(PointOfInstantiation);
02041         }
02042       } else if (StaticAssertDecl *SA = dyn_cast<StaticAssertDecl>(NewMember)) {
02043         if (SA->isFailed()) {
02044           // A static_assert failed. Bail out; instantiating this
02045           // class is probably not meaningful.
02046           Instantiation->setInvalidDecl();
02047           break;
02048         }
02049       }
02050 
02051       if (NewMember->isInvalidDecl())
02052         Instantiation->setInvalidDecl();
02053     } else {
02054       // FIXME: Eventually, a NULL return will mean that one of the
02055       // instantiations was a semantic disaster, and we'll want to mark the
02056       // declaration invalid.
02057       // For now, we expect to skip some members that we can't yet handle.
02058     }
02059   }
02060 
02061   // Finish checking fields.
02062   ActOnFields(nullptr, Instantiation->getLocation(), Instantiation, Fields,
02063               SourceLocation(), SourceLocation(), nullptr);
02064   CheckCompletedCXXClass(Instantiation);
02065 
02066   // Instantiate late parsed attributes, and attach them to their decls.
02067   // See Sema::InstantiateAttrs
02068   for (LateInstantiatedAttrVec::iterator I = LateAttrs.begin(),
02069        E = LateAttrs.end(); I != E; ++I) {
02070     assert(CurrentInstantiationScope == Instantiator.getStartingScope());
02071     CurrentInstantiationScope = I->Scope;
02072 
02073     // Allow 'this' within late-parsed attributes.
02074     NamedDecl *ND = dyn_cast<NamedDecl>(I->NewDecl);
02075     CXXRecordDecl *ThisContext =
02076         dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext());
02077     CXXThisScopeRAII ThisScope(*this, ThisContext, /*TypeQuals*/0,
02078                                ND && ND->isCXXInstanceMember());
02079 
02080     Attr *NewAttr =
02081       instantiateTemplateAttribute(I->TmplAttr, Context, *this, TemplateArgs);
02082     I->NewDecl->addAttr(NewAttr);
02083     LocalInstantiationScope::deleteScopes(I->Scope,
02084                                           Instantiator.getStartingScope());
02085   }
02086   Instantiator.disableLateAttributeInstantiation();
02087   LateAttrs.clear();
02088 
02089   ActOnFinishDelayedMemberInitializers(Instantiation);
02090 
02091   // FIXME: We should do something similar for explicit instantiations so they
02092   // end up in the right module.
02093   if (TSK == TSK_ImplicitInstantiation) {
02094     Instantiation->setLocation(Pattern->getLocation());
02095     Instantiation->setLocStart(Pattern->getInnerLocStart());
02096     Instantiation->setRBraceLoc(Pattern->getRBraceLoc());
02097   }
02098 
02099   if (!Instantiation->isInvalidDecl()) {
02100     // Perform any dependent diagnostics from the pattern.
02101     PerformDependentDiagnostics(Pattern, TemplateArgs);
02102 
02103     // Instantiate any out-of-line class template partial
02104     // specializations now.
02105     for (TemplateDeclInstantiator::delayed_partial_spec_iterator
02106               P = Instantiator.delayed_partial_spec_begin(),
02107            PEnd = Instantiator.delayed_partial_spec_end();
02108          P != PEnd; ++P) {
02109       if (!Instantiator.InstantiateClassTemplatePartialSpecialization(
02110               P->first, P->second)) {
02111         Instantiation->setInvalidDecl();
02112         break;
02113       }
02114     }
02115 
02116     // Instantiate any out-of-line variable template partial
02117     // specializations now.
02118     for (TemplateDeclInstantiator::delayed_var_partial_spec_iterator
02119               P = Instantiator.delayed_var_partial_spec_begin(),
02120            PEnd = Instantiator.delayed_var_partial_spec_end();
02121          P != PEnd; ++P) {
02122       if (!Instantiator.InstantiateVarTemplatePartialSpecialization(
02123               P->first, P->second)) {
02124         Instantiation->setInvalidDecl();
02125         break;
02126       }
02127     }
02128   }
02129 
02130   // Exit the scope of this instantiation.
02131   SavedContext.pop();
02132 
02133   if (!Instantiation->isInvalidDecl()) {
02134     Consumer.HandleTagDeclDefinition(Instantiation);
02135 
02136     // Always emit the vtable for an explicit instantiation definition
02137     // of a polymorphic class template specialization.
02138     if (TSK == TSK_ExplicitInstantiationDefinition)
02139       MarkVTableUsed(PointOfInstantiation, Instantiation, true);
02140   }
02141 
02142   return Instantiation->isInvalidDecl();
02143 }
02144 
02145 /// \brief Instantiate the definition of an enum from a given pattern.
02146 ///
02147 /// \param PointOfInstantiation The point of instantiation within the
02148 ///        source code.
02149 /// \param Instantiation is the declaration whose definition is being
02150 ///        instantiated. This will be a member enumeration of a class
02151 ///        temploid specialization, or a local enumeration within a
02152 ///        function temploid specialization.
02153 /// \param Pattern The templated declaration from which the instantiation
02154 ///        occurs.
02155 /// \param TemplateArgs The template arguments to be substituted into
02156 ///        the pattern.
02157 /// \param TSK The kind of implicit or explicit instantiation to perform.
02158 ///
02159 /// \return \c true if an error occurred, \c false otherwise.
02160 bool Sema::InstantiateEnum(SourceLocation PointOfInstantiation,
02161                            EnumDecl *Instantiation, EnumDecl *Pattern,
02162                            const MultiLevelTemplateArgumentList &TemplateArgs,
02163                            TemplateSpecializationKind TSK) {
02164   EnumDecl *PatternDef = Pattern->getDefinition();
02165   if (DiagnoseUninstantiableTemplate(*this, PointOfInstantiation, Instantiation,
02166                                  Instantiation->getInstantiatedFromMemberEnum(),
02167                                      Pattern, PatternDef, TSK,/*Complain*/true))
02168     return true;
02169   Pattern = PatternDef;
02170 
02171   // Record the point of instantiation.
02172   if (MemberSpecializationInfo *MSInfo
02173         = Instantiation->getMemberSpecializationInfo()) {
02174     MSInfo->setTemplateSpecializationKind(TSK);
02175     MSInfo->setPointOfInstantiation(PointOfInstantiation);
02176   }
02177 
02178   InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
02179   if (Inst.isInvalid())
02180     return true;
02181 
02182   // The instantiation is visible here, even if it was first declared in an
02183   // unimported module.
02184   Instantiation->setHidden(false);
02185 
02186   // Enter the scope of this instantiation. We don't use
02187   // PushDeclContext because we don't have a scope.
02188   ContextRAII SavedContext(*this, Instantiation);
02189   EnterExpressionEvaluationContext EvalContext(*this,
02190                                                Sema::PotentiallyEvaluated);
02191 
02192   LocalInstantiationScope Scope(*this, /*MergeWithParentScope*/true);
02193 
02194   // Pull attributes from the pattern onto the instantiation.
02195   InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
02196 
02197   TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
02198   Instantiator.InstantiateEnumDefinition(Instantiation, Pattern);
02199 
02200   // Exit the scope of this instantiation.
02201   SavedContext.pop();
02202 
02203   return Instantiation->isInvalidDecl();
02204 }
02205 
02206 
02207 /// \brief Instantiate the definition of a field from the given pattern.
02208 ///
02209 /// \param PointOfInstantiation The point of instantiation within the
02210 ///        source code.
02211 /// \param Instantiation is the declaration whose definition is being
02212 ///        instantiated. This will be a class of a class temploid
02213 ///        specialization, or a local enumeration within a function temploid
02214 ///        specialization.
02215 /// \param Pattern The templated declaration from which the instantiation
02216 ///        occurs.
02217 /// \param TemplateArgs The template arguments to be substituted into
02218 ///        the pattern.
02219 ///
02220 /// \return \c true if an error occurred, \c false otherwise.
02221 bool Sema::InstantiateInClassInitializer(
02222     SourceLocation PointOfInstantiation, FieldDecl *Instantiation,
02223     FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs) {
02224   // If there is no initializer, we don't need to do anything.
02225   if (!Pattern->hasInClassInitializer())
02226     return false;
02227 
02228   assert(Instantiation->getInClassInitStyle() ==
02229              Pattern->getInClassInitStyle() &&
02230          "pattern and instantiation disagree about init style");
02231 
02232   // Error out if we haven't parsed the initializer of the pattern yet because
02233   // we are waiting for the closing brace of the outer class.
02234   Expr *OldInit = Pattern->getInClassInitializer();
02235   if (!OldInit) {
02236     RecordDecl *PatternRD = Pattern->getParent();
02237     RecordDecl *OutermostClass = PatternRD->getOuterLexicalRecordContext();
02238     if (OutermostClass == PatternRD) {
02239       Diag(Pattern->getLocEnd(), diag::err_in_class_initializer_not_yet_parsed)
02240           << PatternRD << Pattern;
02241     } else {
02242       Diag(Pattern->getLocEnd(),
02243            diag::err_in_class_initializer_not_yet_parsed_outer_class)
02244           << PatternRD << OutermostClass << Pattern;
02245     }
02246     Instantiation->setInvalidDecl();
02247     return true;
02248   }
02249 
02250   InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
02251   if (Inst.isInvalid())
02252     return true;
02253 
02254   // Enter the scope of this instantiation. We don't use PushDeclContext because
02255   // we don't have a scope.
02256   ContextRAII SavedContext(*this, Instantiation->getParent());
02257   EnterExpressionEvaluationContext EvalContext(*this,
02258                                                Sema::PotentiallyEvaluated);
02259 
02260   LocalInstantiationScope Scope(*this);
02261 
02262   // Instantiate the initializer.
02263   ActOnStartCXXInClassMemberInitializer();
02264   CXXThisScopeRAII ThisScope(*this, Instantiation->getParent(), /*TypeQuals=*/0);
02265 
02266   ExprResult NewInit = SubstInitializer(OldInit, TemplateArgs,
02267                                         /*CXXDirectInit=*/false);
02268   Expr *Init = NewInit.get();
02269   assert((!Init || !isa<ParenListExpr>(Init)) && "call-style init in class");
02270   ActOnFinishCXXInClassMemberInitializer(
02271       Instantiation, Init ? Init->getLocStart() : SourceLocation(), Init);
02272 
02273   // Exit the scope of this instantiation.
02274   SavedContext.pop();
02275 
02276   // Return true if the in-class initializer is still missing.
02277   return !Instantiation->getInClassInitializer();
02278 }
02279 
02280 namespace {
02281   /// \brief A partial specialization whose template arguments have matched
02282   /// a given template-id.
02283   struct PartialSpecMatchResult {
02284     ClassTemplatePartialSpecializationDecl *Partial;
02285     TemplateArgumentList *Args;
02286   };
02287 }
02288 
02289 bool Sema::InstantiateClassTemplateSpecialization(
02290     SourceLocation PointOfInstantiation,
02291     ClassTemplateSpecializationDecl *ClassTemplateSpec,
02292     TemplateSpecializationKind TSK, bool Complain) {
02293   // Perform the actual instantiation on the canonical declaration.
02294   ClassTemplateSpec = cast<ClassTemplateSpecializationDecl>(
02295                                          ClassTemplateSpec->getCanonicalDecl());
02296 
02297   // Check whether we have already instantiated or specialized this class
02298   // template specialization.
02299   if (ClassTemplateSpec->getSpecializationKind() != TSK_Undeclared) {
02300     if (ClassTemplateSpec->getSpecializationKind() == 
02301           TSK_ExplicitInstantiationDeclaration &&
02302         TSK == TSK_ExplicitInstantiationDefinition) {
02303       // An explicit instantiation definition follows an explicit instantiation
02304       // declaration (C++0x [temp.explicit]p10); go ahead and perform the
02305       // explicit instantiation.
02306       ClassTemplateSpec->setSpecializationKind(TSK);
02307       
02308       // If this is an explicit instantiation definition, mark the
02309       // vtable as used.
02310       if (TSK == TSK_ExplicitInstantiationDefinition &&
02311           !ClassTemplateSpec->isInvalidDecl())
02312         MarkVTableUsed(PointOfInstantiation, ClassTemplateSpec, true);
02313 
02314       return false;
02315     }
02316     
02317     // We can only instantiate something that hasn't already been
02318     // instantiated or specialized. Fail without any diagnostics: our
02319     // caller will provide an error message.    
02320     return true;
02321   }
02322 
02323   if (ClassTemplateSpec->isInvalidDecl())
02324     return true;
02325   
02326   ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate();
02327   CXXRecordDecl *Pattern = nullptr;
02328 
02329   // C++ [temp.class.spec.match]p1:
02330   //   When a class template is used in a context that requires an
02331   //   instantiation of the class, it is necessary to determine
02332   //   whether the instantiation is to be generated using the primary
02333   //   template or one of the partial specializations. This is done by
02334   //   matching the template arguments of the class template
02335   //   specialization with the template argument lists of the partial
02336   //   specializations.
02337   typedef PartialSpecMatchResult MatchResult;
02338   SmallVector<MatchResult, 4> Matched;
02339   SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
02340   Template->getPartialSpecializations(PartialSpecs);
02341   TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation);
02342   for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
02343     ClassTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
02344     TemplateDeductionInfo Info(FailedCandidates.getLocation());
02345     if (TemplateDeductionResult Result
02346           = DeduceTemplateArguments(Partial,
02347                                     ClassTemplateSpec->getTemplateArgs(),
02348                                     Info)) {
02349       // Store the failed-deduction information for use in diagnostics, later.
02350       // TODO: Actually use the failed-deduction info?
02351       FailedCandidates.addCandidate()
02352           .set(Partial, MakeDeductionFailureInfo(Context, Result, Info));
02353       (void)Result;
02354     } else {
02355       Matched.push_back(PartialSpecMatchResult());
02356       Matched.back().Partial = Partial;
02357       Matched.back().Args = Info.take();
02358     }
02359   }
02360 
02361   // If we're dealing with a member template where the template parameters
02362   // have been instantiated, this provides the original template parameters
02363   // from which the member template's parameters were instantiated.
02364 
02365   if (Matched.size() >= 1) {
02366     SmallVectorImpl<MatchResult>::iterator Best = Matched.begin();
02367     if (Matched.size() == 1) {
02368       //   -- If exactly one matching specialization is found, the
02369       //      instantiation is generated from that specialization.
02370       // We don't need to do anything for this.
02371     } else {
02372       //   -- If more than one matching specialization is found, the
02373       //      partial order rules (14.5.4.2) are used to determine
02374       //      whether one of the specializations is more specialized
02375       //      than the others. If none of the specializations is more
02376       //      specialized than all of the other matching
02377       //      specializations, then the use of the class template is
02378       //      ambiguous and the program is ill-formed.
02379       for (SmallVectorImpl<MatchResult>::iterator P = Best + 1,
02380                                                PEnd = Matched.end();
02381            P != PEnd; ++P) {
02382         if (getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
02383                                                     PointOfInstantiation) 
02384               == P->Partial)
02385           Best = P;
02386       }
02387       
02388       // Determine if the best partial specialization is more specialized than
02389       // the others.
02390       bool Ambiguous = false;
02391       for (SmallVectorImpl<MatchResult>::iterator P = Matched.begin(),
02392                                                PEnd = Matched.end();
02393            P != PEnd; ++P) {
02394         if (P != Best &&
02395             getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
02396                                                     PointOfInstantiation)
02397               != Best->Partial) {
02398           Ambiguous = true;
02399           break;
02400         }
02401       }
02402        
02403       if (Ambiguous) {
02404         // Partial ordering did not produce a clear winner. Complain.
02405         ClassTemplateSpec->setInvalidDecl();
02406         Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous)
02407           << ClassTemplateSpec;
02408         
02409         // Print the matching partial specializations.
02410         for (SmallVectorImpl<MatchResult>::iterator P = Matched.begin(),
02411                                                  PEnd = Matched.end();
02412              P != PEnd; ++P)
02413           Diag(P->Partial->getLocation(), diag::note_partial_spec_match)
02414             << getTemplateArgumentBindingsText(
02415                                             P->Partial->getTemplateParameters(),
02416                                                *P->Args);
02417 
02418         return true;
02419       }
02420     }
02421     
02422     // Instantiate using the best class template partial specialization.
02423     ClassTemplatePartialSpecializationDecl *OrigPartialSpec = Best->Partial;
02424     while (OrigPartialSpec->getInstantiatedFromMember()) {
02425       // If we've found an explicit specialization of this class template,
02426       // stop here and use that as the pattern.
02427       if (OrigPartialSpec->isMemberSpecialization())
02428         break;
02429       
02430       OrigPartialSpec = OrigPartialSpec->getInstantiatedFromMember();
02431     }
02432     
02433     Pattern = OrigPartialSpec;
02434     ClassTemplateSpec->setInstantiationOf(Best->Partial, Best->Args);
02435   } else {
02436     //   -- If no matches are found, the instantiation is generated
02437     //      from the primary template.
02438     ClassTemplateDecl *OrigTemplate = Template;
02439     while (OrigTemplate->getInstantiatedFromMemberTemplate()) {
02440       // If we've found an explicit specialization of this class template,
02441       // stop here and use that as the pattern.
02442       if (OrigTemplate->isMemberSpecialization())
02443         break;
02444       
02445       OrigTemplate = OrigTemplate->getInstantiatedFromMemberTemplate();
02446     }
02447     
02448     Pattern = OrigTemplate->getTemplatedDecl();
02449   }
02450 
02451   bool Result = InstantiateClass(PointOfInstantiation, ClassTemplateSpec, 
02452                                  Pattern,
02453                                 getTemplateInstantiationArgs(ClassTemplateSpec),
02454                                  TSK,
02455                                  Complain);
02456 
02457   return Result;
02458 }
02459 
02460 /// \brief Instantiates the definitions of all of the member
02461 /// of the given class, which is an instantiation of a class template
02462 /// or a member class of a template.
02463 void
02464 Sema::InstantiateClassMembers(SourceLocation PointOfInstantiation,
02465                               CXXRecordDecl *Instantiation,
02466                         const MultiLevelTemplateArgumentList &TemplateArgs,
02467                               TemplateSpecializationKind TSK) {
02468   // FIXME: We need to notify the ASTMutationListener that we did all of these
02469   // things, in case we have an explicit instantiation definition in a PCM, a
02470   // module, or preamble, and the declaration is in an imported AST.
02471   assert(
02472       (TSK == TSK_ExplicitInstantiationDefinition ||
02473        TSK == TSK_ExplicitInstantiationDeclaration ||
02474        (TSK == TSK_ImplicitInstantiation && Instantiation->isLocalClass())) &&
02475       "Unexpected template specialization kind!");
02476   for (auto *D : Instantiation->decls()) {
02477     bool SuppressNew = false;
02478     if (auto *Function = dyn_cast<FunctionDecl>(D)) {
02479       if (FunctionDecl *Pattern
02480             = Function->getInstantiatedFromMemberFunction()) {
02481         MemberSpecializationInfo *MSInfo 
02482           = Function->getMemberSpecializationInfo();
02483         assert(MSInfo && "No member specialization information?");
02484         if (MSInfo->getTemplateSpecializationKind()
02485                                                  == TSK_ExplicitSpecialization)
02486           continue;
02487         
02488         if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK, 
02489                                                    Function, 
02490                                         MSInfo->getTemplateSpecializationKind(),
02491                                               MSInfo->getPointOfInstantiation(),
02492                                                    SuppressNew) ||
02493             SuppressNew)
02494           continue;
02495 
02496         // C++11 [temp.explicit]p8:
02497         //   An explicit instantiation definition that names a class template
02498         //   specialization explicitly instantiates the class template
02499         //   specialization and is only an explicit instantiation definition
02500         //   of members whose definition is visible at the point of
02501         //   instantiation.
02502         if (TSK == TSK_ExplicitInstantiationDefinition && !Pattern->isDefined())
02503           continue;
02504 
02505         Function->setTemplateSpecializationKind(TSK, PointOfInstantiation);
02506 
02507         if (Function->isDefined()) {
02508           // Let the ASTConsumer know that this function has been explicitly
02509           // instantiated now, and its linkage might have changed.
02510           Consumer.HandleTopLevelDecl(DeclGroupRef(Function));
02511         } else if (TSK == TSK_ExplicitInstantiationDefinition) {
02512           InstantiateFunctionDefinition(PointOfInstantiation, Function);
02513         } else if (TSK == TSK_ImplicitInstantiation) {
02514           PendingLocalImplicitInstantiations.push_back(
02515               std::make_pair(Function, PointOfInstantiation));
02516         }
02517       }
02518     } else if (auto *Var = dyn_cast<VarDecl>(D)) {
02519       if (isa<VarTemplateSpecializationDecl>(Var))
02520         continue;
02521 
02522       if (Var->isStaticDataMember()) {
02523         MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
02524         assert(MSInfo && "No member specialization information?");
02525         if (MSInfo->getTemplateSpecializationKind()
02526                                                  == TSK_ExplicitSpecialization)
02527           continue;
02528         
02529         if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK, 
02530                                                    Var, 
02531                                         MSInfo->getTemplateSpecializationKind(),
02532                                               MSInfo->getPointOfInstantiation(),
02533                                                    SuppressNew) ||
02534             SuppressNew)
02535           continue;
02536         
02537         if (TSK == TSK_ExplicitInstantiationDefinition) {
02538           // C++0x [temp.explicit]p8:
02539           //   An explicit instantiation definition that names a class template
02540           //   specialization explicitly instantiates the class template 
02541           //   specialization and is only an explicit instantiation definition 
02542           //   of members whose definition is visible at the point of 
02543           //   instantiation.
02544           if (!Var->getInstantiatedFromStaticDataMember()
02545                                                      ->getOutOfLineDefinition())
02546             continue;
02547           
02548           Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
02549           InstantiateStaticDataMemberDefinition(PointOfInstantiation, Var);
02550         } else {
02551           Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
02552         }
02553       }      
02554     } else if (auto *Record = dyn_cast<CXXRecordDecl>(D)) {
02555       // Always skip the injected-class-name, along with any
02556       // redeclarations of nested classes, since both would cause us
02557       // to try to instantiate the members of a class twice.
02558       if (Record->isInjectedClassName() || Record->getPreviousDecl())
02559         continue;
02560       
02561       MemberSpecializationInfo *MSInfo = Record->getMemberSpecializationInfo();
02562       assert(MSInfo && "No member specialization information?");
02563       
02564       if (MSInfo->getTemplateSpecializationKind()
02565                                                 == TSK_ExplicitSpecialization)
02566         continue;
02567 
02568       if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK, 
02569                                                  Record, 
02570                                         MSInfo->getTemplateSpecializationKind(),
02571                                               MSInfo->getPointOfInstantiation(),
02572                                                  SuppressNew) ||
02573           SuppressNew)
02574         continue;
02575       
02576       CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
02577       assert(Pattern && "Missing instantiated-from-template information");
02578       
02579       if (!Record->getDefinition()) {
02580         if (!Pattern->getDefinition()) {
02581           // C++0x [temp.explicit]p8:
02582           //   An explicit instantiation definition that names a class template
02583           //   specialization explicitly instantiates the class template 
02584           //   specialization and is only an explicit instantiation definition 
02585           //   of members whose definition is visible at the point of 
02586           //   instantiation.
02587           if (TSK == TSK_ExplicitInstantiationDeclaration) {
02588             MSInfo->setTemplateSpecializationKind(TSK);
02589             MSInfo->setPointOfInstantiation(PointOfInstantiation);
02590           }
02591           
02592           continue;
02593         }
02594         
02595         InstantiateClass(PointOfInstantiation, Record, Pattern,
02596                          TemplateArgs,
02597                          TSK);
02598       } else {
02599         if (TSK == TSK_ExplicitInstantiationDefinition &&
02600             Record->getTemplateSpecializationKind() ==
02601                 TSK_ExplicitInstantiationDeclaration) {
02602           Record->setTemplateSpecializationKind(TSK);
02603           MarkVTableUsed(PointOfInstantiation, Record, true);
02604         }
02605       }
02606       
02607       Pattern = cast_or_null<CXXRecordDecl>(Record->getDefinition());
02608       if (Pattern)
02609         InstantiateClassMembers(PointOfInstantiation, Pattern, TemplateArgs, 
02610                                 TSK);
02611     } else if (auto *Enum = dyn_cast<EnumDecl>(D)) {
02612       MemberSpecializationInfo *MSInfo = Enum->getMemberSpecializationInfo();
02613       assert(MSInfo && "No member specialization information?");
02614 
02615       if (MSInfo->getTemplateSpecializationKind()
02616             == TSK_ExplicitSpecialization)
02617         continue;
02618 
02619       if (CheckSpecializationInstantiationRedecl(
02620             PointOfInstantiation, TSK, Enum,
02621             MSInfo->getTemplateSpecializationKind(),
02622             MSInfo->getPointOfInstantiation(), SuppressNew) ||
02623           SuppressNew)
02624         continue;
02625 
02626       if (Enum->getDefinition())
02627         continue;
02628 
02629       EnumDecl *Pattern = Enum->getInstantiatedFromMemberEnum();
02630       assert(Pattern && "Missing instantiated-from-template information");
02631 
02632       if (TSK == TSK_ExplicitInstantiationDefinition) {
02633         if (!Pattern->getDefinition())
02634           continue;
02635 
02636         InstantiateEnum(PointOfInstantiation, Enum, Pattern, TemplateArgs, TSK);
02637       } else {
02638         MSInfo->setTemplateSpecializationKind(TSK);
02639         MSInfo->setPointOfInstantiation(PointOfInstantiation);
02640       }
02641     } else if (auto *Field = dyn_cast<FieldDecl>(D)) {
02642       // No need to instantiate in-class initializers during explicit
02643       // instantiation.
02644       if (Field->hasInClassInitializer() && TSK == TSK_ImplicitInstantiation) {
02645         CXXRecordDecl *ClassPattern =
02646             Instantiation->getTemplateInstantiationPattern();
02647         DeclContext::lookup_result Lookup =
02648             ClassPattern->lookup(Field->getDeclName());
02649         assert(Lookup.size() == 1);
02650         FieldDecl *Pattern = cast<FieldDecl>(Lookup[0]);
02651         InstantiateInClassInitializer(PointOfInstantiation, Field, Pattern,
02652                                       TemplateArgs);
02653       }
02654     }
02655   }
02656 }
02657 
02658 /// \brief Instantiate the definitions of all of the members of the
02659 /// given class template specialization, which was named as part of an
02660 /// explicit instantiation.
02661 void
02662 Sema::InstantiateClassTemplateSpecializationMembers(
02663                                            SourceLocation PointOfInstantiation,
02664                             ClassTemplateSpecializationDecl *ClassTemplateSpec,
02665                                                TemplateSpecializationKind TSK) {
02666   // C++0x [temp.explicit]p7:
02667   //   An explicit instantiation that names a class template
02668   //   specialization is an explicit instantion of the same kind
02669   //   (declaration or definition) of each of its members (not
02670   //   including members inherited from base classes) that has not
02671   //   been previously explicitly specialized in the translation unit
02672   //   containing the explicit instantiation, except as described
02673   //   below.
02674   InstantiateClassMembers(PointOfInstantiation, ClassTemplateSpec,
02675                           getTemplateInstantiationArgs(ClassTemplateSpec),
02676                           TSK);
02677 }
02678 
02679 StmtResult
02680 Sema::SubstStmt(Stmt *S, const MultiLevelTemplateArgumentList &TemplateArgs) {
02681   if (!S)
02682     return S;
02683 
02684   TemplateInstantiator Instantiator(*this, TemplateArgs,
02685                                     SourceLocation(),
02686                                     DeclarationName());
02687   return Instantiator.TransformStmt(S);
02688 }
02689 
02690 ExprResult
02691 Sema::SubstExpr(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs) {
02692   if (!E)
02693     return E;
02694 
02695   TemplateInstantiator Instantiator(*this, TemplateArgs,
02696                                     SourceLocation(),
02697                                     DeclarationName());
02698   return Instantiator.TransformExpr(E);
02699 }
02700 
02701 ExprResult Sema::SubstInitializer(Expr *Init,
02702                           const MultiLevelTemplateArgumentList &TemplateArgs,
02703                           bool CXXDirectInit) {
02704   TemplateInstantiator Instantiator(*this, TemplateArgs,
02705                                     SourceLocation(),
02706                                     DeclarationName());
02707   return Instantiator.TransformInitializer(Init, CXXDirectInit);
02708 }
02709 
02710 bool Sema::SubstExprs(Expr **Exprs, unsigned NumExprs, bool IsCall,
02711                       const MultiLevelTemplateArgumentList &TemplateArgs,
02712                       SmallVectorImpl<Expr *> &Outputs) {
02713   if (NumExprs == 0)
02714     return false;
02715 
02716   TemplateInstantiator Instantiator(*this, TemplateArgs,
02717                                     SourceLocation(),
02718                                     DeclarationName());
02719   return Instantiator.TransformExprs(Exprs, NumExprs, IsCall, Outputs);
02720 }
02721 
02722 NestedNameSpecifierLoc
02723 Sema::SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
02724                         const MultiLevelTemplateArgumentList &TemplateArgs) {  
02725   if (!NNS)
02726     return NestedNameSpecifierLoc();
02727   
02728   TemplateInstantiator Instantiator(*this, TemplateArgs, NNS.getBeginLoc(),
02729                                     DeclarationName());
02730   return Instantiator.TransformNestedNameSpecifierLoc(NNS);
02731 }
02732 
02733 /// \brief Do template substitution on declaration name info.
02734 DeclarationNameInfo
02735 Sema::SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
02736                          const MultiLevelTemplateArgumentList &TemplateArgs) {
02737   TemplateInstantiator Instantiator(*this, TemplateArgs, NameInfo.getLoc(),
02738                                     NameInfo.getName());
02739   return Instantiator.TransformDeclarationNameInfo(NameInfo);
02740 }
02741 
02742 TemplateName
02743 Sema::SubstTemplateName(NestedNameSpecifierLoc QualifierLoc,
02744                         TemplateName Name, SourceLocation Loc,
02745                         const MultiLevelTemplateArgumentList &TemplateArgs) {
02746   TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
02747                                     DeclarationName());
02748   CXXScopeSpec SS;
02749   SS.Adopt(QualifierLoc);
02750   return Instantiator.TransformTemplateName(SS, Name, Loc);
02751 }
02752 
02753 bool Sema::Subst(const TemplateArgumentLoc *Args, unsigned NumArgs,
02754                  TemplateArgumentListInfo &Result,
02755                  const MultiLevelTemplateArgumentList &TemplateArgs) {
02756   TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(),
02757                                     DeclarationName());
02758   
02759   return Instantiator.TransformTemplateArguments(Args, NumArgs, Result);
02760 }
02761 
02762 
02763 static const Decl* getCanonicalParmVarDecl(const Decl *D) {
02764   // When storing ParmVarDecls in the local instantiation scope, we always
02765   // want to use the ParmVarDecl from the canonical function declaration,
02766   // since the map is then valid for any redeclaration or definition of that
02767   // function.
02768   if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(D)) {
02769     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
02770       unsigned i = PV->getFunctionScopeIndex();
02771       return FD->getCanonicalDecl()->getParamDecl(i);
02772     }
02773   }
02774   return D;
02775 }
02776 
02777 
02778 llvm::PointerUnion<Decl *, LocalInstantiationScope::DeclArgumentPack *> *
02779 LocalInstantiationScope::findInstantiationOf(const Decl *D) {
02780   D = getCanonicalParmVarDecl(D);
02781   for (LocalInstantiationScope *Current = this; Current;
02782        Current = Current->Outer) {
02783 
02784     // Check if we found something within this scope.
02785     const Decl *CheckD = D;
02786     do {
02787       LocalDeclsMap::iterator Found = Current->LocalDecls.find(CheckD);
02788       if (Found != Current->LocalDecls.end())
02789         return &Found->second;
02790       
02791       // If this is a tag declaration, it's possible that we need to look for
02792       // a previous declaration.
02793       if (const TagDecl *Tag = dyn_cast<TagDecl>(CheckD))
02794         CheckD = Tag->getPreviousDecl();
02795       else
02796         CheckD = nullptr;
02797     } while (CheckD);
02798     
02799     // If we aren't combined with our outer scope, we're done. 
02800     if (!Current->CombineWithOuterScope)
02801       break;
02802   }
02803 
02804   // If we're performing a partial substitution during template argument
02805   // deduction, we may not have values for template parameters yet.
02806   if (isa<NonTypeTemplateParmDecl>(D) || isa<TemplateTypeParmDecl>(D) ||
02807       isa<TemplateTemplateParmDecl>(D))
02808     return nullptr;
02809 
02810   // If we didn't find the decl, then we either have a sema bug, or we have a
02811   // forward reference to a label declaration.  Return null to indicate that
02812   // we have an uninstantiated label.
02813   assert(isa<LabelDecl>(D) && "declaration not instantiated in this scope");
02814   return nullptr;
02815 }
02816 
02817 void LocalInstantiationScope::InstantiatedLocal(const Decl *D, Decl *Inst) {
02818   D = getCanonicalParmVarDecl(D);
02819   llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
02820   if (Stored.isNull())
02821     Stored = Inst;
02822   else if (DeclArgumentPack *Pack = Stored.dyn_cast<DeclArgumentPack *>())
02823     Pack->push_back(Inst);
02824   else
02825     assert(Stored.get<Decl *>() == Inst && "Already instantiated this local");
02826 }
02827 
02828 void LocalInstantiationScope::InstantiatedLocalPackArg(const Decl *D, 
02829                                                        Decl *Inst) {
02830   D = getCanonicalParmVarDecl(D);
02831   DeclArgumentPack *Pack = LocalDecls[D].get<DeclArgumentPack *>();
02832   Pack->push_back(Inst);
02833 }
02834 
02835 void LocalInstantiationScope::MakeInstantiatedLocalArgPack(const Decl *D) {
02836   D = getCanonicalParmVarDecl(D);
02837   llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
02838   assert(Stored.isNull() && "Already instantiated this local");
02839   DeclArgumentPack *Pack = new DeclArgumentPack;
02840   Stored = Pack;
02841   ArgumentPacks.push_back(Pack);
02842 }
02843 
02844 void LocalInstantiationScope::SetPartiallySubstitutedPack(NamedDecl *Pack, 
02845                                           const TemplateArgument *ExplicitArgs,
02846                                                     unsigned NumExplicitArgs) {
02847   assert((!PartiallySubstitutedPack || PartiallySubstitutedPack == Pack) &&
02848          "Already have a partially-substituted pack");
02849   assert((!PartiallySubstitutedPack 
02850           || NumArgsInPartiallySubstitutedPack == NumExplicitArgs) &&
02851          "Wrong number of arguments in partially-substituted pack");
02852   PartiallySubstitutedPack = Pack;
02853   ArgsInPartiallySubstitutedPack = ExplicitArgs;
02854   NumArgsInPartiallySubstitutedPack = NumExplicitArgs;
02855 }
02856 
02857 NamedDecl *LocalInstantiationScope::getPartiallySubstitutedPack(
02858                                          const TemplateArgument **ExplicitArgs,
02859                                               unsigned *NumExplicitArgs) const {
02860   if (ExplicitArgs)
02861     *ExplicitArgs = nullptr;
02862   if (NumExplicitArgs)
02863     *NumExplicitArgs = 0;
02864   
02865   for (const LocalInstantiationScope *Current = this; Current; 
02866        Current = Current->Outer) {
02867     if (Current->PartiallySubstitutedPack) {
02868       if (ExplicitArgs)
02869         *ExplicitArgs = Current->ArgsInPartiallySubstitutedPack;
02870       if (NumExplicitArgs)
02871         *NumExplicitArgs = Current->NumArgsInPartiallySubstitutedPack;
02872       
02873       return Current->PartiallySubstitutedPack;
02874     }
02875 
02876     if (!Current->CombineWithOuterScope)
02877       break;
02878   }
02879 
02880   return nullptr;
02881 }