xref: /freebsd/contrib/llvm-project/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp (revision 69ade1e033e478ec426cafc0ec2104d672de294a)
10b57cec5SDimitry Andric //===--- SemaTemplateInstantiateDecl.cpp - C++ Template Decl Instantiation ===/
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //===----------------------------------------------------------------------===/
70b57cec5SDimitry Andric //
80b57cec5SDimitry Andric //  This file implements C++ template instantiation for declarations.
90b57cec5SDimitry Andric //
100b57cec5SDimitry Andric //===----------------------------------------------------------------------===/
115ffd83dbSDimitry Andric 
12fe6060f1SDimitry Andric #include "TreeTransform.h"
130b57cec5SDimitry Andric #include "clang/AST/ASTConsumer.h"
140b57cec5SDimitry Andric #include "clang/AST/ASTContext.h"
150b57cec5SDimitry Andric #include "clang/AST/ASTMutationListener.h"
160b57cec5SDimitry Andric #include "clang/AST/DeclTemplate.h"
170b57cec5SDimitry Andric #include "clang/AST/DeclVisitor.h"
180b57cec5SDimitry Andric #include "clang/AST/DependentDiagnostic.h"
190b57cec5SDimitry Andric #include "clang/AST/Expr.h"
200b57cec5SDimitry Andric #include "clang/AST/ExprCXX.h"
210b57cec5SDimitry Andric #include "clang/AST/PrettyDeclStackTrace.h"
220b57cec5SDimitry Andric #include "clang/AST/TypeLoc.h"
235ffd83dbSDimitry Andric #include "clang/Basic/SourceManager.h"
245ffd83dbSDimitry Andric #include "clang/Basic/TargetInfo.h"
250b57cec5SDimitry Andric #include "clang/Sema/Initialization.h"
260b57cec5SDimitry Andric #include "clang/Sema/Lookup.h"
27fe6060f1SDimitry Andric #include "clang/Sema/ScopeInfo.h"
285ffd83dbSDimitry Andric #include "clang/Sema/SemaInternal.h"
290b57cec5SDimitry Andric #include "clang/Sema/Template.h"
300b57cec5SDimitry Andric #include "clang/Sema/TemplateInstCallback.h"
310b57cec5SDimitry Andric #include "llvm/Support/TimeProfiler.h"
320b57cec5SDimitry Andric 
330b57cec5SDimitry Andric using namespace clang;
340b57cec5SDimitry Andric 
350b57cec5SDimitry Andric static bool isDeclWithinFunction(const Decl *D) {
360b57cec5SDimitry Andric   const DeclContext *DC = D->getDeclContext();
370b57cec5SDimitry Andric   if (DC->isFunctionOrMethod())
380b57cec5SDimitry Andric     return true;
390b57cec5SDimitry Andric 
400b57cec5SDimitry Andric   if (DC->isRecord())
410b57cec5SDimitry Andric     return cast<CXXRecordDecl>(DC)->isLocalClass();
420b57cec5SDimitry Andric 
430b57cec5SDimitry Andric   return false;
440b57cec5SDimitry Andric }
450b57cec5SDimitry Andric 
460b57cec5SDimitry Andric template<typename DeclT>
470b57cec5SDimitry Andric static bool SubstQualifier(Sema &SemaRef, const DeclT *OldDecl, DeclT *NewDecl,
480b57cec5SDimitry Andric                            const MultiLevelTemplateArgumentList &TemplateArgs) {
490b57cec5SDimitry Andric   if (!OldDecl->getQualifierLoc())
500b57cec5SDimitry Andric     return false;
510b57cec5SDimitry Andric 
520b57cec5SDimitry Andric   assert((NewDecl->getFriendObjectKind() ||
530b57cec5SDimitry Andric           !OldDecl->getLexicalDeclContext()->isDependentContext()) &&
540b57cec5SDimitry Andric          "non-friend with qualified name defined in dependent context");
550b57cec5SDimitry Andric   Sema::ContextRAII SavedContext(
560b57cec5SDimitry Andric       SemaRef,
570b57cec5SDimitry Andric       const_cast<DeclContext *>(NewDecl->getFriendObjectKind()
580b57cec5SDimitry Andric                                     ? NewDecl->getLexicalDeclContext()
590b57cec5SDimitry Andric                                     : OldDecl->getLexicalDeclContext()));
600b57cec5SDimitry Andric 
610b57cec5SDimitry Andric   NestedNameSpecifierLoc NewQualifierLoc
620b57cec5SDimitry Andric       = SemaRef.SubstNestedNameSpecifierLoc(OldDecl->getQualifierLoc(),
630b57cec5SDimitry Andric                                             TemplateArgs);
640b57cec5SDimitry Andric 
650b57cec5SDimitry Andric   if (!NewQualifierLoc)
660b57cec5SDimitry Andric     return true;
670b57cec5SDimitry Andric 
680b57cec5SDimitry Andric   NewDecl->setQualifierInfo(NewQualifierLoc);
690b57cec5SDimitry Andric   return false;
700b57cec5SDimitry Andric }
710b57cec5SDimitry Andric 
720b57cec5SDimitry Andric bool TemplateDeclInstantiator::SubstQualifier(const DeclaratorDecl *OldDecl,
730b57cec5SDimitry Andric                                               DeclaratorDecl *NewDecl) {
740b57cec5SDimitry Andric   return ::SubstQualifier(SemaRef, OldDecl, NewDecl, TemplateArgs);
750b57cec5SDimitry Andric }
760b57cec5SDimitry Andric 
770b57cec5SDimitry Andric bool TemplateDeclInstantiator::SubstQualifier(const TagDecl *OldDecl,
780b57cec5SDimitry Andric                                               TagDecl *NewDecl) {
790b57cec5SDimitry Andric   return ::SubstQualifier(SemaRef, OldDecl, NewDecl, TemplateArgs);
800b57cec5SDimitry Andric }
810b57cec5SDimitry Andric 
820b57cec5SDimitry Andric // Include attribute instantiation code.
830b57cec5SDimitry Andric #include "clang/Sema/AttrTemplateInstantiate.inc"
840b57cec5SDimitry Andric 
850b57cec5SDimitry Andric static void instantiateDependentAlignedAttr(
860b57cec5SDimitry Andric     Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
870b57cec5SDimitry Andric     const AlignedAttr *Aligned, Decl *New, bool IsPackExpansion) {
880b57cec5SDimitry Andric   if (Aligned->isAlignmentExpr()) {
890b57cec5SDimitry Andric     // The alignment expression is a constant expression.
900b57cec5SDimitry Andric     EnterExpressionEvaluationContext Unevaluated(
910b57cec5SDimitry Andric         S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
920b57cec5SDimitry Andric     ExprResult Result = S.SubstExpr(Aligned->getAlignmentExpr(), TemplateArgs);
930b57cec5SDimitry Andric     if (!Result.isInvalid())
94a7dea167SDimitry Andric       S.AddAlignedAttr(New, *Aligned, Result.getAs<Expr>(), IsPackExpansion);
950b57cec5SDimitry Andric   } else {
960b57cec5SDimitry Andric     TypeSourceInfo *Result = S.SubstType(Aligned->getAlignmentType(),
970b57cec5SDimitry Andric                                          TemplateArgs, Aligned->getLocation(),
980b57cec5SDimitry Andric                                          DeclarationName());
990b57cec5SDimitry Andric     if (Result)
100a7dea167SDimitry Andric       S.AddAlignedAttr(New, *Aligned, Result, IsPackExpansion);
1010b57cec5SDimitry Andric   }
1020b57cec5SDimitry Andric }
1030b57cec5SDimitry Andric 
1040b57cec5SDimitry Andric static void instantiateDependentAlignedAttr(
1050b57cec5SDimitry Andric     Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
1060b57cec5SDimitry Andric     const AlignedAttr *Aligned, Decl *New) {
1070b57cec5SDimitry Andric   if (!Aligned->isPackExpansion()) {
1080b57cec5SDimitry Andric     instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, false);
1090b57cec5SDimitry Andric     return;
1100b57cec5SDimitry Andric   }
1110b57cec5SDimitry Andric 
1120b57cec5SDimitry Andric   SmallVector<UnexpandedParameterPack, 2> Unexpanded;
1130b57cec5SDimitry Andric   if (Aligned->isAlignmentExpr())
1140b57cec5SDimitry Andric     S.collectUnexpandedParameterPacks(Aligned->getAlignmentExpr(),
1150b57cec5SDimitry Andric                                       Unexpanded);
1160b57cec5SDimitry Andric   else
1170b57cec5SDimitry Andric     S.collectUnexpandedParameterPacks(Aligned->getAlignmentType()->getTypeLoc(),
1180b57cec5SDimitry Andric                                       Unexpanded);
1190b57cec5SDimitry Andric   assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
1200b57cec5SDimitry Andric 
1210b57cec5SDimitry Andric   // Determine whether we can expand this attribute pack yet.
1220b57cec5SDimitry Andric   bool Expand = true, RetainExpansion = false;
1230b57cec5SDimitry Andric   Optional<unsigned> NumExpansions;
1240b57cec5SDimitry Andric   // FIXME: Use the actual location of the ellipsis.
1250b57cec5SDimitry Andric   SourceLocation EllipsisLoc = Aligned->getLocation();
1260b57cec5SDimitry Andric   if (S.CheckParameterPacksForExpansion(EllipsisLoc, Aligned->getRange(),
1270b57cec5SDimitry Andric                                         Unexpanded, TemplateArgs, Expand,
1280b57cec5SDimitry Andric                                         RetainExpansion, NumExpansions))
1290b57cec5SDimitry Andric     return;
1300b57cec5SDimitry Andric 
1310b57cec5SDimitry Andric   if (!Expand) {
1320b57cec5SDimitry Andric     Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(S, -1);
1330b57cec5SDimitry Andric     instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, true);
1340b57cec5SDimitry Andric   } else {
1350b57cec5SDimitry Andric     for (unsigned I = 0; I != *NumExpansions; ++I) {
1360b57cec5SDimitry Andric       Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(S, I);
1370b57cec5SDimitry Andric       instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, false);
1380b57cec5SDimitry Andric     }
1390b57cec5SDimitry Andric   }
1400b57cec5SDimitry Andric }
1410b57cec5SDimitry Andric 
1420b57cec5SDimitry Andric static void instantiateDependentAssumeAlignedAttr(
1430b57cec5SDimitry Andric     Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
1440b57cec5SDimitry Andric     const AssumeAlignedAttr *Aligned, Decl *New) {
1450b57cec5SDimitry Andric   // The alignment expression is a constant expression.
1460b57cec5SDimitry Andric   EnterExpressionEvaluationContext Unevaluated(
1470b57cec5SDimitry Andric       S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
1480b57cec5SDimitry Andric 
1490b57cec5SDimitry Andric   Expr *E, *OE = nullptr;
1500b57cec5SDimitry Andric   ExprResult Result = S.SubstExpr(Aligned->getAlignment(), TemplateArgs);
1510b57cec5SDimitry Andric   if (Result.isInvalid())
1520b57cec5SDimitry Andric     return;
1530b57cec5SDimitry Andric   E = Result.getAs<Expr>();
1540b57cec5SDimitry Andric 
1550b57cec5SDimitry Andric   if (Aligned->getOffset()) {
1560b57cec5SDimitry Andric     Result = S.SubstExpr(Aligned->getOffset(), TemplateArgs);
1570b57cec5SDimitry Andric     if (Result.isInvalid())
1580b57cec5SDimitry Andric       return;
1590b57cec5SDimitry Andric     OE = Result.getAs<Expr>();
1600b57cec5SDimitry Andric   }
1610b57cec5SDimitry Andric 
162a7dea167SDimitry Andric   S.AddAssumeAlignedAttr(New, *Aligned, E, OE);
1630b57cec5SDimitry Andric }
1640b57cec5SDimitry Andric 
1650b57cec5SDimitry Andric static void instantiateDependentAlignValueAttr(
1660b57cec5SDimitry Andric     Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
1670b57cec5SDimitry Andric     const AlignValueAttr *Aligned, Decl *New) {
1680b57cec5SDimitry Andric   // The alignment expression is a constant expression.
1690b57cec5SDimitry Andric   EnterExpressionEvaluationContext Unevaluated(
1700b57cec5SDimitry Andric       S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
1710b57cec5SDimitry Andric   ExprResult Result = S.SubstExpr(Aligned->getAlignment(), TemplateArgs);
1720b57cec5SDimitry Andric   if (!Result.isInvalid())
173a7dea167SDimitry Andric     S.AddAlignValueAttr(New, *Aligned, Result.getAs<Expr>());
1740b57cec5SDimitry Andric }
1750b57cec5SDimitry Andric 
1760b57cec5SDimitry Andric static void instantiateDependentAllocAlignAttr(
1770b57cec5SDimitry Andric     Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
1780b57cec5SDimitry Andric     const AllocAlignAttr *Align, Decl *New) {
1790b57cec5SDimitry Andric   Expr *Param = IntegerLiteral::Create(
1800b57cec5SDimitry Andric       S.getASTContext(),
1810b57cec5SDimitry Andric       llvm::APInt(64, Align->getParamIndex().getSourceIndex()),
1820b57cec5SDimitry Andric       S.getASTContext().UnsignedLongLongTy, Align->getLocation());
183a7dea167SDimitry Andric   S.AddAllocAlignAttr(New, *Align, Param);
1840b57cec5SDimitry Andric }
1850b57cec5SDimitry Andric 
186e8d8bef9SDimitry Andric static void instantiateDependentAnnotationAttr(
187e8d8bef9SDimitry Andric     Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
188e8d8bef9SDimitry Andric     const AnnotateAttr *Attr, Decl *New) {
189e8d8bef9SDimitry Andric   EnterExpressionEvaluationContext Unevaluated(
190e8d8bef9SDimitry Andric       S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
191e8d8bef9SDimitry Andric   SmallVector<Expr *, 4> Args;
192e8d8bef9SDimitry Andric   Args.reserve(Attr->args_size());
193e8d8bef9SDimitry Andric   for (auto *E : Attr->args()) {
194e8d8bef9SDimitry Andric     ExprResult Result = S.SubstExpr(E, TemplateArgs);
195e8d8bef9SDimitry Andric     if (!Result.isUsable())
196e8d8bef9SDimitry Andric       return;
197e8d8bef9SDimitry Andric     Args.push_back(Result.get());
198e8d8bef9SDimitry Andric   }
199e8d8bef9SDimitry Andric   S.AddAnnotationAttr(New, *Attr, Attr->getAnnotation(), Args);
200e8d8bef9SDimitry Andric }
201e8d8bef9SDimitry Andric 
2020b57cec5SDimitry Andric static Expr *instantiateDependentFunctionAttrCondition(
2030b57cec5SDimitry Andric     Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
2040b57cec5SDimitry Andric     const Attr *A, Expr *OldCond, const Decl *Tmpl, FunctionDecl *New) {
2050b57cec5SDimitry Andric   Expr *Cond = nullptr;
2060b57cec5SDimitry Andric   {
2070b57cec5SDimitry Andric     Sema::ContextRAII SwitchContext(S, New);
2080b57cec5SDimitry Andric     EnterExpressionEvaluationContext Unevaluated(
2090b57cec5SDimitry Andric         S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
2100b57cec5SDimitry Andric     ExprResult Result = S.SubstExpr(OldCond, TemplateArgs);
2110b57cec5SDimitry Andric     if (Result.isInvalid())
2120b57cec5SDimitry Andric       return nullptr;
2130b57cec5SDimitry Andric     Cond = Result.getAs<Expr>();
2140b57cec5SDimitry Andric   }
2150b57cec5SDimitry Andric   if (!Cond->isTypeDependent()) {
2160b57cec5SDimitry Andric     ExprResult Converted = S.PerformContextuallyConvertToBool(Cond);
2170b57cec5SDimitry Andric     if (Converted.isInvalid())
2180b57cec5SDimitry Andric       return nullptr;
2190b57cec5SDimitry Andric     Cond = Converted.get();
2200b57cec5SDimitry Andric   }
2210b57cec5SDimitry Andric 
2220b57cec5SDimitry Andric   SmallVector<PartialDiagnosticAt, 8> Diags;
2230b57cec5SDimitry Andric   if (OldCond->isValueDependent() && !Cond->isValueDependent() &&
2240b57cec5SDimitry Andric       !Expr::isPotentialConstantExprUnevaluated(Cond, New, Diags)) {
2250b57cec5SDimitry Andric     S.Diag(A->getLocation(), diag::err_attr_cond_never_constant_expr) << A;
2260b57cec5SDimitry Andric     for (const auto &P : Diags)
2270b57cec5SDimitry Andric       S.Diag(P.first, P.second);
2280b57cec5SDimitry Andric     return nullptr;
2290b57cec5SDimitry Andric   }
2300b57cec5SDimitry Andric   return Cond;
2310b57cec5SDimitry Andric }
2320b57cec5SDimitry Andric 
2330b57cec5SDimitry Andric static void instantiateDependentEnableIfAttr(
2340b57cec5SDimitry Andric     Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
2350b57cec5SDimitry Andric     const EnableIfAttr *EIA, const Decl *Tmpl, FunctionDecl *New) {
2360b57cec5SDimitry Andric   Expr *Cond = instantiateDependentFunctionAttrCondition(
2370b57cec5SDimitry Andric       S, TemplateArgs, EIA, EIA->getCond(), Tmpl, New);
2380b57cec5SDimitry Andric 
2390b57cec5SDimitry Andric   if (Cond)
240a7dea167SDimitry Andric     New->addAttr(new (S.getASTContext()) EnableIfAttr(S.getASTContext(), *EIA,
241a7dea167SDimitry Andric                                                       Cond, EIA->getMessage()));
2420b57cec5SDimitry Andric }
2430b57cec5SDimitry Andric 
2440b57cec5SDimitry Andric static void instantiateDependentDiagnoseIfAttr(
2450b57cec5SDimitry Andric     Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
2460b57cec5SDimitry Andric     const DiagnoseIfAttr *DIA, const Decl *Tmpl, FunctionDecl *New) {
2470b57cec5SDimitry Andric   Expr *Cond = instantiateDependentFunctionAttrCondition(
2480b57cec5SDimitry Andric       S, TemplateArgs, DIA, DIA->getCond(), Tmpl, New);
2490b57cec5SDimitry Andric 
2500b57cec5SDimitry Andric   if (Cond)
2510b57cec5SDimitry Andric     New->addAttr(new (S.getASTContext()) DiagnoseIfAttr(
252a7dea167SDimitry Andric         S.getASTContext(), *DIA, Cond, DIA->getMessage(),
253a7dea167SDimitry Andric         DIA->getDiagnosticType(), DIA->getArgDependent(), New));
2540b57cec5SDimitry Andric }
2550b57cec5SDimitry Andric 
2560b57cec5SDimitry Andric // Constructs and adds to New a new instance of CUDALaunchBoundsAttr using
2570b57cec5SDimitry Andric // template A as the base and arguments from TemplateArgs.
2580b57cec5SDimitry Andric static void instantiateDependentCUDALaunchBoundsAttr(
2590b57cec5SDimitry Andric     Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
2600b57cec5SDimitry Andric     const CUDALaunchBoundsAttr &Attr, Decl *New) {
2610b57cec5SDimitry Andric   // The alignment expression is a constant expression.
2620b57cec5SDimitry Andric   EnterExpressionEvaluationContext Unevaluated(
2630b57cec5SDimitry Andric       S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
2640b57cec5SDimitry Andric 
2650b57cec5SDimitry Andric   ExprResult Result = S.SubstExpr(Attr.getMaxThreads(), TemplateArgs);
2660b57cec5SDimitry Andric   if (Result.isInvalid())
2670b57cec5SDimitry Andric     return;
2680b57cec5SDimitry Andric   Expr *MaxThreads = Result.getAs<Expr>();
2690b57cec5SDimitry Andric 
2700b57cec5SDimitry Andric   Expr *MinBlocks = nullptr;
2710b57cec5SDimitry Andric   if (Attr.getMinBlocks()) {
2720b57cec5SDimitry Andric     Result = S.SubstExpr(Attr.getMinBlocks(), TemplateArgs);
2730b57cec5SDimitry Andric     if (Result.isInvalid())
2740b57cec5SDimitry Andric       return;
2750b57cec5SDimitry Andric     MinBlocks = Result.getAs<Expr>();
2760b57cec5SDimitry Andric   }
2770b57cec5SDimitry Andric 
278a7dea167SDimitry Andric   S.AddLaunchBoundsAttr(New, Attr, MaxThreads, MinBlocks);
2790b57cec5SDimitry Andric }
2800b57cec5SDimitry Andric 
2810b57cec5SDimitry Andric static void
2820b57cec5SDimitry Andric instantiateDependentModeAttr(Sema &S,
2830b57cec5SDimitry Andric                              const MultiLevelTemplateArgumentList &TemplateArgs,
2840b57cec5SDimitry Andric                              const ModeAttr &Attr, Decl *New) {
285a7dea167SDimitry Andric   S.AddModeAttr(New, Attr, Attr.getMode(),
286a7dea167SDimitry Andric                 /*InInstantiation=*/true);
2870b57cec5SDimitry Andric }
2880b57cec5SDimitry Andric 
2890b57cec5SDimitry Andric /// Instantiation of 'declare simd' attribute and its arguments.
2900b57cec5SDimitry Andric static void instantiateOMPDeclareSimdDeclAttr(
2910b57cec5SDimitry Andric     Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
2920b57cec5SDimitry Andric     const OMPDeclareSimdDeclAttr &Attr, Decl *New) {
2930b57cec5SDimitry Andric   // Allow 'this' in clauses with varlists.
2940b57cec5SDimitry Andric   if (auto *FTD = dyn_cast<FunctionTemplateDecl>(New))
2950b57cec5SDimitry Andric     New = FTD->getTemplatedDecl();
2960b57cec5SDimitry Andric   auto *FD = cast<FunctionDecl>(New);
2970b57cec5SDimitry Andric   auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(FD->getDeclContext());
2980b57cec5SDimitry Andric   SmallVector<Expr *, 4> Uniforms, Aligneds, Alignments, Linears, Steps;
2990b57cec5SDimitry Andric   SmallVector<unsigned, 4> LinModifiers;
3000b57cec5SDimitry Andric 
3010b57cec5SDimitry Andric   auto SubstExpr = [&](Expr *E) -> ExprResult {
3020b57cec5SDimitry Andric     if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
3030b57cec5SDimitry Andric       if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
3040b57cec5SDimitry Andric         Sema::ContextRAII SavedContext(S, FD);
3050b57cec5SDimitry Andric         LocalInstantiationScope Local(S);
3060b57cec5SDimitry Andric         if (FD->getNumParams() > PVD->getFunctionScopeIndex())
3070b57cec5SDimitry Andric           Local.InstantiatedLocal(
3080b57cec5SDimitry Andric               PVD, FD->getParamDecl(PVD->getFunctionScopeIndex()));
3090b57cec5SDimitry Andric         return S.SubstExpr(E, TemplateArgs);
3100b57cec5SDimitry Andric       }
3110b57cec5SDimitry Andric     Sema::CXXThisScopeRAII ThisScope(S, ThisContext, Qualifiers(),
3120b57cec5SDimitry Andric                                      FD->isCXXInstanceMember());
3130b57cec5SDimitry Andric     return S.SubstExpr(E, TemplateArgs);
3140b57cec5SDimitry Andric   };
3150b57cec5SDimitry Andric 
3160b57cec5SDimitry Andric   // Substitute a single OpenMP clause, which is a potentially-evaluated
3170b57cec5SDimitry Andric   // full-expression.
3180b57cec5SDimitry Andric   auto Subst = [&](Expr *E) -> ExprResult {
3190b57cec5SDimitry Andric     EnterExpressionEvaluationContext Evaluated(
3200b57cec5SDimitry Andric         S, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
3210b57cec5SDimitry Andric     ExprResult Res = SubstExpr(E);
3220b57cec5SDimitry Andric     if (Res.isInvalid())
3230b57cec5SDimitry Andric       return Res;
3240b57cec5SDimitry Andric     return S.ActOnFinishFullExpr(Res.get(), false);
3250b57cec5SDimitry Andric   };
3260b57cec5SDimitry Andric 
3270b57cec5SDimitry Andric   ExprResult Simdlen;
3280b57cec5SDimitry Andric   if (auto *E = Attr.getSimdlen())
3290b57cec5SDimitry Andric     Simdlen = Subst(E);
3300b57cec5SDimitry Andric 
3310b57cec5SDimitry Andric   if (Attr.uniforms_size() > 0) {
3320b57cec5SDimitry Andric     for(auto *E : Attr.uniforms()) {
3330b57cec5SDimitry Andric       ExprResult Inst = Subst(E);
3340b57cec5SDimitry Andric       if (Inst.isInvalid())
3350b57cec5SDimitry Andric         continue;
3360b57cec5SDimitry Andric       Uniforms.push_back(Inst.get());
3370b57cec5SDimitry Andric     }
3380b57cec5SDimitry Andric   }
3390b57cec5SDimitry Andric 
3400b57cec5SDimitry Andric   auto AI = Attr.alignments_begin();
3410b57cec5SDimitry Andric   for (auto *E : Attr.aligneds()) {
3420b57cec5SDimitry Andric     ExprResult Inst = Subst(E);
3430b57cec5SDimitry Andric     if (Inst.isInvalid())
3440b57cec5SDimitry Andric       continue;
3450b57cec5SDimitry Andric     Aligneds.push_back(Inst.get());
3460b57cec5SDimitry Andric     Inst = ExprEmpty();
3470b57cec5SDimitry Andric     if (*AI)
3480b57cec5SDimitry Andric       Inst = S.SubstExpr(*AI, TemplateArgs);
3490b57cec5SDimitry Andric     Alignments.push_back(Inst.get());
3500b57cec5SDimitry Andric     ++AI;
3510b57cec5SDimitry Andric   }
3520b57cec5SDimitry Andric 
3530b57cec5SDimitry Andric   auto SI = Attr.steps_begin();
3540b57cec5SDimitry Andric   for (auto *E : Attr.linears()) {
3550b57cec5SDimitry Andric     ExprResult Inst = Subst(E);
3560b57cec5SDimitry Andric     if (Inst.isInvalid())
3570b57cec5SDimitry Andric       continue;
3580b57cec5SDimitry Andric     Linears.push_back(Inst.get());
3590b57cec5SDimitry Andric     Inst = ExprEmpty();
3600b57cec5SDimitry Andric     if (*SI)
3610b57cec5SDimitry Andric       Inst = S.SubstExpr(*SI, TemplateArgs);
3620b57cec5SDimitry Andric     Steps.push_back(Inst.get());
3630b57cec5SDimitry Andric     ++SI;
3640b57cec5SDimitry Andric   }
3650b57cec5SDimitry Andric   LinModifiers.append(Attr.modifiers_begin(), Attr.modifiers_end());
3660b57cec5SDimitry Andric   (void)S.ActOnOpenMPDeclareSimdDirective(
3670b57cec5SDimitry Andric       S.ConvertDeclToDeclGroup(New), Attr.getBranchState(), Simdlen.get(),
3680b57cec5SDimitry Andric       Uniforms, Aligneds, Alignments, Linears, LinModifiers, Steps,
3690b57cec5SDimitry Andric       Attr.getRange());
3700b57cec5SDimitry Andric }
3710b57cec5SDimitry Andric 
372a7dea167SDimitry Andric /// Instantiation of 'declare variant' attribute and its arguments.
373a7dea167SDimitry Andric static void instantiateOMPDeclareVariantAttr(
374a7dea167SDimitry Andric     Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
375a7dea167SDimitry Andric     const OMPDeclareVariantAttr &Attr, Decl *New) {
376a7dea167SDimitry Andric   // Allow 'this' in clauses with varlists.
377a7dea167SDimitry Andric   if (auto *FTD = dyn_cast<FunctionTemplateDecl>(New))
378a7dea167SDimitry Andric     New = FTD->getTemplatedDecl();
379a7dea167SDimitry Andric   auto *FD = cast<FunctionDecl>(New);
380a7dea167SDimitry Andric   auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(FD->getDeclContext());
381a7dea167SDimitry Andric 
382a7dea167SDimitry Andric   auto &&SubstExpr = [FD, ThisContext, &S, &TemplateArgs](Expr *E) {
383a7dea167SDimitry Andric     if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
384a7dea167SDimitry Andric       if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
385a7dea167SDimitry Andric         Sema::ContextRAII SavedContext(S, FD);
386a7dea167SDimitry Andric         LocalInstantiationScope Local(S);
387a7dea167SDimitry Andric         if (FD->getNumParams() > PVD->getFunctionScopeIndex())
388a7dea167SDimitry Andric           Local.InstantiatedLocal(
389a7dea167SDimitry Andric               PVD, FD->getParamDecl(PVD->getFunctionScopeIndex()));
390a7dea167SDimitry Andric         return S.SubstExpr(E, TemplateArgs);
391a7dea167SDimitry Andric       }
392a7dea167SDimitry Andric     Sema::CXXThisScopeRAII ThisScope(S, ThisContext, Qualifiers(),
393a7dea167SDimitry Andric                                      FD->isCXXInstanceMember());
394a7dea167SDimitry Andric     return S.SubstExpr(E, TemplateArgs);
395a7dea167SDimitry Andric   };
396a7dea167SDimitry Andric 
397a7dea167SDimitry Andric   // Substitute a single OpenMP clause, which is a potentially-evaluated
398a7dea167SDimitry Andric   // full-expression.
399a7dea167SDimitry Andric   auto &&Subst = [&SubstExpr, &S](Expr *E) {
400a7dea167SDimitry Andric     EnterExpressionEvaluationContext Evaluated(
401a7dea167SDimitry Andric         S, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
402a7dea167SDimitry Andric     ExprResult Res = SubstExpr(E);
403a7dea167SDimitry Andric     if (Res.isInvalid())
404a7dea167SDimitry Andric       return Res;
405a7dea167SDimitry Andric     return S.ActOnFinishFullExpr(Res.get(), false);
406a7dea167SDimitry Andric   };
407a7dea167SDimitry Andric 
408a7dea167SDimitry Andric   ExprResult VariantFuncRef;
409480093f4SDimitry Andric   if (Expr *E = Attr.getVariantFuncRef()) {
410480093f4SDimitry Andric     // Do not mark function as is used to prevent its emission if this is the
411480093f4SDimitry Andric     // only place where it is used.
412480093f4SDimitry Andric     EnterExpressionEvaluationContext Unevaluated(
413480093f4SDimitry Andric         S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
414a7dea167SDimitry Andric     VariantFuncRef = Subst(E);
415480093f4SDimitry Andric   }
416a7dea167SDimitry Andric 
4175ffd83dbSDimitry Andric   // Copy the template version of the OMPTraitInfo and run substitute on all
4185ffd83dbSDimitry Andric   // score and condition expressiosn.
4195ffd83dbSDimitry Andric   OMPTraitInfo &TI = S.getASTContext().getNewOMPTraitInfo();
4205ffd83dbSDimitry Andric   TI = *Attr.getTraitInfos();
4215ffd83dbSDimitry Andric 
4225ffd83dbSDimitry Andric   // Try to substitute template parameters in score and condition expressions.
4235ffd83dbSDimitry Andric   auto SubstScoreOrConditionExpr = [&S, Subst](Expr *&E, bool) {
4245ffd83dbSDimitry Andric     if (E) {
4255ffd83dbSDimitry Andric       EnterExpressionEvaluationContext Unevaluated(
4265ffd83dbSDimitry Andric           S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
4275ffd83dbSDimitry Andric       ExprResult ER = Subst(E);
4285ffd83dbSDimitry Andric       if (ER.isUsable())
4295ffd83dbSDimitry Andric         E = ER.get();
4305ffd83dbSDimitry Andric       else
4315ffd83dbSDimitry Andric         return true;
4325ffd83dbSDimitry Andric     }
4335ffd83dbSDimitry Andric     return false;
4345ffd83dbSDimitry Andric   };
4355ffd83dbSDimitry Andric   if (TI.anyScoreOrCondition(SubstScoreOrConditionExpr))
4365ffd83dbSDimitry Andric     return;
4375ffd83dbSDimitry Andric 
438e8d8bef9SDimitry Andric   Expr *E = VariantFuncRef.get();
439e8d8bef9SDimitry Andric   // Check function/variant ref for `omp declare variant` but not for `omp
440e8d8bef9SDimitry Andric   // begin declare variant` (which use implicit attributes).
441a7dea167SDimitry Andric   Optional<std::pair<FunctionDecl *, Expr *>> DeclVarData =
4425ffd83dbSDimitry Andric       S.checkOpenMPDeclareVariantFunction(S.ConvertDeclToDeclGroup(New),
4435ffd83dbSDimitry Andric                                           VariantFuncRef.get(), TI,
4445ffd83dbSDimitry Andric                                           Attr.getRange());
4455ffd83dbSDimitry Andric 
446a7dea167SDimitry Andric   if (!DeclVarData)
447a7dea167SDimitry Andric     return;
4485ffd83dbSDimitry Andric 
449e8d8bef9SDimitry Andric   E = DeclVarData.getValue().second;
450e8d8bef9SDimitry Andric   FD = DeclVarData.getValue().first;
451e8d8bef9SDimitry Andric 
452e8d8bef9SDimitry Andric   if (auto *VariantDRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts())) {
453e8d8bef9SDimitry Andric     if (auto *VariantFD = dyn_cast<FunctionDecl>(VariantDRE->getDecl())) {
454e8d8bef9SDimitry Andric       if (auto *VariantFTD = VariantFD->getDescribedFunctionTemplate()) {
455e8d8bef9SDimitry Andric         if (!VariantFTD->isThisDeclarationADefinition())
456e8d8bef9SDimitry Andric           return;
457e8d8bef9SDimitry Andric         Sema::TentativeAnalysisScope Trap(S);
458e8d8bef9SDimitry Andric         const TemplateArgumentList *TAL = TemplateArgumentList::CreateCopy(
459e8d8bef9SDimitry Andric             S.Context, TemplateArgs.getInnermost());
460e8d8bef9SDimitry Andric 
461e8d8bef9SDimitry Andric         auto *SubstFD = S.InstantiateFunctionDeclaration(VariantFTD, TAL,
462e8d8bef9SDimitry Andric                                                          New->getLocation());
463e8d8bef9SDimitry Andric         if (!SubstFD)
464e8d8bef9SDimitry Andric           return;
465e8d8bef9SDimitry Andric         QualType NewType = S.Context.mergeFunctionTypes(
466e8d8bef9SDimitry Andric             SubstFD->getType(), FD->getType(),
467e8d8bef9SDimitry Andric             /* OfBlockPointer */ false,
468e8d8bef9SDimitry Andric             /* Unqualified */ false, /* AllowCXX */ true);
469e8d8bef9SDimitry Andric         if (NewType.isNull())
470e8d8bef9SDimitry Andric           return;
471e8d8bef9SDimitry Andric         S.InstantiateFunctionDefinition(
472e8d8bef9SDimitry Andric             New->getLocation(), SubstFD, /* Recursive */ true,
473e8d8bef9SDimitry Andric             /* DefinitionRequired */ false, /* AtEndOfTU */ false);
474e8d8bef9SDimitry Andric         SubstFD->setInstantiationIsPending(!SubstFD->isDefined());
475e8d8bef9SDimitry Andric         E = DeclRefExpr::Create(S.Context, NestedNameSpecifierLoc(),
476e8d8bef9SDimitry Andric                                 SourceLocation(), SubstFD,
477e8d8bef9SDimitry Andric                                 /* RefersToEnclosingVariableOrCapture */ false,
478e8d8bef9SDimitry Andric                                 /* NameLoc */ SubstFD->getLocation(),
479fe6060f1SDimitry Andric                                 SubstFD->getType(), ExprValueKind::VK_PRValue);
480e8d8bef9SDimitry Andric       }
481e8d8bef9SDimitry Andric     }
482e8d8bef9SDimitry Andric   }
483e8d8bef9SDimitry Andric 
484e8d8bef9SDimitry Andric   S.ActOnOpenMPDeclareVariantDirective(FD, E, TI, Attr.getRange());
485a7dea167SDimitry Andric }
486a7dea167SDimitry Andric 
4870b57cec5SDimitry Andric static void instantiateDependentAMDGPUFlatWorkGroupSizeAttr(
4880b57cec5SDimitry Andric     Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
4890b57cec5SDimitry Andric     const AMDGPUFlatWorkGroupSizeAttr &Attr, Decl *New) {
4900b57cec5SDimitry Andric   // Both min and max expression are constant expressions.
4910b57cec5SDimitry Andric   EnterExpressionEvaluationContext Unevaluated(
4920b57cec5SDimitry Andric       S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
4930b57cec5SDimitry Andric 
4940b57cec5SDimitry Andric   ExprResult Result = S.SubstExpr(Attr.getMin(), TemplateArgs);
4950b57cec5SDimitry Andric   if (Result.isInvalid())
4960b57cec5SDimitry Andric     return;
4970b57cec5SDimitry Andric   Expr *MinExpr = Result.getAs<Expr>();
4980b57cec5SDimitry Andric 
4990b57cec5SDimitry Andric   Result = S.SubstExpr(Attr.getMax(), TemplateArgs);
5000b57cec5SDimitry Andric   if (Result.isInvalid())
5010b57cec5SDimitry Andric     return;
5020b57cec5SDimitry Andric   Expr *MaxExpr = Result.getAs<Expr>();
5030b57cec5SDimitry Andric 
504a7dea167SDimitry Andric   S.addAMDGPUFlatWorkGroupSizeAttr(New, Attr, MinExpr, MaxExpr);
5050b57cec5SDimitry Andric }
5060b57cec5SDimitry Andric 
5070b57cec5SDimitry Andric static ExplicitSpecifier
5080b57cec5SDimitry Andric instantiateExplicitSpecifier(Sema &S,
5090b57cec5SDimitry Andric                              const MultiLevelTemplateArgumentList &TemplateArgs,
5100b57cec5SDimitry Andric                              ExplicitSpecifier ES, FunctionDecl *New) {
5110b57cec5SDimitry Andric   if (!ES.getExpr())
5120b57cec5SDimitry Andric     return ES;
5130b57cec5SDimitry Andric   Expr *OldCond = ES.getExpr();
5140b57cec5SDimitry Andric   Expr *Cond = nullptr;
5150b57cec5SDimitry Andric   {
5160b57cec5SDimitry Andric     EnterExpressionEvaluationContext Unevaluated(
5170b57cec5SDimitry Andric         S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
5180b57cec5SDimitry Andric     ExprResult SubstResult = S.SubstExpr(OldCond, TemplateArgs);
5190b57cec5SDimitry Andric     if (SubstResult.isInvalid()) {
5200b57cec5SDimitry Andric       return ExplicitSpecifier::Invalid();
5210b57cec5SDimitry Andric     }
5220b57cec5SDimitry Andric     Cond = SubstResult.get();
5230b57cec5SDimitry Andric   }
5240b57cec5SDimitry Andric   ExplicitSpecifier Result(Cond, ES.getKind());
5250b57cec5SDimitry Andric   if (!Cond->isTypeDependent())
5260b57cec5SDimitry Andric     S.tryResolveExplicitSpecifier(Result);
5270b57cec5SDimitry Andric   return Result;
5280b57cec5SDimitry Andric }
5290b57cec5SDimitry Andric 
5300b57cec5SDimitry Andric static void instantiateDependentAMDGPUWavesPerEUAttr(
5310b57cec5SDimitry Andric     Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
5320b57cec5SDimitry Andric     const AMDGPUWavesPerEUAttr &Attr, Decl *New) {
5330b57cec5SDimitry Andric   // Both min and max expression are constant expressions.
5340b57cec5SDimitry Andric   EnterExpressionEvaluationContext Unevaluated(
5350b57cec5SDimitry Andric       S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
5360b57cec5SDimitry Andric 
5370b57cec5SDimitry Andric   ExprResult Result = S.SubstExpr(Attr.getMin(), TemplateArgs);
5380b57cec5SDimitry Andric   if (Result.isInvalid())
5390b57cec5SDimitry Andric     return;
5400b57cec5SDimitry Andric   Expr *MinExpr = Result.getAs<Expr>();
5410b57cec5SDimitry Andric 
5420b57cec5SDimitry Andric   Expr *MaxExpr = nullptr;
5430b57cec5SDimitry Andric   if (auto Max = Attr.getMax()) {
5440b57cec5SDimitry Andric     Result = S.SubstExpr(Max, TemplateArgs);
5450b57cec5SDimitry Andric     if (Result.isInvalid())
5460b57cec5SDimitry Andric       return;
5470b57cec5SDimitry Andric     MaxExpr = Result.getAs<Expr>();
5480b57cec5SDimitry Andric   }
5490b57cec5SDimitry Andric 
550a7dea167SDimitry Andric   S.addAMDGPUWavesPerEUAttr(New, Attr, MinExpr, MaxExpr);
5510b57cec5SDimitry Andric }
5520b57cec5SDimitry Andric 
553fe6060f1SDimitry Andric // This doesn't take any template parameters, but we have a custom action that
554fe6060f1SDimitry Andric // needs to happen when the kernel itself is instantiated. We need to run the
555fe6060f1SDimitry Andric // ItaniumMangler to mark the names required to name this kernel.
556fe6060f1SDimitry Andric static void instantiateDependentSYCLKernelAttr(
557fe6060f1SDimitry Andric     Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
558fe6060f1SDimitry Andric     const SYCLKernelAttr &Attr, Decl *New) {
559fe6060f1SDimitry Andric   // Functions cannot be partially specialized, so if we are being instantiated,
560fe6060f1SDimitry Andric   // we are obviously a complete specialization. Since this attribute is only
561fe6060f1SDimitry Andric   // valid on function template declarations, we know that this is a full
562fe6060f1SDimitry Andric   // instantiation of a kernel.
563fe6060f1SDimitry Andric   S.AddSYCLKernelLambda(cast<FunctionDecl>(New));
564fe6060f1SDimitry Andric 
565fe6060f1SDimitry Andric   // Evaluate whether this would change any of the already evaluated
566fe6060f1SDimitry Andric   // __builtin_sycl_unique_stable_name values.
567fe6060f1SDimitry Andric   for (auto &Itr : S.Context.SYCLUniqueStableNameEvaluatedValues) {
568fe6060f1SDimitry Andric     const std::string &CurName = Itr.first->ComputeName(S.Context);
569fe6060f1SDimitry Andric     if (Itr.second != CurName) {
570fe6060f1SDimitry Andric       S.Diag(New->getLocation(),
571fe6060f1SDimitry Andric              diag::err_kernel_invalidates_sycl_unique_stable_name);
572fe6060f1SDimitry Andric       S.Diag(Itr.first->getLocation(),
573fe6060f1SDimitry Andric              diag::note_sycl_unique_stable_name_evaluated_here);
574fe6060f1SDimitry Andric       // Update this so future diagnostics work correctly.
575fe6060f1SDimitry Andric       Itr.second = CurName;
576fe6060f1SDimitry Andric     }
577fe6060f1SDimitry Andric   }
578fe6060f1SDimitry Andric 
579fe6060f1SDimitry Andric   New->addAttr(Attr.clone(S.getASTContext()));
580fe6060f1SDimitry Andric }
581fe6060f1SDimitry Andric 
582e8d8bef9SDimitry Andric /// Determine whether the attribute A might be relevent to the declaration D.
583e8d8bef9SDimitry Andric /// If not, we can skip instantiating it. The attribute may or may not have
584e8d8bef9SDimitry Andric /// been instantiated yet.
585e8d8bef9SDimitry Andric static bool isRelevantAttr(Sema &S, const Decl *D, const Attr *A) {
586e8d8bef9SDimitry Andric   // 'preferred_name' is only relevant to the matching specialization of the
587e8d8bef9SDimitry Andric   // template.
588e8d8bef9SDimitry Andric   if (const auto *PNA = dyn_cast<PreferredNameAttr>(A)) {
589e8d8bef9SDimitry Andric     QualType T = PNA->getTypedefType();
590e8d8bef9SDimitry Andric     const auto *RD = cast<CXXRecordDecl>(D);
591e8d8bef9SDimitry Andric     if (!T->isDependentType() && !RD->isDependentContext() &&
592e8d8bef9SDimitry Andric         !declaresSameEntity(T->getAsCXXRecordDecl(), RD))
593e8d8bef9SDimitry Andric       return false;
594e8d8bef9SDimitry Andric     for (const auto *ExistingPNA : D->specific_attrs<PreferredNameAttr>())
595e8d8bef9SDimitry Andric       if (S.Context.hasSameType(ExistingPNA->getTypedefType(),
596e8d8bef9SDimitry Andric                                 PNA->getTypedefType()))
597e8d8bef9SDimitry Andric         return false;
598e8d8bef9SDimitry Andric     return true;
599e8d8bef9SDimitry Andric   }
600e8d8bef9SDimitry Andric 
601e8d8bef9SDimitry Andric   return true;
602e8d8bef9SDimitry Andric }
603e8d8bef9SDimitry Andric 
6040b57cec5SDimitry Andric void Sema::InstantiateAttrsForDecl(
6050b57cec5SDimitry Andric     const MultiLevelTemplateArgumentList &TemplateArgs, const Decl *Tmpl,
6060b57cec5SDimitry Andric     Decl *New, LateInstantiatedAttrVec *LateAttrs,
6070b57cec5SDimitry Andric     LocalInstantiationScope *OuterMostScope) {
6080b57cec5SDimitry Andric   if (NamedDecl *ND = dyn_cast<NamedDecl>(New)) {
609e8d8bef9SDimitry Andric     // FIXME: This function is called multiple times for the same template
610e8d8bef9SDimitry Andric     // specialization. We should only instantiate attributes that were added
611e8d8bef9SDimitry Andric     // since the previous instantiation.
6120b57cec5SDimitry Andric     for (const auto *TmplAttr : Tmpl->attrs()) {
613e8d8bef9SDimitry Andric       if (!isRelevantAttr(*this, New, TmplAttr))
614e8d8bef9SDimitry Andric         continue;
615e8d8bef9SDimitry Andric 
6160b57cec5SDimitry Andric       // FIXME: If any of the special case versions from InstantiateAttrs become
6170b57cec5SDimitry Andric       // applicable to template declaration, we'll need to add them here.
6180b57cec5SDimitry Andric       CXXThisScopeRAII ThisScope(
6190b57cec5SDimitry Andric           *this, dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext()),
6200b57cec5SDimitry Andric           Qualifiers(), ND->isCXXInstanceMember());
6210b57cec5SDimitry Andric 
6220b57cec5SDimitry Andric       Attr *NewAttr = sema::instantiateTemplateAttributeForDecl(
6230b57cec5SDimitry Andric           TmplAttr, Context, *this, TemplateArgs);
624e8d8bef9SDimitry Andric       if (NewAttr && isRelevantAttr(*this, New, NewAttr))
6250b57cec5SDimitry Andric         New->addAttr(NewAttr);
6260b57cec5SDimitry Andric     }
6270b57cec5SDimitry Andric   }
6280b57cec5SDimitry Andric }
6290b57cec5SDimitry Andric 
6300b57cec5SDimitry Andric static Sema::RetainOwnershipKind
6310b57cec5SDimitry Andric attrToRetainOwnershipKind(const Attr *A) {
6320b57cec5SDimitry Andric   switch (A->getKind()) {
6330b57cec5SDimitry Andric   case clang::attr::CFConsumed:
6340b57cec5SDimitry Andric     return Sema::RetainOwnershipKind::CF;
6350b57cec5SDimitry Andric   case clang::attr::OSConsumed:
6360b57cec5SDimitry Andric     return Sema::RetainOwnershipKind::OS;
6370b57cec5SDimitry Andric   case clang::attr::NSConsumed:
6380b57cec5SDimitry Andric     return Sema::RetainOwnershipKind::NS;
6390b57cec5SDimitry Andric   default:
6400b57cec5SDimitry Andric     llvm_unreachable("Wrong argument supplied");
6410b57cec5SDimitry Andric   }
6420b57cec5SDimitry Andric }
6430b57cec5SDimitry Andric 
6440b57cec5SDimitry Andric void Sema::InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs,
6450b57cec5SDimitry Andric                             const Decl *Tmpl, Decl *New,
6460b57cec5SDimitry Andric                             LateInstantiatedAttrVec *LateAttrs,
6470b57cec5SDimitry Andric                             LocalInstantiationScope *OuterMostScope) {
6480b57cec5SDimitry Andric   for (const auto *TmplAttr : Tmpl->attrs()) {
649e8d8bef9SDimitry Andric     if (!isRelevantAttr(*this, New, TmplAttr))
650e8d8bef9SDimitry Andric       continue;
651e8d8bef9SDimitry Andric 
6520b57cec5SDimitry Andric     // FIXME: This should be generalized to more than just the AlignedAttr.
6530b57cec5SDimitry Andric     const AlignedAttr *Aligned = dyn_cast<AlignedAttr>(TmplAttr);
6540b57cec5SDimitry Andric     if (Aligned && Aligned->isAlignmentDependent()) {
6550b57cec5SDimitry Andric       instantiateDependentAlignedAttr(*this, TemplateArgs, Aligned, New);
6560b57cec5SDimitry Andric       continue;
6570b57cec5SDimitry Andric     }
6580b57cec5SDimitry Andric 
659a7dea167SDimitry Andric     if (const auto *AssumeAligned = dyn_cast<AssumeAlignedAttr>(TmplAttr)) {
6600b57cec5SDimitry Andric       instantiateDependentAssumeAlignedAttr(*this, TemplateArgs, AssumeAligned, New);
6610b57cec5SDimitry Andric       continue;
6620b57cec5SDimitry Andric     }
6630b57cec5SDimitry Andric 
664a7dea167SDimitry Andric     if (const auto *AlignValue = dyn_cast<AlignValueAttr>(TmplAttr)) {
6650b57cec5SDimitry Andric       instantiateDependentAlignValueAttr(*this, TemplateArgs, AlignValue, New);
6660b57cec5SDimitry Andric       continue;
6670b57cec5SDimitry Andric     }
6680b57cec5SDimitry Andric 
6690b57cec5SDimitry Andric     if (const auto *AllocAlign = dyn_cast<AllocAlignAttr>(TmplAttr)) {
6700b57cec5SDimitry Andric       instantiateDependentAllocAlignAttr(*this, TemplateArgs, AllocAlign, New);
6710b57cec5SDimitry Andric       continue;
6720b57cec5SDimitry Andric     }
6730b57cec5SDimitry Andric 
674e8d8bef9SDimitry Andric     if (const auto *Annotate = dyn_cast<AnnotateAttr>(TmplAttr)) {
675e8d8bef9SDimitry Andric       instantiateDependentAnnotationAttr(*this, TemplateArgs, Annotate, New);
676e8d8bef9SDimitry Andric       continue;
677e8d8bef9SDimitry Andric     }
6780b57cec5SDimitry Andric 
6790b57cec5SDimitry Andric     if (const auto *EnableIf = dyn_cast<EnableIfAttr>(TmplAttr)) {
6800b57cec5SDimitry Andric       instantiateDependentEnableIfAttr(*this, TemplateArgs, EnableIf, Tmpl,
6810b57cec5SDimitry Andric                                        cast<FunctionDecl>(New));
6820b57cec5SDimitry Andric       continue;
6830b57cec5SDimitry Andric     }
6840b57cec5SDimitry Andric 
6850b57cec5SDimitry Andric     if (const auto *DiagnoseIf = dyn_cast<DiagnoseIfAttr>(TmplAttr)) {
6860b57cec5SDimitry Andric       instantiateDependentDiagnoseIfAttr(*this, TemplateArgs, DiagnoseIf, Tmpl,
6870b57cec5SDimitry Andric                                          cast<FunctionDecl>(New));
6880b57cec5SDimitry Andric       continue;
6890b57cec5SDimitry Andric     }
6900b57cec5SDimitry Andric 
691a7dea167SDimitry Andric     if (const auto *CUDALaunchBounds =
6920b57cec5SDimitry Andric             dyn_cast<CUDALaunchBoundsAttr>(TmplAttr)) {
6930b57cec5SDimitry Andric       instantiateDependentCUDALaunchBoundsAttr(*this, TemplateArgs,
6940b57cec5SDimitry Andric                                                *CUDALaunchBounds, New);
6950b57cec5SDimitry Andric       continue;
6960b57cec5SDimitry Andric     }
6970b57cec5SDimitry Andric 
698a7dea167SDimitry Andric     if (const auto *Mode = dyn_cast<ModeAttr>(TmplAttr)) {
6990b57cec5SDimitry Andric       instantiateDependentModeAttr(*this, TemplateArgs, *Mode, New);
7000b57cec5SDimitry Andric       continue;
7010b57cec5SDimitry Andric     }
7020b57cec5SDimitry Andric 
7030b57cec5SDimitry Andric     if (const auto *OMPAttr = dyn_cast<OMPDeclareSimdDeclAttr>(TmplAttr)) {
7040b57cec5SDimitry Andric       instantiateOMPDeclareSimdDeclAttr(*this, TemplateArgs, *OMPAttr, New);
7050b57cec5SDimitry Andric       continue;
7060b57cec5SDimitry Andric     }
7070b57cec5SDimitry Andric 
708a7dea167SDimitry Andric     if (const auto *OMPAttr = dyn_cast<OMPDeclareVariantAttr>(TmplAttr)) {
709a7dea167SDimitry Andric       instantiateOMPDeclareVariantAttr(*this, TemplateArgs, *OMPAttr, New);
710a7dea167SDimitry Andric       continue;
711a7dea167SDimitry Andric     }
712a7dea167SDimitry Andric 
713a7dea167SDimitry Andric     if (const auto *AMDGPUFlatWorkGroupSize =
7140b57cec5SDimitry Andric             dyn_cast<AMDGPUFlatWorkGroupSizeAttr>(TmplAttr)) {
7150b57cec5SDimitry Andric       instantiateDependentAMDGPUFlatWorkGroupSizeAttr(
7160b57cec5SDimitry Andric           *this, TemplateArgs, *AMDGPUFlatWorkGroupSize, New);
7170b57cec5SDimitry Andric     }
7180b57cec5SDimitry Andric 
719a7dea167SDimitry Andric     if (const auto *AMDGPUFlatWorkGroupSize =
7200b57cec5SDimitry Andric             dyn_cast<AMDGPUWavesPerEUAttr>(TmplAttr)) {
7210b57cec5SDimitry Andric       instantiateDependentAMDGPUWavesPerEUAttr(*this, TemplateArgs,
7220b57cec5SDimitry Andric                                                *AMDGPUFlatWorkGroupSize, New);
7230b57cec5SDimitry Andric     }
7240b57cec5SDimitry Andric 
7250b57cec5SDimitry Andric     // Existing DLL attribute on the instantiation takes precedence.
7260b57cec5SDimitry Andric     if (TmplAttr->getKind() == attr::DLLExport ||
7270b57cec5SDimitry Andric         TmplAttr->getKind() == attr::DLLImport) {
7280b57cec5SDimitry Andric       if (New->hasAttr<DLLExportAttr>() || New->hasAttr<DLLImportAttr>()) {
7290b57cec5SDimitry Andric         continue;
7300b57cec5SDimitry Andric       }
7310b57cec5SDimitry Andric     }
7320b57cec5SDimitry Andric 
733a7dea167SDimitry Andric     if (const auto *ABIAttr = dyn_cast<ParameterABIAttr>(TmplAttr)) {
734a7dea167SDimitry Andric       AddParameterABIAttr(New, *ABIAttr, ABIAttr->getABI());
7350b57cec5SDimitry Andric       continue;
7360b57cec5SDimitry Andric     }
7370b57cec5SDimitry Andric 
7380b57cec5SDimitry Andric     if (isa<NSConsumedAttr>(TmplAttr) || isa<OSConsumedAttr>(TmplAttr) ||
7390b57cec5SDimitry Andric         isa<CFConsumedAttr>(TmplAttr)) {
740a7dea167SDimitry Andric       AddXConsumedAttr(New, *TmplAttr, attrToRetainOwnershipKind(TmplAttr),
7410b57cec5SDimitry Andric                        /*template instantiation=*/true);
7420b57cec5SDimitry Andric       continue;
7430b57cec5SDimitry Andric     }
7440b57cec5SDimitry Andric 
745a7dea167SDimitry Andric     if (auto *A = dyn_cast<PointerAttr>(TmplAttr)) {
746a7dea167SDimitry Andric       if (!New->hasAttr<PointerAttr>())
747a7dea167SDimitry Andric         New->addAttr(A->clone(Context));
748a7dea167SDimitry Andric       continue;
749a7dea167SDimitry Andric     }
750a7dea167SDimitry Andric 
751a7dea167SDimitry Andric     if (auto *A = dyn_cast<OwnerAttr>(TmplAttr)) {
752a7dea167SDimitry Andric       if (!New->hasAttr<OwnerAttr>())
753a7dea167SDimitry Andric         New->addAttr(A->clone(Context));
754a7dea167SDimitry Andric       continue;
755a7dea167SDimitry Andric     }
756a7dea167SDimitry Andric 
757fe6060f1SDimitry Andric     if (auto *A = dyn_cast<SYCLKernelAttr>(TmplAttr)) {
758fe6060f1SDimitry Andric       instantiateDependentSYCLKernelAttr(*this, TemplateArgs, *A, New);
759fe6060f1SDimitry Andric       continue;
760fe6060f1SDimitry Andric     }
761fe6060f1SDimitry Andric 
7620b57cec5SDimitry Andric     assert(!TmplAttr->isPackExpansion());
7630b57cec5SDimitry Andric     if (TmplAttr->isLateParsed() && LateAttrs) {
7640b57cec5SDimitry Andric       // Late parsed attributes must be instantiated and attached after the
7650b57cec5SDimitry Andric       // enclosing class has been instantiated.  See Sema::InstantiateClass.
7660b57cec5SDimitry Andric       LocalInstantiationScope *Saved = nullptr;
7670b57cec5SDimitry Andric       if (CurrentInstantiationScope)
7680b57cec5SDimitry Andric         Saved = CurrentInstantiationScope->cloneScopes(OuterMostScope);
7690b57cec5SDimitry Andric       LateAttrs->push_back(LateInstantiatedAttribute(TmplAttr, Saved, New));
7700b57cec5SDimitry Andric     } else {
7710b57cec5SDimitry Andric       // Allow 'this' within late-parsed attributes.
772480093f4SDimitry Andric       auto *ND = cast<NamedDecl>(New);
773480093f4SDimitry Andric       auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext());
7740b57cec5SDimitry Andric       CXXThisScopeRAII ThisScope(*this, ThisContext, Qualifiers(),
775480093f4SDimitry Andric                                  ND->isCXXInstanceMember());
7760b57cec5SDimitry Andric 
7770b57cec5SDimitry Andric       Attr *NewAttr = sema::instantiateTemplateAttribute(TmplAttr, Context,
7780b57cec5SDimitry Andric                                                          *this, TemplateArgs);
779e8d8bef9SDimitry Andric       if (NewAttr && isRelevantAttr(*this, New, TmplAttr))
7800b57cec5SDimitry Andric         New->addAttr(NewAttr);
7810b57cec5SDimitry Andric     }
7820b57cec5SDimitry Andric   }
7830b57cec5SDimitry Andric }
7840b57cec5SDimitry Andric 
785e8d8bef9SDimitry Andric /// In the MS ABI, we need to instantiate default arguments of dllexported
786e8d8bef9SDimitry Andric /// default constructors along with the constructor definition. This allows IR
787e8d8bef9SDimitry Andric /// gen to emit a constructor closure which calls the default constructor with
788e8d8bef9SDimitry Andric /// its default arguments.
789e8d8bef9SDimitry Andric void Sema::InstantiateDefaultCtorDefaultArgs(CXXConstructorDecl *Ctor) {
790e8d8bef9SDimitry Andric   assert(Context.getTargetInfo().getCXXABI().isMicrosoft() &&
791e8d8bef9SDimitry Andric          Ctor->isDefaultConstructor());
792e8d8bef9SDimitry Andric   unsigned NumParams = Ctor->getNumParams();
793e8d8bef9SDimitry Andric   if (NumParams == 0)
794e8d8bef9SDimitry Andric     return;
795e8d8bef9SDimitry Andric   DLLExportAttr *Attr = Ctor->getAttr<DLLExportAttr>();
796e8d8bef9SDimitry Andric   if (!Attr)
797e8d8bef9SDimitry Andric     return;
798e8d8bef9SDimitry Andric   for (unsigned I = 0; I != NumParams; ++I) {
799e8d8bef9SDimitry Andric     (void)CheckCXXDefaultArgExpr(Attr->getLocation(), Ctor,
800e8d8bef9SDimitry Andric                                    Ctor->getParamDecl(I));
801e8d8bef9SDimitry Andric     DiscardCleanupsInEvaluationContext();
802e8d8bef9SDimitry Andric   }
803e8d8bef9SDimitry Andric }
804e8d8bef9SDimitry Andric 
8050b57cec5SDimitry Andric /// Get the previous declaration of a declaration for the purposes of template
8060b57cec5SDimitry Andric /// instantiation. If this finds a previous declaration, then the previous
8070b57cec5SDimitry Andric /// declaration of the instantiation of D should be an instantiation of the
8080b57cec5SDimitry Andric /// result of this function.
8090b57cec5SDimitry Andric template<typename DeclT>
8100b57cec5SDimitry Andric static DeclT *getPreviousDeclForInstantiation(DeclT *D) {
8110b57cec5SDimitry Andric   DeclT *Result = D->getPreviousDecl();
8120b57cec5SDimitry Andric 
8130b57cec5SDimitry Andric   // If the declaration is within a class, and the previous declaration was
8140b57cec5SDimitry Andric   // merged from a different definition of that class, then we don't have a
8150b57cec5SDimitry Andric   // previous declaration for the purpose of template instantiation.
8160b57cec5SDimitry Andric   if (Result && isa<CXXRecordDecl>(D->getDeclContext()) &&
8170b57cec5SDimitry Andric       D->getLexicalDeclContext() != Result->getLexicalDeclContext())
8180b57cec5SDimitry Andric     return nullptr;
8190b57cec5SDimitry Andric 
8200b57cec5SDimitry Andric   return Result;
8210b57cec5SDimitry Andric }
8220b57cec5SDimitry Andric 
8230b57cec5SDimitry Andric Decl *
8240b57cec5SDimitry Andric TemplateDeclInstantiator::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
8250b57cec5SDimitry Andric   llvm_unreachable("Translation units cannot be instantiated");
8260b57cec5SDimitry Andric }
8270b57cec5SDimitry Andric 
8280b57cec5SDimitry Andric Decl *
8290b57cec5SDimitry Andric TemplateDeclInstantiator::VisitPragmaCommentDecl(PragmaCommentDecl *D) {
8300b57cec5SDimitry Andric   llvm_unreachable("pragma comment cannot be instantiated");
8310b57cec5SDimitry Andric }
8320b57cec5SDimitry Andric 
8330b57cec5SDimitry Andric Decl *TemplateDeclInstantiator::VisitPragmaDetectMismatchDecl(
8340b57cec5SDimitry Andric     PragmaDetectMismatchDecl *D) {
8350b57cec5SDimitry Andric   llvm_unreachable("pragma comment cannot be instantiated");
8360b57cec5SDimitry Andric }
8370b57cec5SDimitry Andric 
8380b57cec5SDimitry Andric Decl *
8390b57cec5SDimitry Andric TemplateDeclInstantiator::VisitExternCContextDecl(ExternCContextDecl *D) {
8400b57cec5SDimitry Andric   llvm_unreachable("extern \"C\" context cannot be instantiated");
8410b57cec5SDimitry Andric }
8420b57cec5SDimitry Andric 
8435ffd83dbSDimitry Andric Decl *TemplateDeclInstantiator::VisitMSGuidDecl(MSGuidDecl *D) {
8445ffd83dbSDimitry Andric   llvm_unreachable("GUID declaration cannot be instantiated");
8455ffd83dbSDimitry Andric }
8465ffd83dbSDimitry Andric 
847e8d8bef9SDimitry Andric Decl *TemplateDeclInstantiator::VisitTemplateParamObjectDecl(
848e8d8bef9SDimitry Andric     TemplateParamObjectDecl *D) {
849e8d8bef9SDimitry Andric   llvm_unreachable("template parameter objects cannot be instantiated");
850e8d8bef9SDimitry Andric }
851e8d8bef9SDimitry Andric 
8520b57cec5SDimitry Andric Decl *
8530b57cec5SDimitry Andric TemplateDeclInstantiator::VisitLabelDecl(LabelDecl *D) {
8540b57cec5SDimitry Andric   LabelDecl *Inst = LabelDecl::Create(SemaRef.Context, Owner, D->getLocation(),
8550b57cec5SDimitry Andric                                       D->getIdentifier());
8560b57cec5SDimitry Andric   Owner->addDecl(Inst);
8570b57cec5SDimitry Andric   return Inst;
8580b57cec5SDimitry Andric }
8590b57cec5SDimitry Andric 
8600b57cec5SDimitry Andric Decl *
8610b57cec5SDimitry Andric TemplateDeclInstantiator::VisitNamespaceDecl(NamespaceDecl *D) {
8620b57cec5SDimitry Andric   llvm_unreachable("Namespaces cannot be instantiated");
8630b57cec5SDimitry Andric }
8640b57cec5SDimitry Andric 
8650b57cec5SDimitry Andric Decl *
8660b57cec5SDimitry Andric TemplateDeclInstantiator::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
8670b57cec5SDimitry Andric   NamespaceAliasDecl *Inst
8680b57cec5SDimitry Andric     = NamespaceAliasDecl::Create(SemaRef.Context, Owner,
8690b57cec5SDimitry Andric                                  D->getNamespaceLoc(),
8700b57cec5SDimitry Andric                                  D->getAliasLoc(),
8710b57cec5SDimitry Andric                                  D->getIdentifier(),
8720b57cec5SDimitry Andric                                  D->getQualifierLoc(),
8730b57cec5SDimitry Andric                                  D->getTargetNameLoc(),
8740b57cec5SDimitry Andric                                  D->getNamespace());
8750b57cec5SDimitry Andric   Owner->addDecl(Inst);
8760b57cec5SDimitry Andric   return Inst;
8770b57cec5SDimitry Andric }
8780b57cec5SDimitry Andric 
8790b57cec5SDimitry Andric Decl *TemplateDeclInstantiator::InstantiateTypedefNameDecl(TypedefNameDecl *D,
8800b57cec5SDimitry Andric                                                            bool IsTypeAlias) {
8810b57cec5SDimitry Andric   bool Invalid = false;
8820b57cec5SDimitry Andric   TypeSourceInfo *DI = D->getTypeSourceInfo();
8830b57cec5SDimitry Andric   if (DI->getType()->isInstantiationDependentType() ||
8840b57cec5SDimitry Andric       DI->getType()->isVariablyModifiedType()) {
8850b57cec5SDimitry Andric     DI = SemaRef.SubstType(DI, TemplateArgs,
8860b57cec5SDimitry Andric                            D->getLocation(), D->getDeclName());
8870b57cec5SDimitry Andric     if (!DI) {
8880b57cec5SDimitry Andric       Invalid = true;
8890b57cec5SDimitry Andric       DI = SemaRef.Context.getTrivialTypeSourceInfo(SemaRef.Context.IntTy);
8900b57cec5SDimitry Andric     }
8910b57cec5SDimitry Andric   } else {
8920b57cec5SDimitry Andric     SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
8930b57cec5SDimitry Andric   }
8940b57cec5SDimitry Andric 
895fe6060f1SDimitry Andric   // HACK: 2012-10-23 g++ has a bug where it gets the value kind of ?: wrong.
896fe6060f1SDimitry Andric   // libstdc++ relies upon this bug in its implementation of common_type.  If we
897fe6060f1SDimitry Andric   // happen to be processing that implementation, fake up the g++ ?:
898fe6060f1SDimitry Andric   // semantics. See LWG issue 2141 for more information on the bug.  The bugs
899fe6060f1SDimitry Andric   // are fixed in g++ and libstdc++ 4.9.0 (2014-04-22).
9000b57cec5SDimitry Andric   const DecltypeType *DT = DI->getType()->getAs<DecltypeType>();
9010b57cec5SDimitry Andric   CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D->getDeclContext());
9020b57cec5SDimitry Andric   if (DT && RD && isa<ConditionalOperator>(DT->getUnderlyingExpr()) &&
9030b57cec5SDimitry Andric       DT->isReferenceType() &&
9040b57cec5SDimitry Andric       RD->getEnclosingNamespaceContext() == SemaRef.getStdNamespace() &&
9050b57cec5SDimitry Andric       RD->getIdentifier() && RD->getIdentifier()->isStr("common_type") &&
9060b57cec5SDimitry Andric       D->getIdentifier() && D->getIdentifier()->isStr("type") &&
9070b57cec5SDimitry Andric       SemaRef.getSourceManager().isInSystemHeader(D->getBeginLoc()))
9080b57cec5SDimitry Andric     // Fold it to the (non-reference) type which g++ would have produced.
9090b57cec5SDimitry Andric     DI = SemaRef.Context.getTrivialTypeSourceInfo(
9100b57cec5SDimitry Andric       DI->getType().getNonReferenceType());
9110b57cec5SDimitry Andric 
9120b57cec5SDimitry Andric   // Create the new typedef
9130b57cec5SDimitry Andric   TypedefNameDecl *Typedef;
9140b57cec5SDimitry Andric   if (IsTypeAlias)
9150b57cec5SDimitry Andric     Typedef = TypeAliasDecl::Create(SemaRef.Context, Owner, D->getBeginLoc(),
9160b57cec5SDimitry Andric                                     D->getLocation(), D->getIdentifier(), DI);
9170b57cec5SDimitry Andric   else
9180b57cec5SDimitry Andric     Typedef = TypedefDecl::Create(SemaRef.Context, Owner, D->getBeginLoc(),
9190b57cec5SDimitry Andric                                   D->getLocation(), D->getIdentifier(), DI);
9200b57cec5SDimitry Andric   if (Invalid)
9210b57cec5SDimitry Andric     Typedef->setInvalidDecl();
9220b57cec5SDimitry Andric 
9230b57cec5SDimitry Andric   // If the old typedef was the name for linkage purposes of an anonymous
9240b57cec5SDimitry Andric   // tag decl, re-establish that relationship for the new typedef.
9250b57cec5SDimitry Andric   if (const TagType *oldTagType = D->getUnderlyingType()->getAs<TagType>()) {
9260b57cec5SDimitry Andric     TagDecl *oldTag = oldTagType->getDecl();
9270b57cec5SDimitry Andric     if (oldTag->getTypedefNameForAnonDecl() == D && !Invalid) {
9280b57cec5SDimitry Andric       TagDecl *newTag = DI->getType()->castAs<TagType>()->getDecl();
9290b57cec5SDimitry Andric       assert(!newTag->hasNameForLinkage());
9300b57cec5SDimitry Andric       newTag->setTypedefNameForAnonDecl(Typedef);
9310b57cec5SDimitry Andric     }
9320b57cec5SDimitry Andric   }
9330b57cec5SDimitry Andric 
9340b57cec5SDimitry Andric   if (TypedefNameDecl *Prev = getPreviousDeclForInstantiation(D)) {
9350b57cec5SDimitry Andric     NamedDecl *InstPrev = SemaRef.FindInstantiatedDecl(D->getLocation(), Prev,
9360b57cec5SDimitry Andric                                                        TemplateArgs);
9370b57cec5SDimitry Andric     if (!InstPrev)
9380b57cec5SDimitry Andric       return nullptr;
9390b57cec5SDimitry Andric 
9400b57cec5SDimitry Andric     TypedefNameDecl *InstPrevTypedef = cast<TypedefNameDecl>(InstPrev);
9410b57cec5SDimitry Andric 
9420b57cec5SDimitry Andric     // If the typedef types are not identical, reject them.
9430b57cec5SDimitry Andric     SemaRef.isIncompatibleTypedef(InstPrevTypedef, Typedef);
9440b57cec5SDimitry Andric 
9450b57cec5SDimitry Andric     Typedef->setPreviousDecl(InstPrevTypedef);
9460b57cec5SDimitry Andric   }
9470b57cec5SDimitry Andric 
9480b57cec5SDimitry Andric   SemaRef.InstantiateAttrs(TemplateArgs, D, Typedef);
9490b57cec5SDimitry Andric 
950a7dea167SDimitry Andric   if (D->getUnderlyingType()->getAs<DependentNameType>())
951a7dea167SDimitry Andric     SemaRef.inferGslPointerAttribute(Typedef);
952a7dea167SDimitry Andric 
9530b57cec5SDimitry Andric   Typedef->setAccess(D->getAccess());
9540b57cec5SDimitry Andric 
9550b57cec5SDimitry Andric   return Typedef;
9560b57cec5SDimitry Andric }
9570b57cec5SDimitry Andric 
9580b57cec5SDimitry Andric Decl *TemplateDeclInstantiator::VisitTypedefDecl(TypedefDecl *D) {
9590b57cec5SDimitry Andric   Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/false);
9600b57cec5SDimitry Andric   if (Typedef)
9610b57cec5SDimitry Andric     Owner->addDecl(Typedef);
9620b57cec5SDimitry Andric   return Typedef;
9630b57cec5SDimitry Andric }
9640b57cec5SDimitry Andric 
9650b57cec5SDimitry Andric Decl *TemplateDeclInstantiator::VisitTypeAliasDecl(TypeAliasDecl *D) {
9660b57cec5SDimitry Andric   Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/true);
9670b57cec5SDimitry Andric   if (Typedef)
9680b57cec5SDimitry Andric     Owner->addDecl(Typedef);
9690b57cec5SDimitry Andric   return Typedef;
9700b57cec5SDimitry Andric }
9710b57cec5SDimitry Andric 
9720b57cec5SDimitry Andric Decl *
9730b57cec5SDimitry Andric TemplateDeclInstantiator::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) {
9740b57cec5SDimitry Andric   // Create a local instantiation scope for this type alias template, which
9750b57cec5SDimitry Andric   // will contain the instantiations of the template parameters.
9760b57cec5SDimitry Andric   LocalInstantiationScope Scope(SemaRef);
9770b57cec5SDimitry Andric 
9780b57cec5SDimitry Andric   TemplateParameterList *TempParams = D->getTemplateParameters();
9790b57cec5SDimitry Andric   TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
9800b57cec5SDimitry Andric   if (!InstParams)
9810b57cec5SDimitry Andric     return nullptr;
9820b57cec5SDimitry Andric 
9830b57cec5SDimitry Andric   TypeAliasDecl *Pattern = D->getTemplatedDecl();
9840b57cec5SDimitry Andric 
9850b57cec5SDimitry Andric   TypeAliasTemplateDecl *PrevAliasTemplate = nullptr;
9860b57cec5SDimitry Andric   if (getPreviousDeclForInstantiation<TypedefNameDecl>(Pattern)) {
9870b57cec5SDimitry Andric     DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
9880b57cec5SDimitry Andric     if (!Found.empty()) {
9890b57cec5SDimitry Andric       PrevAliasTemplate = dyn_cast<TypeAliasTemplateDecl>(Found.front());
9900b57cec5SDimitry Andric     }
9910b57cec5SDimitry Andric   }
9920b57cec5SDimitry Andric 
9930b57cec5SDimitry Andric   TypeAliasDecl *AliasInst = cast_or_null<TypeAliasDecl>(
9940b57cec5SDimitry Andric     InstantiateTypedefNameDecl(Pattern, /*IsTypeAlias=*/true));
9950b57cec5SDimitry Andric   if (!AliasInst)
9960b57cec5SDimitry Andric     return nullptr;
9970b57cec5SDimitry Andric 
9980b57cec5SDimitry Andric   TypeAliasTemplateDecl *Inst
9990b57cec5SDimitry Andric     = TypeAliasTemplateDecl::Create(SemaRef.Context, Owner, D->getLocation(),
10000b57cec5SDimitry Andric                                     D->getDeclName(), InstParams, AliasInst);
10010b57cec5SDimitry Andric   AliasInst->setDescribedAliasTemplate(Inst);
10020b57cec5SDimitry Andric   if (PrevAliasTemplate)
10030b57cec5SDimitry Andric     Inst->setPreviousDecl(PrevAliasTemplate);
10040b57cec5SDimitry Andric 
10050b57cec5SDimitry Andric   Inst->setAccess(D->getAccess());
10060b57cec5SDimitry Andric 
10070b57cec5SDimitry Andric   if (!PrevAliasTemplate)
10080b57cec5SDimitry Andric     Inst->setInstantiatedFromMemberTemplate(D);
10090b57cec5SDimitry Andric 
10100b57cec5SDimitry Andric   Owner->addDecl(Inst);
10110b57cec5SDimitry Andric 
10120b57cec5SDimitry Andric   return Inst;
10130b57cec5SDimitry Andric }
10140b57cec5SDimitry Andric 
10150b57cec5SDimitry Andric Decl *TemplateDeclInstantiator::VisitBindingDecl(BindingDecl *D) {
10160b57cec5SDimitry Andric   auto *NewBD = BindingDecl::Create(SemaRef.Context, Owner, D->getLocation(),
10170b57cec5SDimitry Andric                                     D->getIdentifier());
10180b57cec5SDimitry Andric   NewBD->setReferenced(D->isReferenced());
10190b57cec5SDimitry Andric   SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewBD);
10200b57cec5SDimitry Andric   return NewBD;
10210b57cec5SDimitry Andric }
10220b57cec5SDimitry Andric 
10230b57cec5SDimitry Andric Decl *TemplateDeclInstantiator::VisitDecompositionDecl(DecompositionDecl *D) {
10240b57cec5SDimitry Andric   // Transform the bindings first.
10250b57cec5SDimitry Andric   SmallVector<BindingDecl*, 16> NewBindings;
10260b57cec5SDimitry Andric   for (auto *OldBD : D->bindings())
10270b57cec5SDimitry Andric     NewBindings.push_back(cast<BindingDecl>(VisitBindingDecl(OldBD)));
10280b57cec5SDimitry Andric   ArrayRef<BindingDecl*> NewBindingArray = NewBindings;
10290b57cec5SDimitry Andric 
10300b57cec5SDimitry Andric   auto *NewDD = cast_or_null<DecompositionDecl>(
10310b57cec5SDimitry Andric       VisitVarDecl(D, /*InstantiatingVarTemplate=*/false, &NewBindingArray));
10320b57cec5SDimitry Andric 
10330b57cec5SDimitry Andric   if (!NewDD || NewDD->isInvalidDecl())
10340b57cec5SDimitry Andric     for (auto *NewBD : NewBindings)
10350b57cec5SDimitry Andric       NewBD->setInvalidDecl();
10360b57cec5SDimitry Andric 
10370b57cec5SDimitry Andric   return NewDD;
10380b57cec5SDimitry Andric }
10390b57cec5SDimitry Andric 
10400b57cec5SDimitry Andric Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D) {
10410b57cec5SDimitry Andric   return VisitVarDecl(D, /*InstantiatingVarTemplate=*/false);
10420b57cec5SDimitry Andric }
10430b57cec5SDimitry Andric 
10440b57cec5SDimitry Andric Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D,
10450b57cec5SDimitry Andric                                              bool InstantiatingVarTemplate,
10460b57cec5SDimitry Andric                                              ArrayRef<BindingDecl*> *Bindings) {
10470b57cec5SDimitry Andric 
10480b57cec5SDimitry Andric   // Do substitution on the type of the declaration
10490b57cec5SDimitry Andric   TypeSourceInfo *DI = SemaRef.SubstType(
10500b57cec5SDimitry Andric       D->getTypeSourceInfo(), TemplateArgs, D->getTypeSpecStartLoc(),
10510b57cec5SDimitry Andric       D->getDeclName(), /*AllowDeducedTST*/true);
10520b57cec5SDimitry Andric   if (!DI)
10530b57cec5SDimitry Andric     return nullptr;
10540b57cec5SDimitry Andric 
10550b57cec5SDimitry Andric   if (DI->getType()->isFunctionType()) {
10560b57cec5SDimitry Andric     SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function)
10570b57cec5SDimitry Andric       << D->isStaticDataMember() << DI->getType();
10580b57cec5SDimitry Andric     return nullptr;
10590b57cec5SDimitry Andric   }
10600b57cec5SDimitry Andric 
10610b57cec5SDimitry Andric   DeclContext *DC = Owner;
10620b57cec5SDimitry Andric   if (D->isLocalExternDecl())
10630b57cec5SDimitry Andric     SemaRef.adjustContextForLocalExternDecl(DC);
10640b57cec5SDimitry Andric 
10650b57cec5SDimitry Andric   // Build the instantiated declaration.
10660b57cec5SDimitry Andric   VarDecl *Var;
10670b57cec5SDimitry Andric   if (Bindings)
10680b57cec5SDimitry Andric     Var = DecompositionDecl::Create(SemaRef.Context, DC, D->getInnerLocStart(),
10690b57cec5SDimitry Andric                                     D->getLocation(), DI->getType(), DI,
10700b57cec5SDimitry Andric                                     D->getStorageClass(), *Bindings);
10710b57cec5SDimitry Andric   else
10720b57cec5SDimitry Andric     Var = VarDecl::Create(SemaRef.Context, DC, D->getInnerLocStart(),
10730b57cec5SDimitry Andric                           D->getLocation(), D->getIdentifier(), DI->getType(),
10740b57cec5SDimitry Andric                           DI, D->getStorageClass());
10750b57cec5SDimitry Andric 
10760b57cec5SDimitry Andric   // In ARC, infer 'retaining' for variables of retainable type.
10770b57cec5SDimitry Andric   if (SemaRef.getLangOpts().ObjCAutoRefCount &&
10780b57cec5SDimitry Andric       SemaRef.inferObjCARCLifetime(Var))
10790b57cec5SDimitry Andric     Var->setInvalidDecl();
10800b57cec5SDimitry Andric 
1081480093f4SDimitry Andric   if (SemaRef.getLangOpts().OpenCL)
1082480093f4SDimitry Andric     SemaRef.deduceOpenCLAddressSpace(Var);
1083480093f4SDimitry Andric 
10840b57cec5SDimitry Andric   // Substitute the nested name specifier, if any.
10850b57cec5SDimitry Andric   if (SubstQualifier(D, Var))
10860b57cec5SDimitry Andric     return nullptr;
10870b57cec5SDimitry Andric 
10880b57cec5SDimitry Andric   SemaRef.BuildVariableInstantiation(Var, D, TemplateArgs, LateAttrs, Owner,
10890b57cec5SDimitry Andric                                      StartingScope, InstantiatingVarTemplate);
1090*69ade1e0SDimitry Andric   if (D->isNRVOVariable() && !Var->isInvalidDecl()) {
1091fe6060f1SDimitry Andric     QualType RT;
1092fe6060f1SDimitry Andric     if (auto *F = dyn_cast<FunctionDecl>(DC))
1093fe6060f1SDimitry Andric       RT = F->getReturnType();
1094fe6060f1SDimitry Andric     else if (isa<BlockDecl>(DC))
1095fe6060f1SDimitry Andric       RT = cast<FunctionType>(SemaRef.getCurBlock()->FunctionType)
1096fe6060f1SDimitry Andric                ->getReturnType();
1097fe6060f1SDimitry Andric     else
1098fe6060f1SDimitry Andric       llvm_unreachable("Unknown context type");
1099fe6060f1SDimitry Andric 
1100fe6060f1SDimitry Andric     // This is the last chance we have of checking copy elision eligibility
1101fe6060f1SDimitry Andric     // for functions in dependent contexts. The sema actions for building
1102fe6060f1SDimitry Andric     // the return statement during template instantiation will have no effect
1103fe6060f1SDimitry Andric     // regarding copy elision, since NRVO propagation runs on the scope exit
1104fe6060f1SDimitry Andric     // actions, and these are not run on instantiation.
1105fe6060f1SDimitry Andric     // This might run through some VarDecls which were returned from non-taken
1106fe6060f1SDimitry Andric     // 'if constexpr' branches, and these will end up being constructed on the
1107fe6060f1SDimitry Andric     // return slot even if they will never be returned, as a sort of accidental
1108fe6060f1SDimitry Andric     // 'optimization'. Notably, functions with 'auto' return types won't have it
1109fe6060f1SDimitry Andric     // deduced by this point. Coupled with the limitation described
1110fe6060f1SDimitry Andric     // previously, this makes it very hard to support copy elision for these.
1111fe6060f1SDimitry Andric     Sema::NamedReturnInfo Info = SemaRef.getNamedReturnInfo(Var);
1112fe6060f1SDimitry Andric     bool NRVO = SemaRef.getCopyElisionCandidate(Info, RT) != nullptr;
1113fe6060f1SDimitry Andric     Var->setNRVOVariable(NRVO);
11140b57cec5SDimitry Andric   }
11150b57cec5SDimitry Andric 
11160b57cec5SDimitry Andric   Var->setImplicit(D->isImplicit());
11170b57cec5SDimitry Andric 
11180b57cec5SDimitry Andric   if (Var->isStaticLocal())
11190b57cec5SDimitry Andric     SemaRef.CheckStaticLocalForDllExport(Var);
11200b57cec5SDimitry Andric 
11210b57cec5SDimitry Andric   return Var;
11220b57cec5SDimitry Andric }
11230b57cec5SDimitry Andric 
11240b57cec5SDimitry Andric Decl *TemplateDeclInstantiator::VisitAccessSpecDecl(AccessSpecDecl *D) {
11250b57cec5SDimitry Andric   AccessSpecDecl* AD
11260b57cec5SDimitry Andric     = AccessSpecDecl::Create(SemaRef.Context, D->getAccess(), Owner,
11270b57cec5SDimitry Andric                              D->getAccessSpecifierLoc(), D->getColonLoc());
11280b57cec5SDimitry Andric   Owner->addHiddenDecl(AD);
11290b57cec5SDimitry Andric   return AD;
11300b57cec5SDimitry Andric }
11310b57cec5SDimitry Andric 
11320b57cec5SDimitry Andric Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) {
11330b57cec5SDimitry Andric   bool Invalid = false;
11340b57cec5SDimitry Andric   TypeSourceInfo *DI = D->getTypeSourceInfo();
11350b57cec5SDimitry Andric   if (DI->getType()->isInstantiationDependentType() ||
11360b57cec5SDimitry Andric       DI->getType()->isVariablyModifiedType())  {
11370b57cec5SDimitry Andric     DI = SemaRef.SubstType(DI, TemplateArgs,
11380b57cec5SDimitry Andric                            D->getLocation(), D->getDeclName());
11390b57cec5SDimitry Andric     if (!DI) {
11400b57cec5SDimitry Andric       DI = D->getTypeSourceInfo();
11410b57cec5SDimitry Andric       Invalid = true;
11420b57cec5SDimitry Andric     } else if (DI->getType()->isFunctionType()) {
11430b57cec5SDimitry Andric       // C++ [temp.arg.type]p3:
11440b57cec5SDimitry Andric       //   If a declaration acquires a function type through a type
11450b57cec5SDimitry Andric       //   dependent on a template-parameter and this causes a
11460b57cec5SDimitry Andric       //   declaration that does not use the syntactic form of a
11470b57cec5SDimitry Andric       //   function declarator to have function type, the program is
11480b57cec5SDimitry Andric       //   ill-formed.
11490b57cec5SDimitry Andric       SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
11500b57cec5SDimitry Andric         << DI->getType();
11510b57cec5SDimitry Andric       Invalid = true;
11520b57cec5SDimitry Andric     }
11530b57cec5SDimitry Andric   } else {
11540b57cec5SDimitry Andric     SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
11550b57cec5SDimitry Andric   }
11560b57cec5SDimitry Andric 
11570b57cec5SDimitry Andric   Expr *BitWidth = D->getBitWidth();
11580b57cec5SDimitry Andric   if (Invalid)
11590b57cec5SDimitry Andric     BitWidth = nullptr;
11600b57cec5SDimitry Andric   else if (BitWidth) {
11610b57cec5SDimitry Andric     // The bit-width expression is a constant expression.
11620b57cec5SDimitry Andric     EnterExpressionEvaluationContext Unevaluated(
11630b57cec5SDimitry Andric         SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
11640b57cec5SDimitry Andric 
11650b57cec5SDimitry Andric     ExprResult InstantiatedBitWidth
11660b57cec5SDimitry Andric       = SemaRef.SubstExpr(BitWidth, TemplateArgs);
11670b57cec5SDimitry Andric     if (InstantiatedBitWidth.isInvalid()) {
11680b57cec5SDimitry Andric       Invalid = true;
11690b57cec5SDimitry Andric       BitWidth = nullptr;
11700b57cec5SDimitry Andric     } else
11710b57cec5SDimitry Andric       BitWidth = InstantiatedBitWidth.getAs<Expr>();
11720b57cec5SDimitry Andric   }
11730b57cec5SDimitry Andric 
11740b57cec5SDimitry Andric   FieldDecl *Field = SemaRef.CheckFieldDecl(D->getDeclName(),
11750b57cec5SDimitry Andric                                             DI->getType(), DI,
11760b57cec5SDimitry Andric                                             cast<RecordDecl>(Owner),
11770b57cec5SDimitry Andric                                             D->getLocation(),
11780b57cec5SDimitry Andric                                             D->isMutable(),
11790b57cec5SDimitry Andric                                             BitWidth,
11800b57cec5SDimitry Andric                                             D->getInClassInitStyle(),
11810b57cec5SDimitry Andric                                             D->getInnerLocStart(),
11820b57cec5SDimitry Andric                                             D->getAccess(),
11830b57cec5SDimitry Andric                                             nullptr);
11840b57cec5SDimitry Andric   if (!Field) {
11850b57cec5SDimitry Andric     cast<Decl>(Owner)->setInvalidDecl();
11860b57cec5SDimitry Andric     return nullptr;
11870b57cec5SDimitry Andric   }
11880b57cec5SDimitry Andric 
11890b57cec5SDimitry Andric   SemaRef.InstantiateAttrs(TemplateArgs, D, Field, LateAttrs, StartingScope);
11900b57cec5SDimitry Andric 
11910b57cec5SDimitry Andric   if (Field->hasAttrs())
11920b57cec5SDimitry Andric     SemaRef.CheckAlignasUnderalignment(Field);
11930b57cec5SDimitry Andric 
11940b57cec5SDimitry Andric   if (Invalid)
11950b57cec5SDimitry Andric     Field->setInvalidDecl();
11960b57cec5SDimitry Andric 
11970b57cec5SDimitry Andric   if (!Field->getDeclName()) {
11980b57cec5SDimitry Andric     // Keep track of where this decl came from.
11990b57cec5SDimitry Andric     SemaRef.Context.setInstantiatedFromUnnamedFieldDecl(Field, D);
12000b57cec5SDimitry Andric   }
12010b57cec5SDimitry Andric   if (CXXRecordDecl *Parent= dyn_cast<CXXRecordDecl>(Field->getDeclContext())) {
12020b57cec5SDimitry Andric     if (Parent->isAnonymousStructOrUnion() &&
12030b57cec5SDimitry Andric         Parent->getRedeclContext()->isFunctionOrMethod())
12040b57cec5SDimitry Andric       SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Field);
12050b57cec5SDimitry Andric   }
12060b57cec5SDimitry Andric 
12070b57cec5SDimitry Andric   Field->setImplicit(D->isImplicit());
12080b57cec5SDimitry Andric   Field->setAccess(D->getAccess());
12090b57cec5SDimitry Andric   Owner->addDecl(Field);
12100b57cec5SDimitry Andric 
12110b57cec5SDimitry Andric   return Field;
12120b57cec5SDimitry Andric }
12130b57cec5SDimitry Andric 
12140b57cec5SDimitry Andric Decl *TemplateDeclInstantiator::VisitMSPropertyDecl(MSPropertyDecl *D) {
12150b57cec5SDimitry Andric   bool Invalid = false;
12160b57cec5SDimitry Andric   TypeSourceInfo *DI = D->getTypeSourceInfo();
12170b57cec5SDimitry Andric 
12180b57cec5SDimitry Andric   if (DI->getType()->isVariablyModifiedType()) {
12190b57cec5SDimitry Andric     SemaRef.Diag(D->getLocation(), diag::err_property_is_variably_modified)
12200b57cec5SDimitry Andric       << D;
12210b57cec5SDimitry Andric     Invalid = true;
12220b57cec5SDimitry Andric   } else if (DI->getType()->isInstantiationDependentType())  {
12230b57cec5SDimitry Andric     DI = SemaRef.SubstType(DI, TemplateArgs,
12240b57cec5SDimitry Andric                            D->getLocation(), D->getDeclName());
12250b57cec5SDimitry Andric     if (!DI) {
12260b57cec5SDimitry Andric       DI = D->getTypeSourceInfo();
12270b57cec5SDimitry Andric       Invalid = true;
12280b57cec5SDimitry Andric     } else if (DI->getType()->isFunctionType()) {
12290b57cec5SDimitry Andric       // C++ [temp.arg.type]p3:
12300b57cec5SDimitry Andric       //   If a declaration acquires a function type through a type
12310b57cec5SDimitry Andric       //   dependent on a template-parameter and this causes a
12320b57cec5SDimitry Andric       //   declaration that does not use the syntactic form of a
12330b57cec5SDimitry Andric       //   function declarator to have function type, the program is
12340b57cec5SDimitry Andric       //   ill-formed.
12350b57cec5SDimitry Andric       SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
12360b57cec5SDimitry Andric       << DI->getType();
12370b57cec5SDimitry Andric       Invalid = true;
12380b57cec5SDimitry Andric     }
12390b57cec5SDimitry Andric   } else {
12400b57cec5SDimitry Andric     SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
12410b57cec5SDimitry Andric   }
12420b57cec5SDimitry Andric 
12430b57cec5SDimitry Andric   MSPropertyDecl *Property = MSPropertyDecl::Create(
12440b57cec5SDimitry Andric       SemaRef.Context, Owner, D->getLocation(), D->getDeclName(), DI->getType(),
12450b57cec5SDimitry Andric       DI, D->getBeginLoc(), D->getGetterId(), D->getSetterId());
12460b57cec5SDimitry Andric 
12470b57cec5SDimitry Andric   SemaRef.InstantiateAttrs(TemplateArgs, D, Property, LateAttrs,
12480b57cec5SDimitry Andric                            StartingScope);
12490b57cec5SDimitry Andric 
12500b57cec5SDimitry Andric   if (Invalid)
12510b57cec5SDimitry Andric     Property->setInvalidDecl();
12520b57cec5SDimitry Andric 
12530b57cec5SDimitry Andric   Property->setAccess(D->getAccess());
12540b57cec5SDimitry Andric   Owner->addDecl(Property);
12550b57cec5SDimitry Andric 
12560b57cec5SDimitry Andric   return Property;
12570b57cec5SDimitry Andric }
12580b57cec5SDimitry Andric 
12590b57cec5SDimitry Andric Decl *TemplateDeclInstantiator::VisitIndirectFieldDecl(IndirectFieldDecl *D) {
12600b57cec5SDimitry Andric   NamedDecl **NamedChain =
12610b57cec5SDimitry Andric     new (SemaRef.Context)NamedDecl*[D->getChainingSize()];
12620b57cec5SDimitry Andric 
12630b57cec5SDimitry Andric   int i = 0;
12640b57cec5SDimitry Andric   for (auto *PI : D->chain()) {
12650b57cec5SDimitry Andric     NamedDecl *Next = SemaRef.FindInstantiatedDecl(D->getLocation(), PI,
12660b57cec5SDimitry Andric                                               TemplateArgs);
12670b57cec5SDimitry Andric     if (!Next)
12680b57cec5SDimitry Andric       return nullptr;
12690b57cec5SDimitry Andric 
12700b57cec5SDimitry Andric     NamedChain[i++] = Next;
12710b57cec5SDimitry Andric   }
12720b57cec5SDimitry Andric 
12730b57cec5SDimitry Andric   QualType T = cast<FieldDecl>(NamedChain[i-1])->getType();
12740b57cec5SDimitry Andric   IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
12750b57cec5SDimitry Andric       SemaRef.Context, Owner, D->getLocation(), D->getIdentifier(), T,
12760b57cec5SDimitry Andric       {NamedChain, D->getChainingSize()});
12770b57cec5SDimitry Andric 
12780b57cec5SDimitry Andric   for (const auto *Attr : D->attrs())
12790b57cec5SDimitry Andric     IndirectField->addAttr(Attr->clone(SemaRef.Context));
12800b57cec5SDimitry Andric 
12810b57cec5SDimitry Andric   IndirectField->setImplicit(D->isImplicit());
12820b57cec5SDimitry Andric   IndirectField->setAccess(D->getAccess());
12830b57cec5SDimitry Andric   Owner->addDecl(IndirectField);
12840b57cec5SDimitry Andric   return IndirectField;
12850b57cec5SDimitry Andric }
12860b57cec5SDimitry Andric 
12870b57cec5SDimitry Andric Decl *TemplateDeclInstantiator::VisitFriendDecl(FriendDecl *D) {
12880b57cec5SDimitry Andric   // Handle friend type expressions by simply substituting template
12890b57cec5SDimitry Andric   // parameters into the pattern type and checking the result.
12900b57cec5SDimitry Andric   if (TypeSourceInfo *Ty = D->getFriendType()) {
12910b57cec5SDimitry Andric     TypeSourceInfo *InstTy;
12920b57cec5SDimitry Andric     // If this is an unsupported friend, don't bother substituting template
12930b57cec5SDimitry Andric     // arguments into it. The actual type referred to won't be used by any
12940b57cec5SDimitry Andric     // parts of Clang, and may not be valid for instantiating. Just use the
12950b57cec5SDimitry Andric     // same info for the instantiated friend.
12960b57cec5SDimitry Andric     if (D->isUnsupportedFriend()) {
12970b57cec5SDimitry Andric       InstTy = Ty;
12980b57cec5SDimitry Andric     } else {
12990b57cec5SDimitry Andric       InstTy = SemaRef.SubstType(Ty, TemplateArgs,
13000b57cec5SDimitry Andric                                  D->getLocation(), DeclarationName());
13010b57cec5SDimitry Andric     }
13020b57cec5SDimitry Andric     if (!InstTy)
13030b57cec5SDimitry Andric       return nullptr;
13040b57cec5SDimitry Andric 
13050b57cec5SDimitry Andric     FriendDecl *FD = SemaRef.CheckFriendTypeDecl(D->getBeginLoc(),
13060b57cec5SDimitry Andric                                                  D->getFriendLoc(), InstTy);
13070b57cec5SDimitry Andric     if (!FD)
13080b57cec5SDimitry Andric       return nullptr;
13090b57cec5SDimitry Andric 
13100b57cec5SDimitry Andric     FD->setAccess(AS_public);
13110b57cec5SDimitry Andric     FD->setUnsupportedFriend(D->isUnsupportedFriend());
13120b57cec5SDimitry Andric     Owner->addDecl(FD);
13130b57cec5SDimitry Andric     return FD;
13140b57cec5SDimitry Andric   }
13150b57cec5SDimitry Andric 
13160b57cec5SDimitry Andric   NamedDecl *ND = D->getFriendDecl();
13170b57cec5SDimitry Andric   assert(ND && "friend decl must be a decl or a type!");
13180b57cec5SDimitry Andric 
13190b57cec5SDimitry Andric   // All of the Visit implementations for the various potential friend
13200b57cec5SDimitry Andric   // declarations have to be carefully written to work for friend
13210b57cec5SDimitry Andric   // objects, with the most important detail being that the target
13220b57cec5SDimitry Andric   // decl should almost certainly not be placed in Owner.
13230b57cec5SDimitry Andric   Decl *NewND = Visit(ND);
13240b57cec5SDimitry Andric   if (!NewND) return nullptr;
13250b57cec5SDimitry Andric 
13260b57cec5SDimitry Andric   FriendDecl *FD =
13270b57cec5SDimitry Andric     FriendDecl::Create(SemaRef.Context, Owner, D->getLocation(),
13280b57cec5SDimitry Andric                        cast<NamedDecl>(NewND), D->getFriendLoc());
13290b57cec5SDimitry Andric   FD->setAccess(AS_public);
13300b57cec5SDimitry Andric   FD->setUnsupportedFriend(D->isUnsupportedFriend());
13310b57cec5SDimitry Andric   Owner->addDecl(FD);
13320b57cec5SDimitry Andric   return FD;
13330b57cec5SDimitry Andric }
13340b57cec5SDimitry Andric 
13350b57cec5SDimitry Andric Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) {
13360b57cec5SDimitry Andric   Expr *AssertExpr = D->getAssertExpr();
13370b57cec5SDimitry Andric 
13380b57cec5SDimitry Andric   // The expression in a static assertion is a constant expression.
13390b57cec5SDimitry Andric   EnterExpressionEvaluationContext Unevaluated(
13400b57cec5SDimitry Andric       SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
13410b57cec5SDimitry Andric 
13420b57cec5SDimitry Andric   ExprResult InstantiatedAssertExpr
13430b57cec5SDimitry Andric     = SemaRef.SubstExpr(AssertExpr, TemplateArgs);
13440b57cec5SDimitry Andric   if (InstantiatedAssertExpr.isInvalid())
13450b57cec5SDimitry Andric     return nullptr;
13460b57cec5SDimitry Andric 
13470b57cec5SDimitry Andric   return SemaRef.BuildStaticAssertDeclaration(D->getLocation(),
13480b57cec5SDimitry Andric                                               InstantiatedAssertExpr.get(),
13490b57cec5SDimitry Andric                                               D->getMessage(),
13500b57cec5SDimitry Andric                                               D->getRParenLoc(),
13510b57cec5SDimitry Andric                                               D->isFailed());
13520b57cec5SDimitry Andric }
13530b57cec5SDimitry Andric 
13540b57cec5SDimitry Andric Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) {
13550b57cec5SDimitry Andric   EnumDecl *PrevDecl = nullptr;
13560b57cec5SDimitry Andric   if (EnumDecl *PatternPrev = getPreviousDeclForInstantiation(D)) {
13570b57cec5SDimitry Andric     NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
13580b57cec5SDimitry Andric                                                    PatternPrev,
13590b57cec5SDimitry Andric                                                    TemplateArgs);
13600b57cec5SDimitry Andric     if (!Prev) return nullptr;
13610b57cec5SDimitry Andric     PrevDecl = cast<EnumDecl>(Prev);
13620b57cec5SDimitry Andric   }
13630b57cec5SDimitry Andric 
13640b57cec5SDimitry Andric   EnumDecl *Enum =
13650b57cec5SDimitry Andric       EnumDecl::Create(SemaRef.Context, Owner, D->getBeginLoc(),
13660b57cec5SDimitry Andric                        D->getLocation(), D->getIdentifier(), PrevDecl,
13670b57cec5SDimitry Andric                        D->isScoped(), D->isScopedUsingClassTag(), D->isFixed());
13680b57cec5SDimitry Andric   if (D->isFixed()) {
13690b57cec5SDimitry Andric     if (TypeSourceInfo *TI = D->getIntegerTypeSourceInfo()) {
13700b57cec5SDimitry Andric       // If we have type source information for the underlying type, it means it
13710b57cec5SDimitry Andric       // has been explicitly set by the user. Perform substitution on it before
13720b57cec5SDimitry Andric       // moving on.
13730b57cec5SDimitry Andric       SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
13740b57cec5SDimitry Andric       TypeSourceInfo *NewTI = SemaRef.SubstType(TI, TemplateArgs, UnderlyingLoc,
13750b57cec5SDimitry Andric                                                 DeclarationName());
13760b57cec5SDimitry Andric       if (!NewTI || SemaRef.CheckEnumUnderlyingType(NewTI))
13770b57cec5SDimitry Andric         Enum->setIntegerType(SemaRef.Context.IntTy);
13780b57cec5SDimitry Andric       else
13790b57cec5SDimitry Andric         Enum->setIntegerTypeSourceInfo(NewTI);
13800b57cec5SDimitry Andric     } else {
13810b57cec5SDimitry Andric       assert(!D->getIntegerType()->isDependentType()
13820b57cec5SDimitry Andric              && "Dependent type without type source info");
13830b57cec5SDimitry Andric       Enum->setIntegerType(D->getIntegerType());
13840b57cec5SDimitry Andric     }
13850b57cec5SDimitry Andric   }
13860b57cec5SDimitry Andric 
13870b57cec5SDimitry Andric   SemaRef.InstantiateAttrs(TemplateArgs, D, Enum);
13880b57cec5SDimitry Andric 
13890b57cec5SDimitry Andric   Enum->setInstantiationOfMemberEnum(D, TSK_ImplicitInstantiation);
13900b57cec5SDimitry Andric   Enum->setAccess(D->getAccess());
13910b57cec5SDimitry Andric   // Forward the mangling number from the template to the instantiated decl.
13920b57cec5SDimitry Andric   SemaRef.Context.setManglingNumber(Enum, SemaRef.Context.getManglingNumber(D));
13930b57cec5SDimitry Andric   // See if the old tag was defined along with a declarator.
13940b57cec5SDimitry Andric   // If it did, mark the new tag as being associated with that declarator.
13950b57cec5SDimitry Andric   if (DeclaratorDecl *DD = SemaRef.Context.getDeclaratorForUnnamedTagDecl(D))
13960b57cec5SDimitry Andric     SemaRef.Context.addDeclaratorForUnnamedTagDecl(Enum, DD);
13970b57cec5SDimitry Andric   // See if the old tag was defined along with a typedef.
13980b57cec5SDimitry Andric   // If it did, mark the new tag as being associated with that typedef.
13990b57cec5SDimitry Andric   if (TypedefNameDecl *TND = SemaRef.Context.getTypedefNameForUnnamedTagDecl(D))
14000b57cec5SDimitry Andric     SemaRef.Context.addTypedefNameForUnnamedTagDecl(Enum, TND);
14010b57cec5SDimitry Andric   if (SubstQualifier(D, Enum)) return nullptr;
14020b57cec5SDimitry Andric   Owner->addDecl(Enum);
14030b57cec5SDimitry Andric 
14040b57cec5SDimitry Andric   EnumDecl *Def = D->getDefinition();
14050b57cec5SDimitry Andric   if (Def && Def != D) {
14060b57cec5SDimitry Andric     // If this is an out-of-line definition of an enum member template, check
14070b57cec5SDimitry Andric     // that the underlying types match in the instantiation of both
14080b57cec5SDimitry Andric     // declarations.
14090b57cec5SDimitry Andric     if (TypeSourceInfo *TI = Def->getIntegerTypeSourceInfo()) {
14100b57cec5SDimitry Andric       SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
14110b57cec5SDimitry Andric       QualType DefnUnderlying =
14120b57cec5SDimitry Andric         SemaRef.SubstType(TI->getType(), TemplateArgs,
14130b57cec5SDimitry Andric                           UnderlyingLoc, DeclarationName());
14140b57cec5SDimitry Andric       SemaRef.CheckEnumRedeclaration(Def->getLocation(), Def->isScoped(),
14150b57cec5SDimitry Andric                                      DefnUnderlying, /*IsFixed=*/true, Enum);
14160b57cec5SDimitry Andric     }
14170b57cec5SDimitry Andric   }
14180b57cec5SDimitry Andric 
14190b57cec5SDimitry Andric   // C++11 [temp.inst]p1: The implicit instantiation of a class template
14200b57cec5SDimitry Andric   // specialization causes the implicit instantiation of the declarations, but
14210b57cec5SDimitry Andric   // not the definitions of scoped member enumerations.
14220b57cec5SDimitry Andric   //
14230b57cec5SDimitry Andric   // DR1484 clarifies that enumeration definitions inside of a template
14240b57cec5SDimitry Andric   // declaration aren't considered entities that can be separately instantiated
14250b57cec5SDimitry Andric   // from the rest of the entity they are declared inside of.
14260b57cec5SDimitry Andric   if (isDeclWithinFunction(D) ? D == Def : Def && !Enum->isScoped()) {
14270b57cec5SDimitry Andric     SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Enum);
14280b57cec5SDimitry Andric     InstantiateEnumDefinition(Enum, Def);
14290b57cec5SDimitry Andric   }
14300b57cec5SDimitry Andric 
14310b57cec5SDimitry Andric   return Enum;
14320b57cec5SDimitry Andric }
14330b57cec5SDimitry Andric 
14340b57cec5SDimitry Andric void TemplateDeclInstantiator::InstantiateEnumDefinition(
14350b57cec5SDimitry Andric     EnumDecl *Enum, EnumDecl *Pattern) {
14360b57cec5SDimitry Andric   Enum->startDefinition();
14370b57cec5SDimitry Andric 
14380b57cec5SDimitry Andric   // Update the location to refer to the definition.
14390b57cec5SDimitry Andric   Enum->setLocation(Pattern->getLocation());
14400b57cec5SDimitry Andric 
14410b57cec5SDimitry Andric   SmallVector<Decl*, 4> Enumerators;
14420b57cec5SDimitry Andric 
14430b57cec5SDimitry Andric   EnumConstantDecl *LastEnumConst = nullptr;
14440b57cec5SDimitry Andric   for (auto *EC : Pattern->enumerators()) {
14450b57cec5SDimitry Andric     // The specified value for the enumerator.
14460b57cec5SDimitry Andric     ExprResult Value((Expr *)nullptr);
14470b57cec5SDimitry Andric     if (Expr *UninstValue = EC->getInitExpr()) {
14480b57cec5SDimitry Andric       // The enumerator's value expression is a constant expression.
14490b57cec5SDimitry Andric       EnterExpressionEvaluationContext Unevaluated(
14500b57cec5SDimitry Andric           SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
14510b57cec5SDimitry Andric 
14520b57cec5SDimitry Andric       Value = SemaRef.SubstExpr(UninstValue, TemplateArgs);
14530b57cec5SDimitry Andric     }
14540b57cec5SDimitry Andric 
14550b57cec5SDimitry Andric     // Drop the initial value and continue.
14560b57cec5SDimitry Andric     bool isInvalid = false;
14570b57cec5SDimitry Andric     if (Value.isInvalid()) {
14580b57cec5SDimitry Andric       Value = nullptr;
14590b57cec5SDimitry Andric       isInvalid = true;
14600b57cec5SDimitry Andric     }
14610b57cec5SDimitry Andric 
14620b57cec5SDimitry Andric     EnumConstantDecl *EnumConst
14630b57cec5SDimitry Andric       = SemaRef.CheckEnumConstant(Enum, LastEnumConst,
14640b57cec5SDimitry Andric                                   EC->getLocation(), EC->getIdentifier(),
14650b57cec5SDimitry Andric                                   Value.get());
14660b57cec5SDimitry Andric 
14670b57cec5SDimitry Andric     if (isInvalid) {
14680b57cec5SDimitry Andric       if (EnumConst)
14690b57cec5SDimitry Andric         EnumConst->setInvalidDecl();
14700b57cec5SDimitry Andric       Enum->setInvalidDecl();
14710b57cec5SDimitry Andric     }
14720b57cec5SDimitry Andric 
14730b57cec5SDimitry Andric     if (EnumConst) {
14740b57cec5SDimitry Andric       SemaRef.InstantiateAttrs(TemplateArgs, EC, EnumConst);
14750b57cec5SDimitry Andric 
14760b57cec5SDimitry Andric       EnumConst->setAccess(Enum->getAccess());
14770b57cec5SDimitry Andric       Enum->addDecl(EnumConst);
14780b57cec5SDimitry Andric       Enumerators.push_back(EnumConst);
14790b57cec5SDimitry Andric       LastEnumConst = EnumConst;
14800b57cec5SDimitry Andric 
14810b57cec5SDimitry Andric       if (Pattern->getDeclContext()->isFunctionOrMethod() &&
14820b57cec5SDimitry Andric           !Enum->isScoped()) {
14830b57cec5SDimitry Andric         // If the enumeration is within a function or method, record the enum
14840b57cec5SDimitry Andric         // constant as a local.
14850b57cec5SDimitry Andric         SemaRef.CurrentInstantiationScope->InstantiatedLocal(EC, EnumConst);
14860b57cec5SDimitry Andric       }
14870b57cec5SDimitry Andric     }
14880b57cec5SDimitry Andric   }
14890b57cec5SDimitry Andric 
14900b57cec5SDimitry Andric   SemaRef.ActOnEnumBody(Enum->getLocation(), Enum->getBraceRange(), Enum,
14910b57cec5SDimitry Andric                         Enumerators, nullptr, ParsedAttributesView());
14920b57cec5SDimitry Andric }
14930b57cec5SDimitry Andric 
14940b57cec5SDimitry Andric Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) {
14950b57cec5SDimitry Andric   llvm_unreachable("EnumConstantDecls can only occur within EnumDecls.");
14960b57cec5SDimitry Andric }
14970b57cec5SDimitry Andric 
14980b57cec5SDimitry Andric Decl *
14990b57cec5SDimitry Andric TemplateDeclInstantiator::VisitBuiltinTemplateDecl(BuiltinTemplateDecl *D) {
15000b57cec5SDimitry Andric   llvm_unreachable("BuiltinTemplateDecls cannot be instantiated.");
15010b57cec5SDimitry Andric }
15020b57cec5SDimitry Andric 
15030b57cec5SDimitry Andric Decl *TemplateDeclInstantiator::VisitClassTemplateDecl(ClassTemplateDecl *D) {
15040b57cec5SDimitry Andric   bool isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
15050b57cec5SDimitry Andric 
15060b57cec5SDimitry Andric   // Create a local instantiation scope for this class template, which
15070b57cec5SDimitry Andric   // will contain the instantiations of the template parameters.
15080b57cec5SDimitry Andric   LocalInstantiationScope Scope(SemaRef);
15090b57cec5SDimitry Andric   TemplateParameterList *TempParams = D->getTemplateParameters();
15100b57cec5SDimitry Andric   TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
15110b57cec5SDimitry Andric   if (!InstParams)
15120b57cec5SDimitry Andric     return nullptr;
15130b57cec5SDimitry Andric 
15140b57cec5SDimitry Andric   CXXRecordDecl *Pattern = D->getTemplatedDecl();
15150b57cec5SDimitry Andric 
15160b57cec5SDimitry Andric   // Instantiate the qualifier.  We have to do this first in case
15170b57cec5SDimitry Andric   // we're a friend declaration, because if we are then we need to put
15180b57cec5SDimitry Andric   // the new declaration in the appropriate context.
15190b57cec5SDimitry Andric   NestedNameSpecifierLoc QualifierLoc = Pattern->getQualifierLoc();
15200b57cec5SDimitry Andric   if (QualifierLoc) {
15210b57cec5SDimitry Andric     QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
15220b57cec5SDimitry Andric                                                        TemplateArgs);
15230b57cec5SDimitry Andric     if (!QualifierLoc)
15240b57cec5SDimitry Andric       return nullptr;
15250b57cec5SDimitry Andric   }
15260b57cec5SDimitry Andric 
15270b57cec5SDimitry Andric   CXXRecordDecl *PrevDecl = nullptr;
15280b57cec5SDimitry Andric   ClassTemplateDecl *PrevClassTemplate = nullptr;
15290b57cec5SDimitry Andric 
15300b57cec5SDimitry Andric   if (!isFriend && getPreviousDeclForInstantiation(Pattern)) {
15310b57cec5SDimitry Andric     DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
15320b57cec5SDimitry Andric     if (!Found.empty()) {
15330b57cec5SDimitry Andric       PrevClassTemplate = dyn_cast<ClassTemplateDecl>(Found.front());
15340b57cec5SDimitry Andric       if (PrevClassTemplate)
15350b57cec5SDimitry Andric         PrevDecl = PrevClassTemplate->getTemplatedDecl();
15360b57cec5SDimitry Andric     }
15370b57cec5SDimitry Andric   }
15380b57cec5SDimitry Andric 
15390b57cec5SDimitry Andric   // If this isn't a friend, then it's a member template, in which
15400b57cec5SDimitry Andric   // case we just want to build the instantiation in the
15410b57cec5SDimitry Andric   // specialization.  If it is a friend, we want to build it in
15420b57cec5SDimitry Andric   // the appropriate context.
15430b57cec5SDimitry Andric   DeclContext *DC = Owner;
15440b57cec5SDimitry Andric   if (isFriend) {
15450b57cec5SDimitry Andric     if (QualifierLoc) {
15460b57cec5SDimitry Andric       CXXScopeSpec SS;
15470b57cec5SDimitry Andric       SS.Adopt(QualifierLoc);
15480b57cec5SDimitry Andric       DC = SemaRef.computeDeclContext(SS);
15490b57cec5SDimitry Andric       if (!DC) return nullptr;
15500b57cec5SDimitry Andric     } else {
15510b57cec5SDimitry Andric       DC = SemaRef.FindInstantiatedContext(Pattern->getLocation(),
15520b57cec5SDimitry Andric                                            Pattern->getDeclContext(),
15530b57cec5SDimitry Andric                                            TemplateArgs);
15540b57cec5SDimitry Andric     }
15550b57cec5SDimitry Andric 
15560b57cec5SDimitry Andric     // Look for a previous declaration of the template in the owning
15570b57cec5SDimitry Andric     // context.
15580b57cec5SDimitry Andric     LookupResult R(SemaRef, Pattern->getDeclName(), Pattern->getLocation(),
15590b57cec5SDimitry Andric                    Sema::LookupOrdinaryName,
15600b57cec5SDimitry Andric                    SemaRef.forRedeclarationInCurContext());
15610b57cec5SDimitry Andric     SemaRef.LookupQualifiedName(R, DC);
15620b57cec5SDimitry Andric 
15630b57cec5SDimitry Andric     if (R.isSingleResult()) {
15640b57cec5SDimitry Andric       PrevClassTemplate = R.getAsSingle<ClassTemplateDecl>();
15650b57cec5SDimitry Andric       if (PrevClassTemplate)
15660b57cec5SDimitry Andric         PrevDecl = PrevClassTemplate->getTemplatedDecl();
15670b57cec5SDimitry Andric     }
15680b57cec5SDimitry Andric 
15690b57cec5SDimitry Andric     if (!PrevClassTemplate && QualifierLoc) {
15700b57cec5SDimitry Andric       SemaRef.Diag(Pattern->getLocation(), diag::err_not_tag_in_scope)
15710b57cec5SDimitry Andric         << D->getTemplatedDecl()->getTagKind() << Pattern->getDeclName() << DC
15720b57cec5SDimitry Andric         << QualifierLoc.getSourceRange();
15730b57cec5SDimitry Andric       return nullptr;
15740b57cec5SDimitry Andric     }
15750b57cec5SDimitry Andric 
15760b57cec5SDimitry Andric     if (PrevClassTemplate) {
15770b57cec5SDimitry Andric       TemplateParameterList *PrevParams
15780b57cec5SDimitry Andric         = PrevClassTemplate->getMostRecentDecl()->getTemplateParameters();
15790b57cec5SDimitry Andric 
15800b57cec5SDimitry Andric       // Make sure the parameter lists match.
1581fe6060f1SDimitry Andric       if (!SemaRef.TemplateParameterListsAreEqual(InstParams, PrevParams, true,
1582fe6060f1SDimitry Andric                                                   Sema::TPL_TemplateMatch))
15830b57cec5SDimitry Andric         return nullptr;
15840b57cec5SDimitry Andric 
15850b57cec5SDimitry Andric       // Do some additional validation, then merge default arguments
15860b57cec5SDimitry Andric       // from the existing declarations.
1587fe6060f1SDimitry Andric       if (SemaRef.CheckTemplateParameterList(InstParams, PrevParams,
15880b57cec5SDimitry Andric                                              Sema::TPC_ClassTemplate))
15890b57cec5SDimitry Andric         return nullptr;
15900b57cec5SDimitry Andric     }
15910b57cec5SDimitry Andric   }
15920b57cec5SDimitry Andric 
15930b57cec5SDimitry Andric   CXXRecordDecl *RecordInst = CXXRecordDecl::Create(
15940b57cec5SDimitry Andric       SemaRef.Context, Pattern->getTagKind(), DC, Pattern->getBeginLoc(),
15950b57cec5SDimitry Andric       Pattern->getLocation(), Pattern->getIdentifier(), PrevDecl,
15960b57cec5SDimitry Andric       /*DelayTypeCreation=*/true);
15970b57cec5SDimitry Andric 
15980b57cec5SDimitry Andric   if (QualifierLoc)
15990b57cec5SDimitry Andric     RecordInst->setQualifierInfo(QualifierLoc);
16000b57cec5SDimitry Andric 
16010b57cec5SDimitry Andric   SemaRef.InstantiateAttrsForDecl(TemplateArgs, Pattern, RecordInst, LateAttrs,
16020b57cec5SDimitry Andric                                                               StartingScope);
16030b57cec5SDimitry Andric 
16040b57cec5SDimitry Andric   ClassTemplateDecl *Inst
16050b57cec5SDimitry Andric     = ClassTemplateDecl::Create(SemaRef.Context, DC, D->getLocation(),
16060b57cec5SDimitry Andric                                 D->getIdentifier(), InstParams, RecordInst);
16070b57cec5SDimitry Andric   assert(!(isFriend && Owner->isDependentContext()));
16080b57cec5SDimitry Andric   Inst->setPreviousDecl(PrevClassTemplate);
16090b57cec5SDimitry Andric 
16100b57cec5SDimitry Andric   RecordInst->setDescribedClassTemplate(Inst);
16110b57cec5SDimitry Andric 
16120b57cec5SDimitry Andric   if (isFriend) {
16130b57cec5SDimitry Andric     if (PrevClassTemplate)
16140b57cec5SDimitry Andric       Inst->setAccess(PrevClassTemplate->getAccess());
16150b57cec5SDimitry Andric     else
16160b57cec5SDimitry Andric       Inst->setAccess(D->getAccess());
16170b57cec5SDimitry Andric 
16180b57cec5SDimitry Andric     Inst->setObjectOfFriendDecl();
16190b57cec5SDimitry Andric     // TODO: do we want to track the instantiation progeny of this
16200b57cec5SDimitry Andric     // friend target decl?
16210b57cec5SDimitry Andric   } else {
16220b57cec5SDimitry Andric     Inst->setAccess(D->getAccess());
16230b57cec5SDimitry Andric     if (!PrevClassTemplate)
16240b57cec5SDimitry Andric       Inst->setInstantiatedFromMemberTemplate(D);
16250b57cec5SDimitry Andric   }
16260b57cec5SDimitry Andric 
16270b57cec5SDimitry Andric   // Trigger creation of the type for the instantiation.
16280b57cec5SDimitry Andric   SemaRef.Context.getInjectedClassNameType(RecordInst,
16290b57cec5SDimitry Andric                                     Inst->getInjectedClassNameSpecialization());
16300b57cec5SDimitry Andric 
16310b57cec5SDimitry Andric   // Finish handling of friends.
16320b57cec5SDimitry Andric   if (isFriend) {
16330b57cec5SDimitry Andric     DC->makeDeclVisibleInContext(Inst);
16340b57cec5SDimitry Andric     Inst->setLexicalDeclContext(Owner);
16350b57cec5SDimitry Andric     RecordInst->setLexicalDeclContext(Owner);
16360b57cec5SDimitry Andric     return Inst;
16370b57cec5SDimitry Andric   }
16380b57cec5SDimitry Andric 
16390b57cec5SDimitry Andric   if (D->isOutOfLine()) {
16400b57cec5SDimitry Andric     Inst->setLexicalDeclContext(D->getLexicalDeclContext());
16410b57cec5SDimitry Andric     RecordInst->setLexicalDeclContext(D->getLexicalDeclContext());
16420b57cec5SDimitry Andric   }
16430b57cec5SDimitry Andric 
16440b57cec5SDimitry Andric   Owner->addDecl(Inst);
16450b57cec5SDimitry Andric 
16460b57cec5SDimitry Andric   if (!PrevClassTemplate) {
16470b57cec5SDimitry Andric     // Queue up any out-of-line partial specializations of this member
16480b57cec5SDimitry Andric     // class template; the client will force their instantiation once
16490b57cec5SDimitry Andric     // the enclosing class has been instantiated.
16500b57cec5SDimitry Andric     SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
16510b57cec5SDimitry Andric     D->getPartialSpecializations(PartialSpecs);
16520b57cec5SDimitry Andric     for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
16530b57cec5SDimitry Andric       if (PartialSpecs[I]->getFirstDecl()->isOutOfLine())
16540b57cec5SDimitry Andric         OutOfLinePartialSpecs.push_back(std::make_pair(Inst, PartialSpecs[I]));
16550b57cec5SDimitry Andric   }
16560b57cec5SDimitry Andric 
16570b57cec5SDimitry Andric   return Inst;
16580b57cec5SDimitry Andric }
16590b57cec5SDimitry Andric 
16600b57cec5SDimitry Andric Decl *
16610b57cec5SDimitry Andric TemplateDeclInstantiator::VisitClassTemplatePartialSpecializationDecl(
16620b57cec5SDimitry Andric                                    ClassTemplatePartialSpecializationDecl *D) {
16630b57cec5SDimitry Andric   ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
16640b57cec5SDimitry Andric 
16650b57cec5SDimitry Andric   // Lookup the already-instantiated declaration in the instantiation
16660b57cec5SDimitry Andric   // of the class template and return that.
16670b57cec5SDimitry Andric   DeclContext::lookup_result Found
16680b57cec5SDimitry Andric     = Owner->lookup(ClassTemplate->getDeclName());
16690b57cec5SDimitry Andric   if (Found.empty())
16700b57cec5SDimitry Andric     return nullptr;
16710b57cec5SDimitry Andric 
16720b57cec5SDimitry Andric   ClassTemplateDecl *InstClassTemplate
16730b57cec5SDimitry Andric     = dyn_cast<ClassTemplateDecl>(Found.front());
16740b57cec5SDimitry Andric   if (!InstClassTemplate)
16750b57cec5SDimitry Andric     return nullptr;
16760b57cec5SDimitry Andric 
16770b57cec5SDimitry Andric   if (ClassTemplatePartialSpecializationDecl *Result
16780b57cec5SDimitry Andric         = InstClassTemplate->findPartialSpecInstantiatedFromMember(D))
16790b57cec5SDimitry Andric     return Result;
16800b57cec5SDimitry Andric 
16810b57cec5SDimitry Andric   return InstantiateClassTemplatePartialSpecialization(InstClassTemplate, D);
16820b57cec5SDimitry Andric }
16830b57cec5SDimitry Andric 
16840b57cec5SDimitry Andric Decl *TemplateDeclInstantiator::VisitVarTemplateDecl(VarTemplateDecl *D) {
16850b57cec5SDimitry Andric   assert(D->getTemplatedDecl()->isStaticDataMember() &&
16860b57cec5SDimitry Andric          "Only static data member templates are allowed.");
16870b57cec5SDimitry Andric 
16880b57cec5SDimitry Andric   // Create a local instantiation scope for this variable template, which
16890b57cec5SDimitry Andric   // will contain the instantiations of the template parameters.
16900b57cec5SDimitry Andric   LocalInstantiationScope Scope(SemaRef);
16910b57cec5SDimitry Andric   TemplateParameterList *TempParams = D->getTemplateParameters();
16920b57cec5SDimitry Andric   TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
16930b57cec5SDimitry Andric   if (!InstParams)
16940b57cec5SDimitry Andric     return nullptr;
16950b57cec5SDimitry Andric 
16960b57cec5SDimitry Andric   VarDecl *Pattern = D->getTemplatedDecl();
16970b57cec5SDimitry Andric   VarTemplateDecl *PrevVarTemplate = nullptr;
16980b57cec5SDimitry Andric 
16990b57cec5SDimitry Andric   if (getPreviousDeclForInstantiation(Pattern)) {
17000b57cec5SDimitry Andric     DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
17010b57cec5SDimitry Andric     if (!Found.empty())
17020b57cec5SDimitry Andric       PrevVarTemplate = dyn_cast<VarTemplateDecl>(Found.front());
17030b57cec5SDimitry Andric   }
17040b57cec5SDimitry Andric 
17050b57cec5SDimitry Andric   VarDecl *VarInst =
17060b57cec5SDimitry Andric       cast_or_null<VarDecl>(VisitVarDecl(Pattern,
17070b57cec5SDimitry Andric                                          /*InstantiatingVarTemplate=*/true));
17080b57cec5SDimitry Andric   if (!VarInst) return nullptr;
17090b57cec5SDimitry Andric 
17100b57cec5SDimitry Andric   DeclContext *DC = Owner;
17110b57cec5SDimitry Andric 
17120b57cec5SDimitry Andric   VarTemplateDecl *Inst = VarTemplateDecl::Create(
17130b57cec5SDimitry Andric       SemaRef.Context, DC, D->getLocation(), D->getIdentifier(), InstParams,
17140b57cec5SDimitry Andric       VarInst);
17150b57cec5SDimitry Andric   VarInst->setDescribedVarTemplate(Inst);
17160b57cec5SDimitry Andric   Inst->setPreviousDecl(PrevVarTemplate);
17170b57cec5SDimitry Andric 
17180b57cec5SDimitry Andric   Inst->setAccess(D->getAccess());
17190b57cec5SDimitry Andric   if (!PrevVarTemplate)
17200b57cec5SDimitry Andric     Inst->setInstantiatedFromMemberTemplate(D);
17210b57cec5SDimitry Andric 
17220b57cec5SDimitry Andric   if (D->isOutOfLine()) {
17230b57cec5SDimitry Andric     Inst->setLexicalDeclContext(D->getLexicalDeclContext());
17240b57cec5SDimitry Andric     VarInst->setLexicalDeclContext(D->getLexicalDeclContext());
17250b57cec5SDimitry Andric   }
17260b57cec5SDimitry Andric 
17270b57cec5SDimitry Andric   Owner->addDecl(Inst);
17280b57cec5SDimitry Andric 
17290b57cec5SDimitry Andric   if (!PrevVarTemplate) {
17300b57cec5SDimitry Andric     // Queue up any out-of-line partial specializations of this member
17310b57cec5SDimitry Andric     // variable template; the client will force their instantiation once
17320b57cec5SDimitry Andric     // the enclosing class has been instantiated.
17330b57cec5SDimitry Andric     SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs;
17340b57cec5SDimitry Andric     D->getPartialSpecializations(PartialSpecs);
17350b57cec5SDimitry Andric     for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
17360b57cec5SDimitry Andric       if (PartialSpecs[I]->getFirstDecl()->isOutOfLine())
17370b57cec5SDimitry Andric         OutOfLineVarPartialSpecs.push_back(
17380b57cec5SDimitry Andric             std::make_pair(Inst, PartialSpecs[I]));
17390b57cec5SDimitry Andric   }
17400b57cec5SDimitry Andric 
17410b57cec5SDimitry Andric   return Inst;
17420b57cec5SDimitry Andric }
17430b57cec5SDimitry Andric 
17440b57cec5SDimitry Andric Decl *TemplateDeclInstantiator::VisitVarTemplatePartialSpecializationDecl(
17450b57cec5SDimitry Andric     VarTemplatePartialSpecializationDecl *D) {
17460b57cec5SDimitry Andric   assert(D->isStaticDataMember() &&
17470b57cec5SDimitry Andric          "Only static data member templates are allowed.");
17480b57cec5SDimitry Andric 
17490b57cec5SDimitry Andric   VarTemplateDecl *VarTemplate = D->getSpecializedTemplate();
17500b57cec5SDimitry Andric 
17510b57cec5SDimitry Andric   // Lookup the already-instantiated declaration and return that.
17520b57cec5SDimitry Andric   DeclContext::lookup_result Found = Owner->lookup(VarTemplate->getDeclName());
17530b57cec5SDimitry Andric   assert(!Found.empty() && "Instantiation found nothing?");
17540b57cec5SDimitry Andric 
17550b57cec5SDimitry Andric   VarTemplateDecl *InstVarTemplate = dyn_cast<VarTemplateDecl>(Found.front());
17560b57cec5SDimitry Andric   assert(InstVarTemplate && "Instantiation did not find a variable template?");
17570b57cec5SDimitry Andric 
17580b57cec5SDimitry Andric   if (VarTemplatePartialSpecializationDecl *Result =
17590b57cec5SDimitry Andric           InstVarTemplate->findPartialSpecInstantiatedFromMember(D))
17600b57cec5SDimitry Andric     return Result;
17610b57cec5SDimitry Andric 
17620b57cec5SDimitry Andric   return InstantiateVarTemplatePartialSpecialization(InstVarTemplate, D);
17630b57cec5SDimitry Andric }
17640b57cec5SDimitry Andric 
17650b57cec5SDimitry Andric Decl *
17660b57cec5SDimitry Andric TemplateDeclInstantiator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
17670b57cec5SDimitry Andric   // Create a local instantiation scope for this function template, which
17680b57cec5SDimitry Andric   // will contain the instantiations of the template parameters and then get
17690b57cec5SDimitry Andric   // merged with the local instantiation scope for the function template
17700b57cec5SDimitry Andric   // itself.
17710b57cec5SDimitry Andric   LocalInstantiationScope Scope(SemaRef);
17720b57cec5SDimitry Andric 
17730b57cec5SDimitry Andric   TemplateParameterList *TempParams = D->getTemplateParameters();
17740b57cec5SDimitry Andric   TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
17750b57cec5SDimitry Andric   if (!InstParams)
17760b57cec5SDimitry Andric     return nullptr;
17770b57cec5SDimitry Andric 
17780b57cec5SDimitry Andric   FunctionDecl *Instantiated = nullptr;
17790b57cec5SDimitry Andric   if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(D->getTemplatedDecl()))
17800b57cec5SDimitry Andric     Instantiated = cast_or_null<FunctionDecl>(VisitCXXMethodDecl(DMethod,
17810b57cec5SDimitry Andric                                                                  InstParams));
17820b57cec5SDimitry Andric   else
17830b57cec5SDimitry Andric     Instantiated = cast_or_null<FunctionDecl>(VisitFunctionDecl(
17840b57cec5SDimitry Andric                                                           D->getTemplatedDecl(),
17850b57cec5SDimitry Andric                                                                 InstParams));
17860b57cec5SDimitry Andric 
17870b57cec5SDimitry Andric   if (!Instantiated)
17880b57cec5SDimitry Andric     return nullptr;
17890b57cec5SDimitry Andric 
17900b57cec5SDimitry Andric   // Link the instantiated function template declaration to the function
17910b57cec5SDimitry Andric   // template from which it was instantiated.
17920b57cec5SDimitry Andric   FunctionTemplateDecl *InstTemplate
17930b57cec5SDimitry Andric     = Instantiated->getDescribedFunctionTemplate();
17940b57cec5SDimitry Andric   InstTemplate->setAccess(D->getAccess());
17950b57cec5SDimitry Andric   assert(InstTemplate &&
17960b57cec5SDimitry Andric          "VisitFunctionDecl/CXXMethodDecl didn't create a template!");
17970b57cec5SDimitry Andric 
17980b57cec5SDimitry Andric   bool isFriend = (InstTemplate->getFriendObjectKind() != Decl::FOK_None);
17990b57cec5SDimitry Andric 
18000b57cec5SDimitry Andric   // Link the instantiation back to the pattern *unless* this is a
18010b57cec5SDimitry Andric   // non-definition friend declaration.
18020b57cec5SDimitry Andric   if (!InstTemplate->getInstantiatedFromMemberTemplate() &&
18030b57cec5SDimitry Andric       !(isFriend && !D->getTemplatedDecl()->isThisDeclarationADefinition()))
18040b57cec5SDimitry Andric     InstTemplate->setInstantiatedFromMemberTemplate(D);
18050b57cec5SDimitry Andric 
18060b57cec5SDimitry Andric   // Make declarations visible in the appropriate context.
18070b57cec5SDimitry Andric   if (!isFriend) {
18080b57cec5SDimitry Andric     Owner->addDecl(InstTemplate);
18090b57cec5SDimitry Andric   } else if (InstTemplate->getDeclContext()->isRecord() &&
18100b57cec5SDimitry Andric              !getPreviousDeclForInstantiation(D)) {
18110b57cec5SDimitry Andric     SemaRef.CheckFriendAccess(InstTemplate);
18120b57cec5SDimitry Andric   }
18130b57cec5SDimitry Andric 
18140b57cec5SDimitry Andric   return InstTemplate;
18150b57cec5SDimitry Andric }
18160b57cec5SDimitry Andric 
18170b57cec5SDimitry Andric Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) {
18180b57cec5SDimitry Andric   CXXRecordDecl *PrevDecl = nullptr;
18190b57cec5SDimitry Andric   if (D->isInjectedClassName())
18200b57cec5SDimitry Andric     PrevDecl = cast<CXXRecordDecl>(Owner);
18210b57cec5SDimitry Andric   else if (CXXRecordDecl *PatternPrev = getPreviousDeclForInstantiation(D)) {
18220b57cec5SDimitry Andric     NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
18230b57cec5SDimitry Andric                                                    PatternPrev,
18240b57cec5SDimitry Andric                                                    TemplateArgs);
18250b57cec5SDimitry Andric     if (!Prev) return nullptr;
18260b57cec5SDimitry Andric     PrevDecl = cast<CXXRecordDecl>(Prev);
18270b57cec5SDimitry Andric   }
18280b57cec5SDimitry Andric 
1829fe6060f1SDimitry Andric   CXXRecordDecl *Record = nullptr;
1830fe6060f1SDimitry Andric   if (D->isLambda())
1831fe6060f1SDimitry Andric     Record = CXXRecordDecl::CreateLambda(
1832fe6060f1SDimitry Andric         SemaRef.Context, Owner, D->getLambdaTypeInfo(), D->getLocation(),
1833fe6060f1SDimitry Andric         D->isDependentLambda(), D->isGenericLambda(),
1834fe6060f1SDimitry Andric         D->getLambdaCaptureDefault());
1835fe6060f1SDimitry Andric   else
1836fe6060f1SDimitry Andric     Record = CXXRecordDecl::Create(SemaRef.Context, D->getTagKind(), Owner,
1837fe6060f1SDimitry Andric                                    D->getBeginLoc(), D->getLocation(),
1838fe6060f1SDimitry Andric                                    D->getIdentifier(), PrevDecl);
18390b57cec5SDimitry Andric 
18400b57cec5SDimitry Andric   // Substitute the nested name specifier, if any.
18410b57cec5SDimitry Andric   if (SubstQualifier(D, Record))
18420b57cec5SDimitry Andric     return nullptr;
18430b57cec5SDimitry Andric 
18440b57cec5SDimitry Andric   SemaRef.InstantiateAttrsForDecl(TemplateArgs, D, Record, LateAttrs,
18450b57cec5SDimitry Andric                                                               StartingScope);
18460b57cec5SDimitry Andric 
18470b57cec5SDimitry Andric   Record->setImplicit(D->isImplicit());
18480b57cec5SDimitry Andric   // FIXME: Check against AS_none is an ugly hack to work around the issue that
18490b57cec5SDimitry Andric   // the tag decls introduced by friend class declarations don't have an access
18500b57cec5SDimitry Andric   // specifier. Remove once this area of the code gets sorted out.
18510b57cec5SDimitry Andric   if (D->getAccess() != AS_none)
18520b57cec5SDimitry Andric     Record->setAccess(D->getAccess());
18530b57cec5SDimitry Andric   if (!D->isInjectedClassName())
18540b57cec5SDimitry Andric     Record->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
18550b57cec5SDimitry Andric 
18560b57cec5SDimitry Andric   // If the original function was part of a friend declaration,
18570b57cec5SDimitry Andric   // inherit its namespace state.
18580b57cec5SDimitry Andric   if (D->getFriendObjectKind())
18590b57cec5SDimitry Andric     Record->setObjectOfFriendDecl();
18600b57cec5SDimitry Andric 
18610b57cec5SDimitry Andric   // Make sure that anonymous structs and unions are recorded.
18620b57cec5SDimitry Andric   if (D->isAnonymousStructOrUnion())
18630b57cec5SDimitry Andric     Record->setAnonymousStructOrUnion(true);
18640b57cec5SDimitry Andric 
18650b57cec5SDimitry Andric   if (D->isLocalClass())
18660b57cec5SDimitry Andric     SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Record);
18670b57cec5SDimitry Andric 
18680b57cec5SDimitry Andric   // Forward the mangling number from the template to the instantiated decl.
18690b57cec5SDimitry Andric   SemaRef.Context.setManglingNumber(Record,
18700b57cec5SDimitry Andric                                     SemaRef.Context.getManglingNumber(D));
18710b57cec5SDimitry Andric 
18720b57cec5SDimitry Andric   // See if the old tag was defined along with a declarator.
18730b57cec5SDimitry Andric   // If it did, mark the new tag as being associated with that declarator.
18740b57cec5SDimitry Andric   if (DeclaratorDecl *DD = SemaRef.Context.getDeclaratorForUnnamedTagDecl(D))
18750b57cec5SDimitry Andric     SemaRef.Context.addDeclaratorForUnnamedTagDecl(Record, DD);
18760b57cec5SDimitry Andric 
18770b57cec5SDimitry Andric   // See if the old tag was defined along with a typedef.
18780b57cec5SDimitry Andric   // If it did, mark the new tag as being associated with that typedef.
18790b57cec5SDimitry Andric   if (TypedefNameDecl *TND = SemaRef.Context.getTypedefNameForUnnamedTagDecl(D))
18800b57cec5SDimitry Andric     SemaRef.Context.addTypedefNameForUnnamedTagDecl(Record, TND);
18810b57cec5SDimitry Andric 
18820b57cec5SDimitry Andric   Owner->addDecl(Record);
18830b57cec5SDimitry Andric 
18840b57cec5SDimitry Andric   // DR1484 clarifies that the members of a local class are instantiated as part
18850b57cec5SDimitry Andric   // of the instantiation of their enclosing entity.
18860b57cec5SDimitry Andric   if (D->isCompleteDefinition() && D->isLocalClass()) {
18870b57cec5SDimitry Andric     Sema::LocalEagerInstantiationScope LocalInstantiations(SemaRef);
18880b57cec5SDimitry Andric 
18890b57cec5SDimitry Andric     SemaRef.InstantiateClass(D->getLocation(), Record, D, TemplateArgs,
18900b57cec5SDimitry Andric                              TSK_ImplicitInstantiation,
18910b57cec5SDimitry Andric                              /*Complain=*/true);
18920b57cec5SDimitry Andric 
18930b57cec5SDimitry Andric     // For nested local classes, we will instantiate the members when we
18940b57cec5SDimitry Andric     // reach the end of the outermost (non-nested) local class.
18950b57cec5SDimitry Andric     if (!D->isCXXClassMember())
18960b57cec5SDimitry Andric       SemaRef.InstantiateClassMembers(D->getLocation(), Record, TemplateArgs,
18970b57cec5SDimitry Andric                                       TSK_ImplicitInstantiation);
18980b57cec5SDimitry Andric 
18990b57cec5SDimitry Andric     // This class may have local implicit instantiations that need to be
19000b57cec5SDimitry Andric     // performed within this scope.
19010b57cec5SDimitry Andric     LocalInstantiations.perform();
19020b57cec5SDimitry Andric   }
19030b57cec5SDimitry Andric 
19040b57cec5SDimitry Andric   SemaRef.DiagnoseUnusedNestedTypedefs(Record);
19050b57cec5SDimitry Andric 
19060b57cec5SDimitry Andric   return Record;
19070b57cec5SDimitry Andric }
19080b57cec5SDimitry Andric 
19090b57cec5SDimitry Andric /// Adjust the given function type for an instantiation of the
19100b57cec5SDimitry Andric /// given declaration, to cope with modifications to the function's type that
19110b57cec5SDimitry Andric /// aren't reflected in the type-source information.
19120b57cec5SDimitry Andric ///
19130b57cec5SDimitry Andric /// \param D The declaration we're instantiating.
19140b57cec5SDimitry Andric /// \param TInfo The already-instantiated type.
19150b57cec5SDimitry Andric static QualType adjustFunctionTypeForInstantiation(ASTContext &Context,
19160b57cec5SDimitry Andric                                                    FunctionDecl *D,
19170b57cec5SDimitry Andric                                                    TypeSourceInfo *TInfo) {
19180b57cec5SDimitry Andric   const FunctionProtoType *OrigFunc
19190b57cec5SDimitry Andric     = D->getType()->castAs<FunctionProtoType>();
19200b57cec5SDimitry Andric   const FunctionProtoType *NewFunc
19210b57cec5SDimitry Andric     = TInfo->getType()->castAs<FunctionProtoType>();
19220b57cec5SDimitry Andric   if (OrigFunc->getExtInfo() == NewFunc->getExtInfo())
19230b57cec5SDimitry Andric     return TInfo->getType();
19240b57cec5SDimitry Andric 
19250b57cec5SDimitry Andric   FunctionProtoType::ExtProtoInfo NewEPI = NewFunc->getExtProtoInfo();
19260b57cec5SDimitry Andric   NewEPI.ExtInfo = OrigFunc->getExtInfo();
19270b57cec5SDimitry Andric   return Context.getFunctionType(NewFunc->getReturnType(),
19280b57cec5SDimitry Andric                                  NewFunc->getParamTypes(), NewEPI);
19290b57cec5SDimitry Andric }
19300b57cec5SDimitry Andric 
19310b57cec5SDimitry Andric /// Normal class members are of more specific types and therefore
19320b57cec5SDimitry Andric /// don't make it here.  This function serves three purposes:
19330b57cec5SDimitry Andric ///   1) instantiating function templates
19340b57cec5SDimitry Andric ///   2) substituting friend declarations
19350b57cec5SDimitry Andric ///   3) substituting deduction guide declarations for nested class templates
1936480093f4SDimitry Andric Decl *TemplateDeclInstantiator::VisitFunctionDecl(
1937480093f4SDimitry Andric     FunctionDecl *D, TemplateParameterList *TemplateParams,
1938480093f4SDimitry Andric     RewriteKind FunctionRewriteKind) {
19390b57cec5SDimitry Andric   // Check whether there is already a function template specialization for
19400b57cec5SDimitry Andric   // this declaration.
19410b57cec5SDimitry Andric   FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
19420b57cec5SDimitry Andric   if (FunctionTemplate && !TemplateParams) {
19430b57cec5SDimitry Andric     ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
19440b57cec5SDimitry Andric 
19450b57cec5SDimitry Andric     void *InsertPos = nullptr;
19460b57cec5SDimitry Andric     FunctionDecl *SpecFunc
19470b57cec5SDimitry Andric       = FunctionTemplate->findSpecialization(Innermost, InsertPos);
19480b57cec5SDimitry Andric 
19490b57cec5SDimitry Andric     // If we already have a function template specialization, return it.
19500b57cec5SDimitry Andric     if (SpecFunc)
19510b57cec5SDimitry Andric       return SpecFunc;
19520b57cec5SDimitry Andric   }
19530b57cec5SDimitry Andric 
19540b57cec5SDimitry Andric   bool isFriend;
19550b57cec5SDimitry Andric   if (FunctionTemplate)
19560b57cec5SDimitry Andric     isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
19570b57cec5SDimitry Andric   else
19580b57cec5SDimitry Andric     isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
19590b57cec5SDimitry Andric 
19600b57cec5SDimitry Andric   bool MergeWithParentScope = (TemplateParams != nullptr) ||
19610b57cec5SDimitry Andric     Owner->isFunctionOrMethod() ||
19620b57cec5SDimitry Andric     !(isa<Decl>(Owner) &&
19630b57cec5SDimitry Andric       cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
19640b57cec5SDimitry Andric   LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
19650b57cec5SDimitry Andric 
19660b57cec5SDimitry Andric   ExplicitSpecifier InstantiatedExplicitSpecifier;
19670b57cec5SDimitry Andric   if (auto *DGuide = dyn_cast<CXXDeductionGuideDecl>(D)) {
19680b57cec5SDimitry Andric     InstantiatedExplicitSpecifier = instantiateExplicitSpecifier(
19690b57cec5SDimitry Andric         SemaRef, TemplateArgs, DGuide->getExplicitSpecifier(), DGuide);
19700b57cec5SDimitry Andric     if (InstantiatedExplicitSpecifier.isInvalid())
19710b57cec5SDimitry Andric       return nullptr;
19720b57cec5SDimitry Andric   }
19730b57cec5SDimitry Andric 
19740b57cec5SDimitry Andric   SmallVector<ParmVarDecl *, 4> Params;
19750b57cec5SDimitry Andric   TypeSourceInfo *TInfo = SubstFunctionType(D, Params);
19760b57cec5SDimitry Andric   if (!TInfo)
19770b57cec5SDimitry Andric     return nullptr;
19780b57cec5SDimitry Andric   QualType T = adjustFunctionTypeForInstantiation(SemaRef.Context, D, TInfo);
19790b57cec5SDimitry Andric 
198013138422SDimitry Andric   if (TemplateParams && TemplateParams->size()) {
198113138422SDimitry Andric     auto *LastParam =
198213138422SDimitry Andric         dyn_cast<TemplateTypeParmDecl>(TemplateParams->asArray().back());
198313138422SDimitry Andric     if (LastParam && LastParam->isImplicit() &&
198413138422SDimitry Andric         LastParam->hasTypeConstraint()) {
198513138422SDimitry Andric       // In abbreviated templates, the type-constraints of invented template
198613138422SDimitry Andric       // type parameters are instantiated with the function type, invalidating
198713138422SDimitry Andric       // the TemplateParameterList which relied on the template type parameter
198813138422SDimitry Andric       // not having a type constraint. Recreate the TemplateParameterList with
198913138422SDimitry Andric       // the updated parameter list.
199013138422SDimitry Andric       TemplateParams = TemplateParameterList::Create(
199113138422SDimitry Andric           SemaRef.Context, TemplateParams->getTemplateLoc(),
199213138422SDimitry Andric           TemplateParams->getLAngleLoc(), TemplateParams->asArray(),
199313138422SDimitry Andric           TemplateParams->getRAngleLoc(), TemplateParams->getRequiresClause());
199413138422SDimitry Andric     }
199513138422SDimitry Andric   }
199613138422SDimitry Andric 
19970b57cec5SDimitry Andric   NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
19980b57cec5SDimitry Andric   if (QualifierLoc) {
19990b57cec5SDimitry Andric     QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
20000b57cec5SDimitry Andric                                                        TemplateArgs);
20010b57cec5SDimitry Andric     if (!QualifierLoc)
20020b57cec5SDimitry Andric       return nullptr;
20030b57cec5SDimitry Andric   }
20040b57cec5SDimitry Andric 
2005480093f4SDimitry Andric   // FIXME: Concepts: Do not substitute into constraint expressions
2006480093f4SDimitry Andric   Expr *TrailingRequiresClause = D->getTrailingRequiresClause();
2007480093f4SDimitry Andric   if (TrailingRequiresClause) {
200855e4f9d5SDimitry Andric     EnterExpressionEvaluationContext ConstantEvaluated(
200955e4f9d5SDimitry Andric         SemaRef, Sema::ExpressionEvaluationContext::Unevaluated);
2010480093f4SDimitry Andric     ExprResult SubstRC = SemaRef.SubstExpr(TrailingRequiresClause,
2011480093f4SDimitry Andric                                            TemplateArgs);
2012480093f4SDimitry Andric     if (SubstRC.isInvalid())
2013480093f4SDimitry Andric       return nullptr;
2014480093f4SDimitry Andric     TrailingRequiresClause = SubstRC.get();
2015480093f4SDimitry Andric     if (!SemaRef.CheckConstraintExpression(TrailingRequiresClause))
2016480093f4SDimitry Andric       return nullptr;
2017480093f4SDimitry Andric   }
2018480093f4SDimitry Andric 
20190b57cec5SDimitry Andric   // If we're instantiating a local function declaration, put the result
20200b57cec5SDimitry Andric   // in the enclosing namespace; otherwise we need to find the instantiated
20210b57cec5SDimitry Andric   // context.
20220b57cec5SDimitry Andric   DeclContext *DC;
20230b57cec5SDimitry Andric   if (D->isLocalExternDecl()) {
20240b57cec5SDimitry Andric     DC = Owner;
20250b57cec5SDimitry Andric     SemaRef.adjustContextForLocalExternDecl(DC);
20260b57cec5SDimitry Andric   } else if (isFriend && QualifierLoc) {
20270b57cec5SDimitry Andric     CXXScopeSpec SS;
20280b57cec5SDimitry Andric     SS.Adopt(QualifierLoc);
20290b57cec5SDimitry Andric     DC = SemaRef.computeDeclContext(SS);
20300b57cec5SDimitry Andric     if (!DC) return nullptr;
20310b57cec5SDimitry Andric   } else {
20320b57cec5SDimitry Andric     DC = SemaRef.FindInstantiatedContext(D->getLocation(), D->getDeclContext(),
20330b57cec5SDimitry Andric                                          TemplateArgs);
20340b57cec5SDimitry Andric   }
20350b57cec5SDimitry Andric 
20360b57cec5SDimitry Andric   DeclarationNameInfo NameInfo
20370b57cec5SDimitry Andric     = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
20380b57cec5SDimitry Andric 
2039480093f4SDimitry Andric   if (FunctionRewriteKind != RewriteKind::None)
2040480093f4SDimitry Andric     adjustForRewrite(FunctionRewriteKind, D, T, TInfo, NameInfo);
2041480093f4SDimitry Andric 
20420b57cec5SDimitry Andric   FunctionDecl *Function;
20430b57cec5SDimitry Andric   if (auto *DGuide = dyn_cast<CXXDeductionGuideDecl>(D)) {
20440b57cec5SDimitry Andric     Function = CXXDeductionGuideDecl::Create(
20450b57cec5SDimitry Andric         SemaRef.Context, DC, D->getInnerLocStart(),
20460b57cec5SDimitry Andric         InstantiatedExplicitSpecifier, NameInfo, T, TInfo,
20470b57cec5SDimitry Andric         D->getSourceRange().getEnd());
20480b57cec5SDimitry Andric     if (DGuide->isCopyDeductionCandidate())
20490b57cec5SDimitry Andric       cast<CXXDeductionGuideDecl>(Function)->setIsCopyDeductionCandidate();
20500b57cec5SDimitry Andric     Function->setAccess(D->getAccess());
20510b57cec5SDimitry Andric   } else {
20520b57cec5SDimitry Andric     Function = FunctionDecl::Create(
20530b57cec5SDimitry Andric         SemaRef.Context, DC, D->getInnerLocStart(), NameInfo, T, TInfo,
20540b57cec5SDimitry Andric         D->getCanonicalDecl()->getStorageClass(), D->isInlineSpecified(),
2055480093f4SDimitry Andric         D->hasWrittenPrototype(), D->getConstexprKind(),
2056480093f4SDimitry Andric         TrailingRequiresClause);
20570b57cec5SDimitry Andric     Function->setRangeEnd(D->getSourceRange().getEnd());
20580b57cec5SDimitry Andric   }
20590b57cec5SDimitry Andric 
20600b57cec5SDimitry Andric   if (D->isInlined())
20610b57cec5SDimitry Andric     Function->setImplicitlyInline();
20620b57cec5SDimitry Andric 
20630b57cec5SDimitry Andric   if (QualifierLoc)
20640b57cec5SDimitry Andric     Function->setQualifierInfo(QualifierLoc);
20650b57cec5SDimitry Andric 
20660b57cec5SDimitry Andric   if (D->isLocalExternDecl())
20670b57cec5SDimitry Andric     Function->setLocalExternDecl();
20680b57cec5SDimitry Andric 
20690b57cec5SDimitry Andric   DeclContext *LexicalDC = Owner;
20700b57cec5SDimitry Andric   if (!isFriend && D->isOutOfLine() && !D->isLocalExternDecl()) {
20710b57cec5SDimitry Andric     assert(D->getDeclContext()->isFileContext());
20720b57cec5SDimitry Andric     LexicalDC = D->getDeclContext();
20730b57cec5SDimitry Andric   }
20740b57cec5SDimitry Andric 
20750b57cec5SDimitry Andric   Function->setLexicalDeclContext(LexicalDC);
20760b57cec5SDimitry Andric 
20770b57cec5SDimitry Andric   // Attach the parameters
20780b57cec5SDimitry Andric   for (unsigned P = 0; P < Params.size(); ++P)
20790b57cec5SDimitry Andric     if (Params[P])
20800b57cec5SDimitry Andric       Params[P]->setOwningFunction(Function);
20810b57cec5SDimitry Andric   Function->setParams(Params);
20820b57cec5SDimitry Andric 
2083480093f4SDimitry Andric   if (TrailingRequiresClause)
2084480093f4SDimitry Andric     Function->setTrailingRequiresClause(TrailingRequiresClause);
2085480093f4SDimitry Andric 
20860b57cec5SDimitry Andric   if (TemplateParams) {
20870b57cec5SDimitry Andric     // Our resulting instantiation is actually a function template, since we
20880b57cec5SDimitry Andric     // are substituting only the outer template parameters. For example, given
20890b57cec5SDimitry Andric     //
20900b57cec5SDimitry Andric     //   template<typename T>
20910b57cec5SDimitry Andric     //   struct X {
20920b57cec5SDimitry Andric     //     template<typename U> friend void f(T, U);
20930b57cec5SDimitry Andric     //   };
20940b57cec5SDimitry Andric     //
20950b57cec5SDimitry Andric     //   X<int> x;
20960b57cec5SDimitry Andric     //
20970b57cec5SDimitry Andric     // We are instantiating the friend function template "f" within X<int>,
20980b57cec5SDimitry Andric     // which means substituting int for T, but leaving "f" as a friend function
20990b57cec5SDimitry Andric     // template.
21000b57cec5SDimitry Andric     // Build the function template itself.
21010b57cec5SDimitry Andric     FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, DC,
21020b57cec5SDimitry Andric                                                     Function->getLocation(),
21030b57cec5SDimitry Andric                                                     Function->getDeclName(),
21040b57cec5SDimitry Andric                                                     TemplateParams, Function);
21050b57cec5SDimitry Andric     Function->setDescribedFunctionTemplate(FunctionTemplate);
21060b57cec5SDimitry Andric 
21070b57cec5SDimitry Andric     FunctionTemplate->setLexicalDeclContext(LexicalDC);
21080b57cec5SDimitry Andric 
21090b57cec5SDimitry Andric     if (isFriend && D->isThisDeclarationADefinition()) {
21100b57cec5SDimitry Andric       FunctionTemplate->setInstantiatedFromMemberTemplate(
21110b57cec5SDimitry Andric                                            D->getDescribedFunctionTemplate());
21120b57cec5SDimitry Andric     }
21130b57cec5SDimitry Andric   } else if (FunctionTemplate) {
21140b57cec5SDimitry Andric     // Record this function template specialization.
21150b57cec5SDimitry Andric     ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
21160b57cec5SDimitry Andric     Function->setFunctionTemplateSpecialization(FunctionTemplate,
21170b57cec5SDimitry Andric                             TemplateArgumentList::CreateCopy(SemaRef.Context,
21180b57cec5SDimitry Andric                                                              Innermost),
21190b57cec5SDimitry Andric                                                 /*InsertPos=*/nullptr);
21200b57cec5SDimitry Andric   } else if (isFriend && D->isThisDeclarationADefinition()) {
21210b57cec5SDimitry Andric     // Do not connect the friend to the template unless it's actually a
21220b57cec5SDimitry Andric     // definition. We don't want non-template functions to be marked as being
21230b57cec5SDimitry Andric     // template instantiations.
21240b57cec5SDimitry Andric     Function->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
21250b57cec5SDimitry Andric   }
21260b57cec5SDimitry Andric 
2127e8d8bef9SDimitry Andric   if (isFriend) {
21280b57cec5SDimitry Andric     Function->setObjectOfFriendDecl();
2129e8d8bef9SDimitry Andric     if (FunctionTemplateDecl *FT = Function->getDescribedFunctionTemplate())
2130e8d8bef9SDimitry Andric       FT->setObjectOfFriendDecl();
2131e8d8bef9SDimitry Andric   }
21320b57cec5SDimitry Andric 
21330b57cec5SDimitry Andric   if (InitFunctionInstantiation(Function, D))
21340b57cec5SDimitry Andric     Function->setInvalidDecl();
21350b57cec5SDimitry Andric 
21360b57cec5SDimitry Andric   bool IsExplicitSpecialization = false;
21370b57cec5SDimitry Andric 
21380b57cec5SDimitry Andric   LookupResult Previous(
21390b57cec5SDimitry Andric       SemaRef, Function->getDeclName(), SourceLocation(),
21400b57cec5SDimitry Andric       D->isLocalExternDecl() ? Sema::LookupRedeclarationWithLinkage
21410b57cec5SDimitry Andric                              : Sema::LookupOrdinaryName,
21420b57cec5SDimitry Andric       D->isLocalExternDecl() ? Sema::ForExternalRedeclaration
21430b57cec5SDimitry Andric                              : SemaRef.forRedeclarationInCurContext());
21440b57cec5SDimitry Andric 
21450b57cec5SDimitry Andric   if (DependentFunctionTemplateSpecializationInfo *Info
21460b57cec5SDimitry Andric         = D->getDependentSpecializationInfo()) {
21470b57cec5SDimitry Andric     assert(isFriend && "non-friend has dependent specialization info?");
21480b57cec5SDimitry Andric 
21490b57cec5SDimitry Andric     // Instantiate the explicit template arguments.
21500b57cec5SDimitry Andric     TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(),
21510b57cec5SDimitry Andric                                           Info->getRAngleLoc());
21520b57cec5SDimitry Andric     if (SemaRef.Subst(Info->getTemplateArgs(), Info->getNumTemplateArgs(),
21530b57cec5SDimitry Andric                       ExplicitArgs, TemplateArgs))
21540b57cec5SDimitry Andric       return nullptr;
21550b57cec5SDimitry Andric 
21560b57cec5SDimitry Andric     // Map the candidate templates to their instantiations.
21570b57cec5SDimitry Andric     for (unsigned I = 0, E = Info->getNumTemplates(); I != E; ++I) {
21580b57cec5SDimitry Andric       Decl *Temp = SemaRef.FindInstantiatedDecl(D->getLocation(),
21590b57cec5SDimitry Andric                                                 Info->getTemplate(I),
21600b57cec5SDimitry Andric                                                 TemplateArgs);
21610b57cec5SDimitry Andric       if (!Temp) return nullptr;
21620b57cec5SDimitry Andric 
21630b57cec5SDimitry Andric       Previous.addDecl(cast<FunctionTemplateDecl>(Temp));
21640b57cec5SDimitry Andric     }
21650b57cec5SDimitry Andric 
21660b57cec5SDimitry Andric     if (SemaRef.CheckFunctionTemplateSpecialization(Function,
21670b57cec5SDimitry Andric                                                     &ExplicitArgs,
21680b57cec5SDimitry Andric                                                     Previous))
21690b57cec5SDimitry Andric       Function->setInvalidDecl();
21700b57cec5SDimitry Andric 
21710b57cec5SDimitry Andric     IsExplicitSpecialization = true;
21720b57cec5SDimitry Andric   } else if (const ASTTemplateArgumentListInfo *Info =
21730b57cec5SDimitry Andric                  D->getTemplateSpecializationArgsAsWritten()) {
21740b57cec5SDimitry Andric     // The name of this function was written as a template-id.
21750b57cec5SDimitry Andric     SemaRef.LookupQualifiedName(Previous, DC);
21760b57cec5SDimitry Andric 
21770b57cec5SDimitry Andric     // Instantiate the explicit template arguments.
21780b57cec5SDimitry Andric     TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(),
21790b57cec5SDimitry Andric                                           Info->getRAngleLoc());
21800b57cec5SDimitry Andric     if (SemaRef.Subst(Info->getTemplateArgs(), Info->getNumTemplateArgs(),
21810b57cec5SDimitry Andric                       ExplicitArgs, TemplateArgs))
21820b57cec5SDimitry Andric       return nullptr;
21830b57cec5SDimitry Andric 
21840b57cec5SDimitry Andric     if (SemaRef.CheckFunctionTemplateSpecialization(Function,
21850b57cec5SDimitry Andric                                                     &ExplicitArgs,
21860b57cec5SDimitry Andric                                                     Previous))
21870b57cec5SDimitry Andric       Function->setInvalidDecl();
21880b57cec5SDimitry Andric 
21890b57cec5SDimitry Andric     IsExplicitSpecialization = true;
21900b57cec5SDimitry Andric   } else if (TemplateParams || !FunctionTemplate) {
21910b57cec5SDimitry Andric     // Look only into the namespace where the friend would be declared to
21920b57cec5SDimitry Andric     // find a previous declaration. This is the innermost enclosing namespace,
21930b57cec5SDimitry Andric     // as described in ActOnFriendFunctionDecl.
21945ffd83dbSDimitry Andric     SemaRef.LookupQualifiedName(Previous, DC->getRedeclContext());
21950b57cec5SDimitry Andric 
21960b57cec5SDimitry Andric     // In C++, the previous declaration we find might be a tag type
21970b57cec5SDimitry Andric     // (class or enum). In this case, the new declaration will hide the
21980b57cec5SDimitry Andric     // tag type. Note that this does does not apply if we're declaring a
21990b57cec5SDimitry Andric     // typedef (C++ [dcl.typedef]p4).
22000b57cec5SDimitry Andric     if (Previous.isSingleTagDecl())
22010b57cec5SDimitry Andric       Previous.clear();
220216d6b3b3SDimitry Andric 
220316d6b3b3SDimitry Andric     // Filter out previous declarations that don't match the scope. The only
220416d6b3b3SDimitry Andric     // effect this has is to remove declarations found in inline namespaces
220516d6b3b3SDimitry Andric     // for friend declarations with unqualified names.
220616d6b3b3SDimitry Andric     SemaRef.FilterLookupForScope(Previous, DC, /*Scope*/ nullptr,
220716d6b3b3SDimitry Andric                                  /*ConsiderLinkage*/ true,
220816d6b3b3SDimitry Andric                                  QualifierLoc.hasQualifier());
22090b57cec5SDimitry Andric   }
22100b57cec5SDimitry Andric 
22110b57cec5SDimitry Andric   SemaRef.CheckFunctionDeclaration(/*Scope*/ nullptr, Function, Previous,
22120b57cec5SDimitry Andric                                    IsExplicitSpecialization);
22130b57cec5SDimitry Andric 
22140b57cec5SDimitry Andric   // Check the template parameter list against the previous declaration. The
22150b57cec5SDimitry Andric   // goal here is to pick up default arguments added since the friend was
22160b57cec5SDimitry Andric   // declared; we know the template parameter lists match, since otherwise
22170b57cec5SDimitry Andric   // we would not have picked this template as the previous declaration.
2218e8d8bef9SDimitry Andric   if (isFriend && TemplateParams && FunctionTemplate->getPreviousDecl()) {
22190b57cec5SDimitry Andric     SemaRef.CheckTemplateParameterList(
22200b57cec5SDimitry Andric         TemplateParams,
22210b57cec5SDimitry Andric         FunctionTemplate->getPreviousDecl()->getTemplateParameters(),
22220b57cec5SDimitry Andric         Function->isThisDeclarationADefinition()
22230b57cec5SDimitry Andric             ? Sema::TPC_FriendFunctionTemplateDefinition
22240b57cec5SDimitry Andric             : Sema::TPC_FriendFunctionTemplate);
22250b57cec5SDimitry Andric   }
2226e8d8bef9SDimitry Andric 
2227e8d8bef9SDimitry Andric   // If we're introducing a friend definition after the first use, trigger
2228e8d8bef9SDimitry Andric   // instantiation.
2229e8d8bef9SDimitry Andric   // FIXME: If this is a friend function template definition, we should check
2230e8d8bef9SDimitry Andric   // to see if any specializations have been used.
2231e8d8bef9SDimitry Andric   if (isFriend && D->isThisDeclarationADefinition() && Function->isUsed(false)) {
2232e8d8bef9SDimitry Andric     if (MemberSpecializationInfo *MSInfo =
2233e8d8bef9SDimitry Andric             Function->getMemberSpecializationInfo()) {
2234e8d8bef9SDimitry Andric       if (MSInfo->getPointOfInstantiation().isInvalid()) {
2235e8d8bef9SDimitry Andric         SourceLocation Loc = D->getLocation(); // FIXME
2236e8d8bef9SDimitry Andric         MSInfo->setPointOfInstantiation(Loc);
2237e8d8bef9SDimitry Andric         SemaRef.PendingLocalImplicitInstantiations.push_back(
2238e8d8bef9SDimitry Andric             std::make_pair(Function, Loc));
2239e8d8bef9SDimitry Andric       }
2240e8d8bef9SDimitry Andric     }
22410b57cec5SDimitry Andric   }
22420b57cec5SDimitry Andric 
2243480093f4SDimitry Andric   if (D->isExplicitlyDefaulted()) {
2244480093f4SDimitry Andric     if (SubstDefaultedFunction(Function, D))
2245480093f4SDimitry Andric       return nullptr;
2246480093f4SDimitry Andric   }
2247480093f4SDimitry Andric   if (D->isDeleted())
2248480093f4SDimitry Andric     SemaRef.SetDeclDeleted(Function, D->getLocation());
2249480093f4SDimitry Andric 
2250e8d8bef9SDimitry Andric   NamedDecl *PrincipalDecl =
2251e8d8bef9SDimitry Andric       (TemplateParams ? cast<NamedDecl>(FunctionTemplate) : Function);
2252e8d8bef9SDimitry Andric 
2253e8d8bef9SDimitry Andric   // If this declaration lives in a different context from its lexical context,
2254e8d8bef9SDimitry Andric   // add it to the corresponding lookup table.
2255e8d8bef9SDimitry Andric   if (isFriend ||
2256e8d8bef9SDimitry Andric       (Function->isLocalExternDecl() && !Function->getPreviousDecl()))
22570b57cec5SDimitry Andric     DC->makeDeclVisibleInContext(PrincipalDecl);
22580b57cec5SDimitry Andric 
22590b57cec5SDimitry Andric   if (Function->isOverloadedOperator() && !DC->isRecord() &&
22600b57cec5SDimitry Andric       PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
22610b57cec5SDimitry Andric     PrincipalDecl->setNonMemberOperator();
22620b57cec5SDimitry Andric 
22630b57cec5SDimitry Andric   return Function;
22640b57cec5SDimitry Andric }
22650b57cec5SDimitry Andric 
22660b57cec5SDimitry Andric Decl *TemplateDeclInstantiator::VisitCXXMethodDecl(
22670b57cec5SDimitry Andric     CXXMethodDecl *D, TemplateParameterList *TemplateParams,
2268480093f4SDimitry Andric     Optional<const ASTTemplateArgumentListInfo *> ClassScopeSpecializationArgs,
2269480093f4SDimitry Andric     RewriteKind FunctionRewriteKind) {
22700b57cec5SDimitry Andric   FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
22710b57cec5SDimitry Andric   if (FunctionTemplate && !TemplateParams) {
22720b57cec5SDimitry Andric     // We are creating a function template specialization from a function
22730b57cec5SDimitry Andric     // template. Check whether there is already a function template
22740b57cec5SDimitry Andric     // specialization for this particular set of template arguments.
22750b57cec5SDimitry Andric     ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
22760b57cec5SDimitry Andric 
22770b57cec5SDimitry Andric     void *InsertPos = nullptr;
22780b57cec5SDimitry Andric     FunctionDecl *SpecFunc
22790b57cec5SDimitry Andric       = FunctionTemplate->findSpecialization(Innermost, InsertPos);
22800b57cec5SDimitry Andric 
22810b57cec5SDimitry Andric     // If we already have a function template specialization, return it.
22820b57cec5SDimitry Andric     if (SpecFunc)
22830b57cec5SDimitry Andric       return SpecFunc;
22840b57cec5SDimitry Andric   }
22850b57cec5SDimitry Andric 
22860b57cec5SDimitry Andric   bool isFriend;
22870b57cec5SDimitry Andric   if (FunctionTemplate)
22880b57cec5SDimitry Andric     isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
22890b57cec5SDimitry Andric   else
22900b57cec5SDimitry Andric     isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
22910b57cec5SDimitry Andric 
22920b57cec5SDimitry Andric   bool MergeWithParentScope = (TemplateParams != nullptr) ||
22930b57cec5SDimitry Andric     !(isa<Decl>(Owner) &&
22940b57cec5SDimitry Andric       cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
22950b57cec5SDimitry Andric   LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
22960b57cec5SDimitry Andric 
22970b57cec5SDimitry Andric   // Instantiate enclosing template arguments for friends.
22980b57cec5SDimitry Andric   SmallVector<TemplateParameterList *, 4> TempParamLists;
22990b57cec5SDimitry Andric   unsigned NumTempParamLists = 0;
23000b57cec5SDimitry Andric   if (isFriend && (NumTempParamLists = D->getNumTemplateParameterLists())) {
23010b57cec5SDimitry Andric     TempParamLists.resize(NumTempParamLists);
23020b57cec5SDimitry Andric     for (unsigned I = 0; I != NumTempParamLists; ++I) {
23030b57cec5SDimitry Andric       TemplateParameterList *TempParams = D->getTemplateParameterList(I);
23040b57cec5SDimitry Andric       TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
23050b57cec5SDimitry Andric       if (!InstParams)
23060b57cec5SDimitry Andric         return nullptr;
23070b57cec5SDimitry Andric       TempParamLists[I] = InstParams;
23080b57cec5SDimitry Andric     }
23090b57cec5SDimitry Andric   }
23100b57cec5SDimitry Andric 
23110b57cec5SDimitry Andric   ExplicitSpecifier InstantiatedExplicitSpecifier =
23120b57cec5SDimitry Andric       instantiateExplicitSpecifier(SemaRef, TemplateArgs,
23130b57cec5SDimitry Andric                                    ExplicitSpecifier::getFromDecl(D), D);
23140b57cec5SDimitry Andric   if (InstantiatedExplicitSpecifier.isInvalid())
23150b57cec5SDimitry Andric     return nullptr;
23160b57cec5SDimitry Andric 
2317fe6060f1SDimitry Andric   // Implicit destructors/constructors created for local classes in
2318fe6060f1SDimitry Andric   // DeclareImplicit* (see SemaDeclCXX.cpp) might not have an associated TSI.
2319fe6060f1SDimitry Andric   // Unfortunately there isn't enough context in those functions to
2320fe6060f1SDimitry Andric   // conditionally populate the TSI without breaking non-template related use
2321fe6060f1SDimitry Andric   // cases. Populate TSIs prior to calling SubstFunctionType to make sure we get
2322fe6060f1SDimitry Andric   // a proper transformation.
2323fe6060f1SDimitry Andric   if (cast<CXXRecordDecl>(D->getParent())->isLambda() &&
2324fe6060f1SDimitry Andric       !D->getTypeSourceInfo() &&
2325fe6060f1SDimitry Andric       isa<CXXConstructorDecl, CXXDestructorDecl>(D)) {
2326fe6060f1SDimitry Andric     TypeSourceInfo *TSI =
2327fe6060f1SDimitry Andric         SemaRef.Context.getTrivialTypeSourceInfo(D->getType());
2328fe6060f1SDimitry Andric     D->setTypeSourceInfo(TSI);
2329fe6060f1SDimitry Andric   }
2330fe6060f1SDimitry Andric 
23310b57cec5SDimitry Andric   SmallVector<ParmVarDecl *, 4> Params;
23320b57cec5SDimitry Andric   TypeSourceInfo *TInfo = SubstFunctionType(D, Params);
23330b57cec5SDimitry Andric   if (!TInfo)
23340b57cec5SDimitry Andric     return nullptr;
23350b57cec5SDimitry Andric   QualType T = adjustFunctionTypeForInstantiation(SemaRef.Context, D, TInfo);
23360b57cec5SDimitry Andric 
233713138422SDimitry Andric   if (TemplateParams && TemplateParams->size()) {
233813138422SDimitry Andric     auto *LastParam =
233913138422SDimitry Andric         dyn_cast<TemplateTypeParmDecl>(TemplateParams->asArray().back());
234013138422SDimitry Andric     if (LastParam && LastParam->isImplicit() &&
234113138422SDimitry Andric         LastParam->hasTypeConstraint()) {
234213138422SDimitry Andric       // In abbreviated templates, the type-constraints of invented template
234313138422SDimitry Andric       // type parameters are instantiated with the function type, invalidating
234413138422SDimitry Andric       // the TemplateParameterList which relied on the template type parameter
234513138422SDimitry Andric       // not having a type constraint. Recreate the TemplateParameterList with
234613138422SDimitry Andric       // the updated parameter list.
234713138422SDimitry Andric       TemplateParams = TemplateParameterList::Create(
234813138422SDimitry Andric           SemaRef.Context, TemplateParams->getTemplateLoc(),
234913138422SDimitry Andric           TemplateParams->getLAngleLoc(), TemplateParams->asArray(),
235013138422SDimitry Andric           TemplateParams->getRAngleLoc(), TemplateParams->getRequiresClause());
235113138422SDimitry Andric     }
235213138422SDimitry Andric   }
235313138422SDimitry Andric 
23540b57cec5SDimitry Andric   NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
23550b57cec5SDimitry Andric   if (QualifierLoc) {
23560b57cec5SDimitry Andric     QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
23570b57cec5SDimitry Andric                                                  TemplateArgs);
23580b57cec5SDimitry Andric     if (!QualifierLoc)
23590b57cec5SDimitry Andric       return nullptr;
23600b57cec5SDimitry Andric   }
23610b57cec5SDimitry Andric 
2362480093f4SDimitry Andric   // FIXME: Concepts: Do not substitute into constraint expressions
2363480093f4SDimitry Andric   Expr *TrailingRequiresClause = D->getTrailingRequiresClause();
2364480093f4SDimitry Andric   if (TrailingRequiresClause) {
236555e4f9d5SDimitry Andric     EnterExpressionEvaluationContext ConstantEvaluated(
236655e4f9d5SDimitry Andric         SemaRef, Sema::ExpressionEvaluationContext::Unevaluated);
236713138422SDimitry Andric     auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(Owner);
236813138422SDimitry Andric     Sema::CXXThisScopeRAII ThisScope(SemaRef, ThisContext,
236913138422SDimitry Andric                                      D->getMethodQualifiers(), ThisContext);
2370480093f4SDimitry Andric     ExprResult SubstRC = SemaRef.SubstExpr(TrailingRequiresClause,
2371480093f4SDimitry Andric                                            TemplateArgs);
2372480093f4SDimitry Andric     if (SubstRC.isInvalid())
2373480093f4SDimitry Andric       return nullptr;
2374480093f4SDimitry Andric     TrailingRequiresClause = SubstRC.get();
2375480093f4SDimitry Andric     if (!SemaRef.CheckConstraintExpression(TrailingRequiresClause))
2376480093f4SDimitry Andric       return nullptr;
2377480093f4SDimitry Andric   }
2378480093f4SDimitry Andric 
23790b57cec5SDimitry Andric   DeclContext *DC = Owner;
23800b57cec5SDimitry Andric   if (isFriend) {
23810b57cec5SDimitry Andric     if (QualifierLoc) {
23820b57cec5SDimitry Andric       CXXScopeSpec SS;
23830b57cec5SDimitry Andric       SS.Adopt(QualifierLoc);
23840b57cec5SDimitry Andric       DC = SemaRef.computeDeclContext(SS);
23850b57cec5SDimitry Andric 
23860b57cec5SDimitry Andric       if (DC && SemaRef.RequireCompleteDeclContext(SS, DC))
23870b57cec5SDimitry Andric         return nullptr;
23880b57cec5SDimitry Andric     } else {
23890b57cec5SDimitry Andric       DC = SemaRef.FindInstantiatedContext(D->getLocation(),
23900b57cec5SDimitry Andric                                            D->getDeclContext(),
23910b57cec5SDimitry Andric                                            TemplateArgs);
23920b57cec5SDimitry Andric     }
23930b57cec5SDimitry Andric     if (!DC) return nullptr;
23940b57cec5SDimitry Andric   }
23950b57cec5SDimitry Andric 
2396480093f4SDimitry Andric   DeclarationNameInfo NameInfo
2397480093f4SDimitry Andric     = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
2398480093f4SDimitry Andric 
2399480093f4SDimitry Andric   if (FunctionRewriteKind != RewriteKind::None)
2400480093f4SDimitry Andric     adjustForRewrite(FunctionRewriteKind, D, T, TInfo, NameInfo);
2401480093f4SDimitry Andric 
24020b57cec5SDimitry Andric   // Build the instantiated method declaration.
24030b57cec5SDimitry Andric   CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
24040b57cec5SDimitry Andric   CXXMethodDecl *Method = nullptr;
24050b57cec5SDimitry Andric 
24060b57cec5SDimitry Andric   SourceLocation StartLoc = D->getInnerLocStart();
24070b57cec5SDimitry Andric   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
24080b57cec5SDimitry Andric     Method = CXXConstructorDecl::Create(
24090b57cec5SDimitry Andric         SemaRef.Context, Record, StartLoc, NameInfo, T, TInfo,
24100b57cec5SDimitry Andric         InstantiatedExplicitSpecifier, Constructor->isInlineSpecified(), false,
2411480093f4SDimitry Andric         Constructor->getConstexprKind(), InheritedConstructor(),
2412480093f4SDimitry Andric         TrailingRequiresClause);
24130b57cec5SDimitry Andric     Method->setRangeEnd(Constructor->getEndLoc());
24140b57cec5SDimitry Andric   } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
2415a7dea167SDimitry Andric     Method = CXXDestructorDecl::Create(
2416a7dea167SDimitry Andric         SemaRef.Context, Record, StartLoc, NameInfo, T, TInfo,
2417480093f4SDimitry Andric         Destructor->isInlineSpecified(), false, Destructor->getConstexprKind(),
2418480093f4SDimitry Andric         TrailingRequiresClause);
24190b57cec5SDimitry Andric     Method->setRangeEnd(Destructor->getEndLoc());
2420fe6060f1SDimitry Andric     Method->setDeclName(SemaRef.Context.DeclarationNames.getCXXDestructorName(
2421fe6060f1SDimitry Andric         SemaRef.Context.getCanonicalType(
2422fe6060f1SDimitry Andric             SemaRef.Context.getTypeDeclType(Record))));
24230b57cec5SDimitry Andric   } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) {
24240b57cec5SDimitry Andric     Method = CXXConversionDecl::Create(
24250b57cec5SDimitry Andric         SemaRef.Context, Record, StartLoc, NameInfo, T, TInfo,
24260b57cec5SDimitry Andric         Conversion->isInlineSpecified(), InstantiatedExplicitSpecifier,
2427480093f4SDimitry Andric         Conversion->getConstexprKind(), Conversion->getEndLoc(),
2428480093f4SDimitry Andric         TrailingRequiresClause);
24290b57cec5SDimitry Andric   } else {
24300b57cec5SDimitry Andric     StorageClass SC = D->isStatic() ? SC_Static : SC_None;
24310b57cec5SDimitry Andric     Method = CXXMethodDecl::Create(SemaRef.Context, Record, StartLoc, NameInfo,
24320b57cec5SDimitry Andric                                    T, TInfo, SC, D->isInlineSpecified(),
2433480093f4SDimitry Andric                                    D->getConstexprKind(), D->getEndLoc(),
2434480093f4SDimitry Andric                                    TrailingRequiresClause);
24350b57cec5SDimitry Andric   }
24360b57cec5SDimitry Andric 
24370b57cec5SDimitry Andric   if (D->isInlined())
24380b57cec5SDimitry Andric     Method->setImplicitlyInline();
24390b57cec5SDimitry Andric 
24400b57cec5SDimitry Andric   if (QualifierLoc)
24410b57cec5SDimitry Andric     Method->setQualifierInfo(QualifierLoc);
24420b57cec5SDimitry Andric 
24430b57cec5SDimitry Andric   if (TemplateParams) {
24440b57cec5SDimitry Andric     // Our resulting instantiation is actually a function template, since we
24450b57cec5SDimitry Andric     // are substituting only the outer template parameters. For example, given
24460b57cec5SDimitry Andric     //
24470b57cec5SDimitry Andric     //   template<typename T>
24480b57cec5SDimitry Andric     //   struct X {
24490b57cec5SDimitry Andric     //     template<typename U> void f(T, U);
24500b57cec5SDimitry Andric     //   };
24510b57cec5SDimitry Andric     //
24520b57cec5SDimitry Andric     //   X<int> x;
24530b57cec5SDimitry Andric     //
24540b57cec5SDimitry Andric     // We are instantiating the member template "f" within X<int>, which means
24550b57cec5SDimitry Andric     // substituting int for T, but leaving "f" as a member function template.
24560b57cec5SDimitry Andric     // Build the function template itself.
24570b57cec5SDimitry Andric     FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Record,
24580b57cec5SDimitry Andric                                                     Method->getLocation(),
24590b57cec5SDimitry Andric                                                     Method->getDeclName(),
24600b57cec5SDimitry Andric                                                     TemplateParams, Method);
24610b57cec5SDimitry Andric     if (isFriend) {
24620b57cec5SDimitry Andric       FunctionTemplate->setLexicalDeclContext(Owner);
24630b57cec5SDimitry Andric       FunctionTemplate->setObjectOfFriendDecl();
24640b57cec5SDimitry Andric     } else if (D->isOutOfLine())
24650b57cec5SDimitry Andric       FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
24660b57cec5SDimitry Andric     Method->setDescribedFunctionTemplate(FunctionTemplate);
24670b57cec5SDimitry Andric   } else if (FunctionTemplate) {
24680b57cec5SDimitry Andric     // Record this function template specialization.
24690b57cec5SDimitry Andric     ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
24700b57cec5SDimitry Andric     Method->setFunctionTemplateSpecialization(FunctionTemplate,
24710b57cec5SDimitry Andric                          TemplateArgumentList::CreateCopy(SemaRef.Context,
24720b57cec5SDimitry Andric                                                           Innermost),
24730b57cec5SDimitry Andric                                               /*InsertPos=*/nullptr);
24740b57cec5SDimitry Andric   } else if (!isFriend) {
24750b57cec5SDimitry Andric     // Record that this is an instantiation of a member function.
24760b57cec5SDimitry Andric     Method->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
24770b57cec5SDimitry Andric   }
24780b57cec5SDimitry Andric 
24790b57cec5SDimitry Andric   // If we are instantiating a member function defined
24800b57cec5SDimitry Andric   // out-of-line, the instantiation will have the same lexical
24810b57cec5SDimitry Andric   // context (which will be a namespace scope) as the template.
24820b57cec5SDimitry Andric   if (isFriend) {
24830b57cec5SDimitry Andric     if (NumTempParamLists)
24840b57cec5SDimitry Andric       Method->setTemplateParameterListsInfo(
24850b57cec5SDimitry Andric           SemaRef.Context,
24860b57cec5SDimitry Andric           llvm::makeArrayRef(TempParamLists.data(), NumTempParamLists));
24870b57cec5SDimitry Andric 
24880b57cec5SDimitry Andric     Method->setLexicalDeclContext(Owner);
24890b57cec5SDimitry Andric     Method->setObjectOfFriendDecl();
24900b57cec5SDimitry Andric   } else if (D->isOutOfLine())
24910b57cec5SDimitry Andric     Method->setLexicalDeclContext(D->getLexicalDeclContext());
24920b57cec5SDimitry Andric 
24930b57cec5SDimitry Andric   // Attach the parameters
24940b57cec5SDimitry Andric   for (unsigned P = 0; P < Params.size(); ++P)
24950b57cec5SDimitry Andric     Params[P]->setOwningFunction(Method);
24960b57cec5SDimitry Andric   Method->setParams(Params);
24970b57cec5SDimitry Andric 
24980b57cec5SDimitry Andric   if (InitMethodInstantiation(Method, D))
24990b57cec5SDimitry Andric     Method->setInvalidDecl();
25000b57cec5SDimitry Andric 
25010b57cec5SDimitry Andric   LookupResult Previous(SemaRef, NameInfo, Sema::LookupOrdinaryName,
25020b57cec5SDimitry Andric                         Sema::ForExternalRedeclaration);
25030b57cec5SDimitry Andric 
25040b57cec5SDimitry Andric   bool IsExplicitSpecialization = false;
25050b57cec5SDimitry Andric 
25060b57cec5SDimitry Andric   // If the name of this function was written as a template-id, instantiate
25070b57cec5SDimitry Andric   // the explicit template arguments.
25080b57cec5SDimitry Andric   if (DependentFunctionTemplateSpecializationInfo *Info
25090b57cec5SDimitry Andric         = D->getDependentSpecializationInfo()) {
25100b57cec5SDimitry Andric     assert(isFriend && "non-friend has dependent specialization info?");
25110b57cec5SDimitry Andric 
25120b57cec5SDimitry Andric     // Instantiate the explicit template arguments.
25130b57cec5SDimitry Andric     TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(),
25140b57cec5SDimitry Andric                                           Info->getRAngleLoc());
25150b57cec5SDimitry Andric     if (SemaRef.Subst(Info->getTemplateArgs(), Info->getNumTemplateArgs(),
25160b57cec5SDimitry Andric                       ExplicitArgs, TemplateArgs))
25170b57cec5SDimitry Andric       return nullptr;
25180b57cec5SDimitry Andric 
25190b57cec5SDimitry Andric     // Map the candidate templates to their instantiations.
25200b57cec5SDimitry Andric     for (unsigned I = 0, E = Info->getNumTemplates(); I != E; ++I) {
25210b57cec5SDimitry Andric       Decl *Temp = SemaRef.FindInstantiatedDecl(D->getLocation(),
25220b57cec5SDimitry Andric                                                 Info->getTemplate(I),
25230b57cec5SDimitry Andric                                                 TemplateArgs);
25240b57cec5SDimitry Andric       if (!Temp) return nullptr;
25250b57cec5SDimitry Andric 
25260b57cec5SDimitry Andric       Previous.addDecl(cast<FunctionTemplateDecl>(Temp));
25270b57cec5SDimitry Andric     }
25280b57cec5SDimitry Andric 
25290b57cec5SDimitry Andric     if (SemaRef.CheckFunctionTemplateSpecialization(Method,
25300b57cec5SDimitry Andric                                                     &ExplicitArgs,
25310b57cec5SDimitry Andric                                                     Previous))
25320b57cec5SDimitry Andric       Method->setInvalidDecl();
25330b57cec5SDimitry Andric 
25340b57cec5SDimitry Andric     IsExplicitSpecialization = true;
25350b57cec5SDimitry Andric   } else if (const ASTTemplateArgumentListInfo *Info =
25360b57cec5SDimitry Andric                  ClassScopeSpecializationArgs.getValueOr(
25370b57cec5SDimitry Andric                      D->getTemplateSpecializationArgsAsWritten())) {
25380b57cec5SDimitry Andric     SemaRef.LookupQualifiedName(Previous, DC);
25390b57cec5SDimitry Andric 
25400b57cec5SDimitry Andric     TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(),
25410b57cec5SDimitry Andric                                           Info->getRAngleLoc());
25420b57cec5SDimitry Andric     if (SemaRef.Subst(Info->getTemplateArgs(), Info->getNumTemplateArgs(),
25430b57cec5SDimitry Andric                       ExplicitArgs, TemplateArgs))
25440b57cec5SDimitry Andric       return nullptr;
25450b57cec5SDimitry Andric 
25460b57cec5SDimitry Andric     if (SemaRef.CheckFunctionTemplateSpecialization(Method,
25470b57cec5SDimitry Andric                                                     &ExplicitArgs,
25480b57cec5SDimitry Andric                                                     Previous))
25490b57cec5SDimitry Andric       Method->setInvalidDecl();
25500b57cec5SDimitry Andric 
25510b57cec5SDimitry Andric     IsExplicitSpecialization = true;
25520b57cec5SDimitry Andric   } else if (ClassScopeSpecializationArgs) {
25530b57cec5SDimitry Andric     // Class-scope explicit specialization written without explicit template
25540b57cec5SDimitry Andric     // arguments.
25550b57cec5SDimitry Andric     SemaRef.LookupQualifiedName(Previous, DC);
25560b57cec5SDimitry Andric     if (SemaRef.CheckFunctionTemplateSpecialization(Method, nullptr, Previous))
25570b57cec5SDimitry Andric       Method->setInvalidDecl();
25580b57cec5SDimitry Andric 
25590b57cec5SDimitry Andric     IsExplicitSpecialization = true;
25600b57cec5SDimitry Andric   } else if (!FunctionTemplate || TemplateParams || isFriend) {
25610b57cec5SDimitry Andric     SemaRef.LookupQualifiedName(Previous, Record);
25620b57cec5SDimitry Andric 
25630b57cec5SDimitry Andric     // In C++, the previous declaration we find might be a tag type
25640b57cec5SDimitry Andric     // (class or enum). In this case, the new declaration will hide the
25650b57cec5SDimitry Andric     // tag type. Note that this does does not apply if we're declaring a
25660b57cec5SDimitry Andric     // typedef (C++ [dcl.typedef]p4).
25670b57cec5SDimitry Andric     if (Previous.isSingleTagDecl())
25680b57cec5SDimitry Andric       Previous.clear();
25690b57cec5SDimitry Andric   }
25700b57cec5SDimitry Andric 
25710b57cec5SDimitry Andric   SemaRef.CheckFunctionDeclaration(nullptr, Method, Previous,
25720b57cec5SDimitry Andric                                    IsExplicitSpecialization);
25730b57cec5SDimitry Andric 
25740b57cec5SDimitry Andric   if (D->isPure())
25750b57cec5SDimitry Andric     SemaRef.CheckPureMethod(Method, SourceRange());
25760b57cec5SDimitry Andric 
25770b57cec5SDimitry Andric   // Propagate access.  For a non-friend declaration, the access is
25780b57cec5SDimitry Andric   // whatever we're propagating from.  For a friend, it should be the
25790b57cec5SDimitry Andric   // previous declaration we just found.
25800b57cec5SDimitry Andric   if (isFriend && Method->getPreviousDecl())
25810b57cec5SDimitry Andric     Method->setAccess(Method->getPreviousDecl()->getAccess());
25820b57cec5SDimitry Andric   else
25830b57cec5SDimitry Andric     Method->setAccess(D->getAccess());
25840b57cec5SDimitry Andric   if (FunctionTemplate)
25850b57cec5SDimitry Andric     FunctionTemplate->setAccess(Method->getAccess());
25860b57cec5SDimitry Andric 
25870b57cec5SDimitry Andric   SemaRef.CheckOverrideControl(Method);
25880b57cec5SDimitry Andric 
25890b57cec5SDimitry Andric   // If a function is defined as defaulted or deleted, mark it as such now.
2590480093f4SDimitry Andric   if (D->isExplicitlyDefaulted()) {
2591480093f4SDimitry Andric     if (SubstDefaultedFunction(Method, D))
2592480093f4SDimitry Andric       return nullptr;
2593480093f4SDimitry Andric   }
25940b57cec5SDimitry Andric   if (D->isDeletedAsWritten())
25950b57cec5SDimitry Andric     SemaRef.SetDeclDeleted(Method, Method->getLocation());
25960b57cec5SDimitry Andric 
25970b57cec5SDimitry Andric   // If this is an explicit specialization, mark the implicitly-instantiated
25980b57cec5SDimitry Andric   // template specialization as being an explicit specialization too.
25990b57cec5SDimitry Andric   // FIXME: Is this necessary?
26000b57cec5SDimitry Andric   if (IsExplicitSpecialization && !isFriend)
26010b57cec5SDimitry Andric     SemaRef.CompleteMemberSpecialization(Method, Previous);
26020b57cec5SDimitry Andric 
26030b57cec5SDimitry Andric   // If there's a function template, let our caller handle it.
26040b57cec5SDimitry Andric   if (FunctionTemplate) {
26050b57cec5SDimitry Andric     // do nothing
26060b57cec5SDimitry Andric 
26070b57cec5SDimitry Andric   // Don't hide a (potentially) valid declaration with an invalid one.
26080b57cec5SDimitry Andric   } else if (Method->isInvalidDecl() && !Previous.empty()) {
26090b57cec5SDimitry Andric     // do nothing
26100b57cec5SDimitry Andric 
26110b57cec5SDimitry Andric   // Otherwise, check access to friends and make them visible.
26120b57cec5SDimitry Andric   } else if (isFriend) {
26130b57cec5SDimitry Andric     // We only need to re-check access for methods which we didn't
26140b57cec5SDimitry Andric     // manage to match during parsing.
26150b57cec5SDimitry Andric     if (!D->getPreviousDecl())
26160b57cec5SDimitry Andric       SemaRef.CheckFriendAccess(Method);
26170b57cec5SDimitry Andric 
26180b57cec5SDimitry Andric     Record->makeDeclVisibleInContext(Method);
26190b57cec5SDimitry Andric 
26200b57cec5SDimitry Andric   // Otherwise, add the declaration.  We don't need to do this for
26210b57cec5SDimitry Andric   // class-scope specializations because we'll have matched them with
26220b57cec5SDimitry Andric   // the appropriate template.
26230b57cec5SDimitry Andric   } else {
26240b57cec5SDimitry Andric     Owner->addDecl(Method);
26250b57cec5SDimitry Andric   }
26260b57cec5SDimitry Andric 
26270b57cec5SDimitry Andric   // PR17480: Honor the used attribute to instantiate member function
26280b57cec5SDimitry Andric   // definitions
26290b57cec5SDimitry Andric   if (Method->hasAttr<UsedAttr>()) {
26300b57cec5SDimitry Andric     if (const auto *A = dyn_cast<CXXRecordDecl>(Owner)) {
26310b57cec5SDimitry Andric       SourceLocation Loc;
26320b57cec5SDimitry Andric       if (const MemberSpecializationInfo *MSInfo =
26330b57cec5SDimitry Andric               A->getMemberSpecializationInfo())
26340b57cec5SDimitry Andric         Loc = MSInfo->getPointOfInstantiation();
26350b57cec5SDimitry Andric       else if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(A))
26360b57cec5SDimitry Andric         Loc = Spec->getPointOfInstantiation();
26370b57cec5SDimitry Andric       SemaRef.MarkFunctionReferenced(Loc, Method);
26380b57cec5SDimitry Andric     }
26390b57cec5SDimitry Andric   }
26400b57cec5SDimitry Andric 
26410b57cec5SDimitry Andric   return Method;
26420b57cec5SDimitry Andric }
26430b57cec5SDimitry Andric 
26440b57cec5SDimitry Andric Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
26450b57cec5SDimitry Andric   return VisitCXXMethodDecl(D);
26460b57cec5SDimitry Andric }
26470b57cec5SDimitry Andric 
26480b57cec5SDimitry Andric Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
26490b57cec5SDimitry Andric   return VisitCXXMethodDecl(D);
26500b57cec5SDimitry Andric }
26510b57cec5SDimitry Andric 
26520b57cec5SDimitry Andric Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
26530b57cec5SDimitry Andric   return VisitCXXMethodDecl(D);
26540b57cec5SDimitry Andric }
26550b57cec5SDimitry Andric 
26560b57cec5SDimitry Andric Decl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
26570b57cec5SDimitry Andric   return SemaRef.SubstParmVarDecl(D, TemplateArgs, /*indexAdjustment*/ 0, None,
26580b57cec5SDimitry Andric                                   /*ExpectParameterPack=*/ false);
26590b57cec5SDimitry Andric }
26600b57cec5SDimitry Andric 
26610b57cec5SDimitry Andric Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl(
26620b57cec5SDimitry Andric                                                     TemplateTypeParmDecl *D) {
26630b57cec5SDimitry Andric   assert(D->getTypeForDecl()->isTemplateTypeParmType());
26640b57cec5SDimitry Andric 
2665480093f4SDimitry Andric   Optional<unsigned> NumExpanded;
2666480093f4SDimitry Andric 
2667480093f4SDimitry Andric   if (const TypeConstraint *TC = D->getTypeConstraint()) {
2668480093f4SDimitry Andric     if (D->isPackExpansion() && !D->isExpandedParameterPack()) {
2669480093f4SDimitry Andric       assert(TC->getTemplateArgsAsWritten() &&
2670480093f4SDimitry Andric              "type parameter can only be an expansion when explicit arguments "
2671480093f4SDimitry Andric              "are specified");
2672480093f4SDimitry Andric       // The template type parameter pack's type is a pack expansion of types.
2673480093f4SDimitry Andric       // Determine whether we need to expand this parameter pack into separate
2674480093f4SDimitry Andric       // types.
2675480093f4SDimitry Andric       SmallVector<UnexpandedParameterPack, 2> Unexpanded;
2676480093f4SDimitry Andric       for (auto &ArgLoc : TC->getTemplateArgsAsWritten()->arguments())
2677480093f4SDimitry Andric         SemaRef.collectUnexpandedParameterPacks(ArgLoc, Unexpanded);
2678480093f4SDimitry Andric 
2679480093f4SDimitry Andric       // Determine whether the set of unexpanded parameter packs can and should
2680480093f4SDimitry Andric       // be expanded.
2681480093f4SDimitry Andric       bool Expand = true;
2682480093f4SDimitry Andric       bool RetainExpansion = false;
2683480093f4SDimitry Andric       if (SemaRef.CheckParameterPacksForExpansion(
2684480093f4SDimitry Andric               cast<CXXFoldExpr>(TC->getImmediatelyDeclaredConstraint())
2685480093f4SDimitry Andric                   ->getEllipsisLoc(),
2686480093f4SDimitry Andric               SourceRange(TC->getConceptNameLoc(),
2687480093f4SDimitry Andric                           TC->hasExplicitTemplateArgs() ?
2688480093f4SDimitry Andric                           TC->getTemplateArgsAsWritten()->getRAngleLoc() :
2689480093f4SDimitry Andric                           TC->getConceptNameInfo().getEndLoc()),
2690480093f4SDimitry Andric               Unexpanded, TemplateArgs, Expand, RetainExpansion, NumExpanded))
2691480093f4SDimitry Andric         return nullptr;
2692480093f4SDimitry Andric     }
2693480093f4SDimitry Andric   }
2694480093f4SDimitry Andric 
26950b57cec5SDimitry Andric   TemplateTypeParmDecl *Inst = TemplateTypeParmDecl::Create(
26960b57cec5SDimitry Andric       SemaRef.Context, Owner, D->getBeginLoc(), D->getLocation(),
26970b57cec5SDimitry Andric       D->getDepth() - TemplateArgs.getNumSubstitutedLevels(), D->getIndex(),
2698480093f4SDimitry Andric       D->getIdentifier(), D->wasDeclaredWithTypename(), D->isParameterPack(),
2699480093f4SDimitry Andric       D->hasTypeConstraint(), NumExpanded);
2700480093f4SDimitry Andric 
27010b57cec5SDimitry Andric   Inst->setAccess(AS_public);
2702a7dea167SDimitry Andric   Inst->setImplicit(D->isImplicit());
2703480093f4SDimitry Andric   if (auto *TC = D->getTypeConstraint()) {
270413138422SDimitry Andric     if (!D->isImplicit()) {
270513138422SDimitry Andric       // Invented template parameter type constraints will be instantiated with
270613138422SDimitry Andric       // the corresponding auto-typed parameter as it might reference other
270713138422SDimitry Andric       // parameters.
270813138422SDimitry Andric 
2709480093f4SDimitry Andric       // TODO: Concepts: do not instantiate the constraint (delayed constraint
2710480093f4SDimitry Andric       // substitution)
2711480093f4SDimitry Andric       const ASTTemplateArgumentListInfo *TemplArgInfo
2712480093f4SDimitry Andric         = TC->getTemplateArgsAsWritten();
2713480093f4SDimitry Andric       TemplateArgumentListInfo InstArgs;
27140b57cec5SDimitry Andric 
2715480093f4SDimitry Andric       if (TemplArgInfo) {
2716480093f4SDimitry Andric         InstArgs.setLAngleLoc(TemplArgInfo->LAngleLoc);
2717480093f4SDimitry Andric         InstArgs.setRAngleLoc(TemplArgInfo->RAngleLoc);
2718480093f4SDimitry Andric         if (SemaRef.Subst(TemplArgInfo->getTemplateArgs(),
2719480093f4SDimitry Andric                           TemplArgInfo->NumTemplateArgs,
2720480093f4SDimitry Andric                           InstArgs, TemplateArgs))
2721480093f4SDimitry Andric           return nullptr;
2722480093f4SDimitry Andric       }
2723480093f4SDimitry Andric       if (SemaRef.AttachTypeConstraint(
2724480093f4SDimitry Andric               TC->getNestedNameSpecifierLoc(), TC->getConceptNameInfo(),
2725480093f4SDimitry Andric               TC->getNamedConcept(), &InstArgs, Inst,
2726480093f4SDimitry Andric               D->isParameterPack()
2727480093f4SDimitry Andric                   ? cast<CXXFoldExpr>(TC->getImmediatelyDeclaredConstraint())
2728480093f4SDimitry Andric                       ->getEllipsisLoc()
2729480093f4SDimitry Andric                   : SourceLocation()))
2730480093f4SDimitry Andric         return nullptr;
2731480093f4SDimitry Andric     }
273213138422SDimitry Andric   }
27330b57cec5SDimitry Andric   if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited()) {
27340b57cec5SDimitry Andric     TypeSourceInfo *InstantiatedDefaultArg =
27350b57cec5SDimitry Andric         SemaRef.SubstType(D->getDefaultArgumentInfo(), TemplateArgs,
27360b57cec5SDimitry Andric                           D->getDefaultArgumentLoc(), D->getDeclName());
27370b57cec5SDimitry Andric     if (InstantiatedDefaultArg)
27380b57cec5SDimitry Andric       Inst->setDefaultArgument(InstantiatedDefaultArg);
27390b57cec5SDimitry Andric   }
27400b57cec5SDimitry Andric 
27410b57cec5SDimitry Andric   // Introduce this template parameter's instantiation into the instantiation
27420b57cec5SDimitry Andric   // scope.
27430b57cec5SDimitry Andric   SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst);
27440b57cec5SDimitry Andric 
27450b57cec5SDimitry Andric   return Inst;
27460b57cec5SDimitry Andric }
27470b57cec5SDimitry Andric 
27480b57cec5SDimitry Andric Decl *TemplateDeclInstantiator::VisitNonTypeTemplateParmDecl(
27490b57cec5SDimitry Andric                                                  NonTypeTemplateParmDecl *D) {
27500b57cec5SDimitry Andric   // Substitute into the type of the non-type template parameter.
27510b57cec5SDimitry Andric   TypeLoc TL = D->getTypeSourceInfo()->getTypeLoc();
27520b57cec5SDimitry Andric   SmallVector<TypeSourceInfo *, 4> ExpandedParameterPackTypesAsWritten;
27530b57cec5SDimitry Andric   SmallVector<QualType, 4> ExpandedParameterPackTypes;
27540b57cec5SDimitry Andric   bool IsExpandedParameterPack = false;
27550b57cec5SDimitry Andric   TypeSourceInfo *DI;
27560b57cec5SDimitry Andric   QualType T;
27570b57cec5SDimitry Andric   bool Invalid = false;
27580b57cec5SDimitry Andric 
27590b57cec5SDimitry Andric   if (D->isExpandedParameterPack()) {
27600b57cec5SDimitry Andric     // The non-type template parameter pack is an already-expanded pack
27610b57cec5SDimitry Andric     // expansion of types. Substitute into each of the expanded types.
27620b57cec5SDimitry Andric     ExpandedParameterPackTypes.reserve(D->getNumExpansionTypes());
27630b57cec5SDimitry Andric     ExpandedParameterPackTypesAsWritten.reserve(D->getNumExpansionTypes());
27640b57cec5SDimitry Andric     for (unsigned I = 0, N = D->getNumExpansionTypes(); I != N; ++I) {
27650b57cec5SDimitry Andric       TypeSourceInfo *NewDI =
27660b57cec5SDimitry Andric           SemaRef.SubstType(D->getExpansionTypeSourceInfo(I), TemplateArgs,
27670b57cec5SDimitry Andric                             D->getLocation(), D->getDeclName());
27680b57cec5SDimitry Andric       if (!NewDI)
27690b57cec5SDimitry Andric         return nullptr;
27700b57cec5SDimitry Andric 
27710b57cec5SDimitry Andric       QualType NewT =
27720b57cec5SDimitry Andric           SemaRef.CheckNonTypeTemplateParameterType(NewDI, D->getLocation());
27730b57cec5SDimitry Andric       if (NewT.isNull())
27740b57cec5SDimitry Andric         return nullptr;
27750b57cec5SDimitry Andric 
27760b57cec5SDimitry Andric       ExpandedParameterPackTypesAsWritten.push_back(NewDI);
27770b57cec5SDimitry Andric       ExpandedParameterPackTypes.push_back(NewT);
27780b57cec5SDimitry Andric     }
27790b57cec5SDimitry Andric 
27800b57cec5SDimitry Andric     IsExpandedParameterPack = true;
27810b57cec5SDimitry Andric     DI = D->getTypeSourceInfo();
27820b57cec5SDimitry Andric     T = DI->getType();
27830b57cec5SDimitry Andric   } else if (D->isPackExpansion()) {
27840b57cec5SDimitry Andric     // The non-type template parameter pack's type is a pack expansion of types.
27850b57cec5SDimitry Andric     // Determine whether we need to expand this parameter pack into separate
27860b57cec5SDimitry Andric     // types.
27870b57cec5SDimitry Andric     PackExpansionTypeLoc Expansion = TL.castAs<PackExpansionTypeLoc>();
27880b57cec5SDimitry Andric     TypeLoc Pattern = Expansion.getPatternLoc();
27890b57cec5SDimitry Andric     SmallVector<UnexpandedParameterPack, 2> Unexpanded;
27900b57cec5SDimitry Andric     SemaRef.collectUnexpandedParameterPacks(Pattern, Unexpanded);
27910b57cec5SDimitry Andric 
27920b57cec5SDimitry Andric     // Determine whether the set of unexpanded parameter packs can and should
27930b57cec5SDimitry Andric     // be expanded.
27940b57cec5SDimitry Andric     bool Expand = true;
27950b57cec5SDimitry Andric     bool RetainExpansion = false;
27960b57cec5SDimitry Andric     Optional<unsigned> OrigNumExpansions
27970b57cec5SDimitry Andric       = Expansion.getTypePtr()->getNumExpansions();
27980b57cec5SDimitry Andric     Optional<unsigned> NumExpansions = OrigNumExpansions;
27990b57cec5SDimitry Andric     if (SemaRef.CheckParameterPacksForExpansion(Expansion.getEllipsisLoc(),
28000b57cec5SDimitry Andric                                                 Pattern.getSourceRange(),
28010b57cec5SDimitry Andric                                                 Unexpanded,
28020b57cec5SDimitry Andric                                                 TemplateArgs,
28030b57cec5SDimitry Andric                                                 Expand, RetainExpansion,
28040b57cec5SDimitry Andric                                                 NumExpansions))
28050b57cec5SDimitry Andric       return nullptr;
28060b57cec5SDimitry Andric 
28070b57cec5SDimitry Andric     if (Expand) {
28080b57cec5SDimitry Andric       for (unsigned I = 0; I != *NumExpansions; ++I) {
28090b57cec5SDimitry Andric         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
28100b57cec5SDimitry Andric         TypeSourceInfo *NewDI = SemaRef.SubstType(Pattern, TemplateArgs,
28110b57cec5SDimitry Andric                                                   D->getLocation(),
28120b57cec5SDimitry Andric                                                   D->getDeclName());
28130b57cec5SDimitry Andric         if (!NewDI)
28140b57cec5SDimitry Andric           return nullptr;
28150b57cec5SDimitry Andric 
28160b57cec5SDimitry Andric         QualType NewT =
28170b57cec5SDimitry Andric             SemaRef.CheckNonTypeTemplateParameterType(NewDI, D->getLocation());
28180b57cec5SDimitry Andric         if (NewT.isNull())
28190b57cec5SDimitry Andric           return nullptr;
28200b57cec5SDimitry Andric 
28210b57cec5SDimitry Andric         ExpandedParameterPackTypesAsWritten.push_back(NewDI);
28220b57cec5SDimitry Andric         ExpandedParameterPackTypes.push_back(NewT);
28230b57cec5SDimitry Andric       }
28240b57cec5SDimitry Andric 
28250b57cec5SDimitry Andric       // Note that we have an expanded parameter pack. The "type" of this
28260b57cec5SDimitry Andric       // expanded parameter pack is the original expansion type, but callers
28270b57cec5SDimitry Andric       // will end up using the expanded parameter pack types for type-checking.
28280b57cec5SDimitry Andric       IsExpandedParameterPack = true;
28290b57cec5SDimitry Andric       DI = D->getTypeSourceInfo();
28300b57cec5SDimitry Andric       T = DI->getType();
28310b57cec5SDimitry Andric     } else {
28320b57cec5SDimitry Andric       // We cannot fully expand the pack expansion now, so substitute into the
28330b57cec5SDimitry Andric       // pattern and create a new pack expansion type.
28340b57cec5SDimitry Andric       Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
28350b57cec5SDimitry Andric       TypeSourceInfo *NewPattern = SemaRef.SubstType(Pattern, TemplateArgs,
28360b57cec5SDimitry Andric                                                      D->getLocation(),
28370b57cec5SDimitry Andric                                                      D->getDeclName());
28380b57cec5SDimitry Andric       if (!NewPattern)
28390b57cec5SDimitry Andric         return nullptr;
28400b57cec5SDimitry Andric 
28410b57cec5SDimitry Andric       SemaRef.CheckNonTypeTemplateParameterType(NewPattern, D->getLocation());
28420b57cec5SDimitry Andric       DI = SemaRef.CheckPackExpansion(NewPattern, Expansion.getEllipsisLoc(),
28430b57cec5SDimitry Andric                                       NumExpansions);
28440b57cec5SDimitry Andric       if (!DI)
28450b57cec5SDimitry Andric         return nullptr;
28460b57cec5SDimitry Andric 
28470b57cec5SDimitry Andric       T = DI->getType();
28480b57cec5SDimitry Andric     }
28490b57cec5SDimitry Andric   } else {
28500b57cec5SDimitry Andric     // Simple case: substitution into a parameter that is not a parameter pack.
28510b57cec5SDimitry Andric     DI = SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs,
28520b57cec5SDimitry Andric                            D->getLocation(), D->getDeclName());
28530b57cec5SDimitry Andric     if (!DI)
28540b57cec5SDimitry Andric       return nullptr;
28550b57cec5SDimitry Andric 
28560b57cec5SDimitry Andric     // Check that this type is acceptable for a non-type template parameter.
28570b57cec5SDimitry Andric     T = SemaRef.CheckNonTypeTemplateParameterType(DI, D->getLocation());
28580b57cec5SDimitry Andric     if (T.isNull()) {
28590b57cec5SDimitry Andric       T = SemaRef.Context.IntTy;
28600b57cec5SDimitry Andric       Invalid = true;
28610b57cec5SDimitry Andric     }
28620b57cec5SDimitry Andric   }
28630b57cec5SDimitry Andric 
28640b57cec5SDimitry Andric   NonTypeTemplateParmDecl *Param;
28650b57cec5SDimitry Andric   if (IsExpandedParameterPack)
28660b57cec5SDimitry Andric     Param = NonTypeTemplateParmDecl::Create(
28670b57cec5SDimitry Andric         SemaRef.Context, Owner, D->getInnerLocStart(), D->getLocation(),
28680b57cec5SDimitry Andric         D->getDepth() - TemplateArgs.getNumSubstitutedLevels(),
28690b57cec5SDimitry Andric         D->getPosition(), D->getIdentifier(), T, DI, ExpandedParameterPackTypes,
28700b57cec5SDimitry Andric         ExpandedParameterPackTypesAsWritten);
28710b57cec5SDimitry Andric   else
28720b57cec5SDimitry Andric     Param = NonTypeTemplateParmDecl::Create(
28730b57cec5SDimitry Andric         SemaRef.Context, Owner, D->getInnerLocStart(), D->getLocation(),
28740b57cec5SDimitry Andric         D->getDepth() - TemplateArgs.getNumSubstitutedLevels(),
28750b57cec5SDimitry Andric         D->getPosition(), D->getIdentifier(), T, D->isParameterPack(), DI);
28760b57cec5SDimitry Andric 
287755e4f9d5SDimitry Andric   if (AutoTypeLoc AutoLoc = DI->getTypeLoc().getContainedAutoTypeLoc())
287855e4f9d5SDimitry Andric     if (AutoLoc.isConstrained())
287955e4f9d5SDimitry Andric       if (SemaRef.AttachTypeConstraint(
288055e4f9d5SDimitry Andric               AutoLoc, Param,
288155e4f9d5SDimitry Andric               IsExpandedParameterPack
288255e4f9d5SDimitry Andric                 ? DI->getTypeLoc().getAs<PackExpansionTypeLoc>()
288355e4f9d5SDimitry Andric                     .getEllipsisLoc()
288455e4f9d5SDimitry Andric                 : SourceLocation()))
288555e4f9d5SDimitry Andric         Invalid = true;
288655e4f9d5SDimitry Andric 
28870b57cec5SDimitry Andric   Param->setAccess(AS_public);
2888a7dea167SDimitry Andric   Param->setImplicit(D->isImplicit());
28890b57cec5SDimitry Andric   if (Invalid)
28900b57cec5SDimitry Andric     Param->setInvalidDecl();
28910b57cec5SDimitry Andric 
28920b57cec5SDimitry Andric   if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited()) {
28930b57cec5SDimitry Andric     EnterExpressionEvaluationContext ConstantEvaluated(
28940b57cec5SDimitry Andric         SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
28950b57cec5SDimitry Andric     ExprResult Value = SemaRef.SubstExpr(D->getDefaultArgument(), TemplateArgs);
28960b57cec5SDimitry Andric     if (!Value.isInvalid())
28970b57cec5SDimitry Andric       Param->setDefaultArgument(Value.get());
28980b57cec5SDimitry Andric   }
28990b57cec5SDimitry Andric 
29000b57cec5SDimitry Andric   // Introduce this template parameter's instantiation into the instantiation
29010b57cec5SDimitry Andric   // scope.
29020b57cec5SDimitry Andric   SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
29030b57cec5SDimitry Andric   return Param;
29040b57cec5SDimitry Andric }
29050b57cec5SDimitry Andric 
29060b57cec5SDimitry Andric static void collectUnexpandedParameterPacks(
29070b57cec5SDimitry Andric     Sema &S,
29080b57cec5SDimitry Andric     TemplateParameterList *Params,
29090b57cec5SDimitry Andric     SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
29100b57cec5SDimitry Andric   for (const auto &P : *Params) {
29110b57cec5SDimitry Andric     if (P->isTemplateParameterPack())
29120b57cec5SDimitry Andric       continue;
29130b57cec5SDimitry Andric     if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P))
29140b57cec5SDimitry Andric       S.collectUnexpandedParameterPacks(NTTP->getTypeSourceInfo()->getTypeLoc(),
29150b57cec5SDimitry Andric                                         Unexpanded);
29160b57cec5SDimitry Andric     if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(P))
29170b57cec5SDimitry Andric       collectUnexpandedParameterPacks(S, TTP->getTemplateParameters(),
29180b57cec5SDimitry Andric                                       Unexpanded);
29190b57cec5SDimitry Andric   }
29200b57cec5SDimitry Andric }
29210b57cec5SDimitry Andric 
29220b57cec5SDimitry Andric Decl *
29230b57cec5SDimitry Andric TemplateDeclInstantiator::VisitTemplateTemplateParmDecl(
29240b57cec5SDimitry Andric                                                   TemplateTemplateParmDecl *D) {
29250b57cec5SDimitry Andric   // Instantiate the template parameter list of the template template parameter.
29260b57cec5SDimitry Andric   TemplateParameterList *TempParams = D->getTemplateParameters();
29270b57cec5SDimitry Andric   TemplateParameterList *InstParams;
29280b57cec5SDimitry Andric   SmallVector<TemplateParameterList*, 8> ExpandedParams;
29290b57cec5SDimitry Andric 
29300b57cec5SDimitry Andric   bool IsExpandedParameterPack = false;
29310b57cec5SDimitry Andric 
29320b57cec5SDimitry Andric   if (D->isExpandedParameterPack()) {
29330b57cec5SDimitry Andric     // The template template parameter pack is an already-expanded pack
29340b57cec5SDimitry Andric     // expansion of template parameters. Substitute into each of the expanded
29350b57cec5SDimitry Andric     // parameters.
29360b57cec5SDimitry Andric     ExpandedParams.reserve(D->getNumExpansionTemplateParameters());
29370b57cec5SDimitry Andric     for (unsigned I = 0, N = D->getNumExpansionTemplateParameters();
29380b57cec5SDimitry Andric          I != N; ++I) {
29390b57cec5SDimitry Andric       LocalInstantiationScope Scope(SemaRef);
29400b57cec5SDimitry Andric       TemplateParameterList *Expansion =
29410b57cec5SDimitry Andric         SubstTemplateParams(D->getExpansionTemplateParameters(I));
29420b57cec5SDimitry Andric       if (!Expansion)
29430b57cec5SDimitry Andric         return nullptr;
29440b57cec5SDimitry Andric       ExpandedParams.push_back(Expansion);
29450b57cec5SDimitry Andric     }
29460b57cec5SDimitry Andric 
29470b57cec5SDimitry Andric     IsExpandedParameterPack = true;
29480b57cec5SDimitry Andric     InstParams = TempParams;
29490b57cec5SDimitry Andric   } else if (D->isPackExpansion()) {
29500b57cec5SDimitry Andric     // The template template parameter pack expands to a pack of template
29510b57cec5SDimitry Andric     // template parameters. Determine whether we need to expand this parameter
29520b57cec5SDimitry Andric     // pack into separate parameters.
29530b57cec5SDimitry Andric     SmallVector<UnexpandedParameterPack, 2> Unexpanded;
29540b57cec5SDimitry Andric     collectUnexpandedParameterPacks(SemaRef, D->getTemplateParameters(),
29550b57cec5SDimitry Andric                                     Unexpanded);
29560b57cec5SDimitry Andric 
29570b57cec5SDimitry Andric     // Determine whether the set of unexpanded parameter packs can and should
29580b57cec5SDimitry Andric     // be expanded.
29590b57cec5SDimitry Andric     bool Expand = true;
29600b57cec5SDimitry Andric     bool RetainExpansion = false;
29610b57cec5SDimitry Andric     Optional<unsigned> NumExpansions;
29620b57cec5SDimitry Andric     if (SemaRef.CheckParameterPacksForExpansion(D->getLocation(),
29630b57cec5SDimitry Andric                                                 TempParams->getSourceRange(),
29640b57cec5SDimitry Andric                                                 Unexpanded,
29650b57cec5SDimitry Andric                                                 TemplateArgs,
29660b57cec5SDimitry Andric                                                 Expand, RetainExpansion,
29670b57cec5SDimitry Andric                                                 NumExpansions))
29680b57cec5SDimitry Andric       return nullptr;
29690b57cec5SDimitry Andric 
29700b57cec5SDimitry Andric     if (Expand) {
29710b57cec5SDimitry Andric       for (unsigned I = 0; I != *NumExpansions; ++I) {
29720b57cec5SDimitry Andric         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
29730b57cec5SDimitry Andric         LocalInstantiationScope Scope(SemaRef);
29740b57cec5SDimitry Andric         TemplateParameterList *Expansion = SubstTemplateParams(TempParams);
29750b57cec5SDimitry Andric         if (!Expansion)
29760b57cec5SDimitry Andric           return nullptr;
29770b57cec5SDimitry Andric         ExpandedParams.push_back(Expansion);
29780b57cec5SDimitry Andric       }
29790b57cec5SDimitry Andric 
29800b57cec5SDimitry Andric       // Note that we have an expanded parameter pack. The "type" of this
29810b57cec5SDimitry Andric       // expanded parameter pack is the original expansion type, but callers
29820b57cec5SDimitry Andric       // will end up using the expanded parameter pack types for type-checking.
29830b57cec5SDimitry Andric       IsExpandedParameterPack = true;
29840b57cec5SDimitry Andric       InstParams = TempParams;
29850b57cec5SDimitry Andric     } else {
29860b57cec5SDimitry Andric       // We cannot fully expand the pack expansion now, so just substitute
29870b57cec5SDimitry Andric       // into the pattern.
29880b57cec5SDimitry Andric       Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
29890b57cec5SDimitry Andric 
29900b57cec5SDimitry Andric       LocalInstantiationScope Scope(SemaRef);
29910b57cec5SDimitry Andric       InstParams = SubstTemplateParams(TempParams);
29920b57cec5SDimitry Andric       if (!InstParams)
29930b57cec5SDimitry Andric         return nullptr;
29940b57cec5SDimitry Andric     }
29950b57cec5SDimitry Andric   } else {
29960b57cec5SDimitry Andric     // Perform the actual substitution of template parameters within a new,
29970b57cec5SDimitry Andric     // local instantiation scope.
29980b57cec5SDimitry Andric     LocalInstantiationScope Scope(SemaRef);
29990b57cec5SDimitry Andric     InstParams = SubstTemplateParams(TempParams);
30000b57cec5SDimitry Andric     if (!InstParams)
30010b57cec5SDimitry Andric       return nullptr;
30020b57cec5SDimitry Andric   }
30030b57cec5SDimitry Andric 
30040b57cec5SDimitry Andric   // Build the template template parameter.
30050b57cec5SDimitry Andric   TemplateTemplateParmDecl *Param;
30060b57cec5SDimitry Andric   if (IsExpandedParameterPack)
30070b57cec5SDimitry Andric     Param = TemplateTemplateParmDecl::Create(
30080b57cec5SDimitry Andric         SemaRef.Context, Owner, D->getLocation(),
30090b57cec5SDimitry Andric         D->getDepth() - TemplateArgs.getNumSubstitutedLevels(),
30100b57cec5SDimitry Andric         D->getPosition(), D->getIdentifier(), InstParams, ExpandedParams);
30110b57cec5SDimitry Andric   else
30120b57cec5SDimitry Andric     Param = TemplateTemplateParmDecl::Create(
30130b57cec5SDimitry Andric         SemaRef.Context, Owner, D->getLocation(),
30140b57cec5SDimitry Andric         D->getDepth() - TemplateArgs.getNumSubstitutedLevels(),
30150b57cec5SDimitry Andric         D->getPosition(), D->isParameterPack(), D->getIdentifier(), InstParams);
30160b57cec5SDimitry Andric   if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited()) {
30170b57cec5SDimitry Andric     NestedNameSpecifierLoc QualifierLoc =
30180b57cec5SDimitry Andric         D->getDefaultArgument().getTemplateQualifierLoc();
30190b57cec5SDimitry Andric     QualifierLoc =
30200b57cec5SDimitry Andric         SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgs);
30210b57cec5SDimitry Andric     TemplateName TName = SemaRef.SubstTemplateName(
30220b57cec5SDimitry Andric         QualifierLoc, D->getDefaultArgument().getArgument().getAsTemplate(),
30230b57cec5SDimitry Andric         D->getDefaultArgument().getTemplateNameLoc(), TemplateArgs);
30240b57cec5SDimitry Andric     if (!TName.isNull())
30250b57cec5SDimitry Andric       Param->setDefaultArgument(
30260b57cec5SDimitry Andric           SemaRef.Context,
3027e8d8bef9SDimitry Andric           TemplateArgumentLoc(SemaRef.Context, TemplateArgument(TName),
30280b57cec5SDimitry Andric                               D->getDefaultArgument().getTemplateQualifierLoc(),
30290b57cec5SDimitry Andric                               D->getDefaultArgument().getTemplateNameLoc()));
30300b57cec5SDimitry Andric   }
30310b57cec5SDimitry Andric   Param->setAccess(AS_public);
3032a7dea167SDimitry Andric   Param->setImplicit(D->isImplicit());
30330b57cec5SDimitry Andric 
30340b57cec5SDimitry Andric   // Introduce this template parameter's instantiation into the instantiation
30350b57cec5SDimitry Andric   // scope.
30360b57cec5SDimitry Andric   SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
30370b57cec5SDimitry Andric 
30380b57cec5SDimitry Andric   return Param;
30390b57cec5SDimitry Andric }
30400b57cec5SDimitry Andric 
30410b57cec5SDimitry Andric Decl *TemplateDeclInstantiator::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
30420b57cec5SDimitry Andric   // Using directives are never dependent (and never contain any types or
30430b57cec5SDimitry Andric   // expressions), so they require no explicit instantiation work.
30440b57cec5SDimitry Andric 
30450b57cec5SDimitry Andric   UsingDirectiveDecl *Inst
30460b57cec5SDimitry Andric     = UsingDirectiveDecl::Create(SemaRef.Context, Owner, D->getLocation(),
30470b57cec5SDimitry Andric                                  D->getNamespaceKeyLocation(),
30480b57cec5SDimitry Andric                                  D->getQualifierLoc(),
30490b57cec5SDimitry Andric                                  D->getIdentLocation(),
30500b57cec5SDimitry Andric                                  D->getNominatedNamespace(),
30510b57cec5SDimitry Andric                                  D->getCommonAncestor());
30520b57cec5SDimitry Andric 
30530b57cec5SDimitry Andric   // Add the using directive to its declaration context
30540b57cec5SDimitry Andric   // only if this is not a function or method.
30550b57cec5SDimitry Andric   if (!Owner->isFunctionOrMethod())
30560b57cec5SDimitry Andric     Owner->addDecl(Inst);
30570b57cec5SDimitry Andric 
30580b57cec5SDimitry Andric   return Inst;
30590b57cec5SDimitry Andric }
30600b57cec5SDimitry Andric 
3061fe6060f1SDimitry Andric Decl *TemplateDeclInstantiator::VisitBaseUsingDecls(BaseUsingDecl *D,
3062fe6060f1SDimitry Andric                                                     BaseUsingDecl *Inst,
3063fe6060f1SDimitry Andric                                                     LookupResult *Lookup) {
3064fe6060f1SDimitry Andric 
3065fe6060f1SDimitry Andric   bool isFunctionScope = Owner->isFunctionOrMethod();
3066fe6060f1SDimitry Andric 
3067fe6060f1SDimitry Andric   for (auto *Shadow : D->shadows()) {
3068fe6060f1SDimitry Andric     // FIXME: UsingShadowDecl doesn't preserve its immediate target, so
3069fe6060f1SDimitry Andric     // reconstruct it in the case where it matters. Hm, can we extract it from
3070fe6060f1SDimitry Andric     // the DeclSpec when parsing and save it in the UsingDecl itself?
3071fe6060f1SDimitry Andric     NamedDecl *OldTarget = Shadow->getTargetDecl();
3072fe6060f1SDimitry Andric     if (auto *CUSD = dyn_cast<ConstructorUsingShadowDecl>(Shadow))
3073fe6060f1SDimitry Andric       if (auto *BaseShadow = CUSD->getNominatedBaseClassShadowDecl())
3074fe6060f1SDimitry Andric         OldTarget = BaseShadow;
3075fe6060f1SDimitry Andric 
3076fe6060f1SDimitry Andric     NamedDecl *InstTarget = nullptr;
3077fe6060f1SDimitry Andric     if (auto *EmptyD =
3078fe6060f1SDimitry Andric             dyn_cast<UnresolvedUsingIfExistsDecl>(Shadow->getTargetDecl())) {
3079fe6060f1SDimitry Andric       InstTarget = UnresolvedUsingIfExistsDecl::Create(
3080fe6060f1SDimitry Andric           SemaRef.Context, Owner, EmptyD->getLocation(), EmptyD->getDeclName());
3081fe6060f1SDimitry Andric     } else {
3082fe6060f1SDimitry Andric       InstTarget = cast_or_null<NamedDecl>(SemaRef.FindInstantiatedDecl(
3083fe6060f1SDimitry Andric           Shadow->getLocation(), OldTarget, TemplateArgs));
3084fe6060f1SDimitry Andric     }
3085fe6060f1SDimitry Andric     if (!InstTarget)
3086fe6060f1SDimitry Andric       return nullptr;
3087fe6060f1SDimitry Andric 
3088fe6060f1SDimitry Andric     UsingShadowDecl *PrevDecl = nullptr;
3089fe6060f1SDimitry Andric     if (Lookup &&
3090fe6060f1SDimitry Andric         SemaRef.CheckUsingShadowDecl(Inst, InstTarget, *Lookup, PrevDecl))
3091fe6060f1SDimitry Andric       continue;
3092fe6060f1SDimitry Andric 
3093fe6060f1SDimitry Andric     if (UsingShadowDecl *OldPrev = getPreviousDeclForInstantiation(Shadow))
3094fe6060f1SDimitry Andric       PrevDecl = cast_or_null<UsingShadowDecl>(SemaRef.FindInstantiatedDecl(
3095fe6060f1SDimitry Andric           Shadow->getLocation(), OldPrev, TemplateArgs));
3096fe6060f1SDimitry Andric 
3097fe6060f1SDimitry Andric     UsingShadowDecl *InstShadow = SemaRef.BuildUsingShadowDecl(
3098fe6060f1SDimitry Andric         /*Scope*/ nullptr, Inst, InstTarget, PrevDecl);
3099fe6060f1SDimitry Andric     SemaRef.Context.setInstantiatedFromUsingShadowDecl(InstShadow, Shadow);
3100fe6060f1SDimitry Andric 
3101fe6060f1SDimitry Andric     if (isFunctionScope)
3102fe6060f1SDimitry Andric       SemaRef.CurrentInstantiationScope->InstantiatedLocal(Shadow, InstShadow);
3103fe6060f1SDimitry Andric   }
3104fe6060f1SDimitry Andric 
3105fe6060f1SDimitry Andric   return Inst;
3106fe6060f1SDimitry Andric }
3107fe6060f1SDimitry Andric 
31080b57cec5SDimitry Andric Decl *TemplateDeclInstantiator::VisitUsingDecl(UsingDecl *D) {
31090b57cec5SDimitry Andric 
31100b57cec5SDimitry Andric   // The nested name specifier may be dependent, for example
31110b57cec5SDimitry Andric   //     template <typename T> struct t {
31120b57cec5SDimitry Andric   //       struct s1 { T f1(); };
31130b57cec5SDimitry Andric   //       struct s2 : s1 { using s1::f1; };
31140b57cec5SDimitry Andric   //     };
31150b57cec5SDimitry Andric   //     template struct t<int>;
31160b57cec5SDimitry Andric   // Here, in using s1::f1, s1 refers to t<T>::s1;
31170b57cec5SDimitry Andric   // we need to substitute for t<int>::s1.
31180b57cec5SDimitry Andric   NestedNameSpecifierLoc QualifierLoc
31190b57cec5SDimitry Andric     = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
31200b57cec5SDimitry Andric                                           TemplateArgs);
31210b57cec5SDimitry Andric   if (!QualifierLoc)
31220b57cec5SDimitry Andric     return nullptr;
31230b57cec5SDimitry Andric 
31240b57cec5SDimitry Andric   // For an inheriting constructor declaration, the name of the using
31250b57cec5SDimitry Andric   // declaration is the name of a constructor in this class, not in the
31260b57cec5SDimitry Andric   // base class.
31270b57cec5SDimitry Andric   DeclarationNameInfo NameInfo = D->getNameInfo();
31280b57cec5SDimitry Andric   if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName)
31290b57cec5SDimitry Andric     if (auto *RD = dyn_cast<CXXRecordDecl>(SemaRef.CurContext))
31300b57cec5SDimitry Andric       NameInfo.setName(SemaRef.Context.DeclarationNames.getCXXConstructorName(
31310b57cec5SDimitry Andric           SemaRef.Context.getCanonicalType(SemaRef.Context.getRecordType(RD))));
31320b57cec5SDimitry Andric 
3133fe6060f1SDimitry Andric   // We only need to do redeclaration lookups if we're in a class scope (in
3134fe6060f1SDimitry Andric   // fact, it's not really even possible in non-class scopes).
31350b57cec5SDimitry Andric   bool CheckRedeclaration = Owner->isRecord();
31360b57cec5SDimitry Andric   LookupResult Prev(SemaRef, NameInfo, Sema::LookupUsingDeclName,
31370b57cec5SDimitry Andric                     Sema::ForVisibleRedeclaration);
31380b57cec5SDimitry Andric 
31390b57cec5SDimitry Andric   UsingDecl *NewUD = UsingDecl::Create(SemaRef.Context, Owner,
31400b57cec5SDimitry Andric                                        D->getUsingLoc(),
31410b57cec5SDimitry Andric                                        QualifierLoc,
31420b57cec5SDimitry Andric                                        NameInfo,
31430b57cec5SDimitry Andric                                        D->hasTypename());
31440b57cec5SDimitry Andric 
31450b57cec5SDimitry Andric   CXXScopeSpec SS;
31460b57cec5SDimitry Andric   SS.Adopt(QualifierLoc);
31470b57cec5SDimitry Andric   if (CheckRedeclaration) {
31480b57cec5SDimitry Andric     Prev.setHideTags(false);
31490b57cec5SDimitry Andric     SemaRef.LookupQualifiedName(Prev, Owner);
31500b57cec5SDimitry Andric 
31510b57cec5SDimitry Andric     // Check for invalid redeclarations.
31520b57cec5SDimitry Andric     if (SemaRef.CheckUsingDeclRedeclaration(D->getUsingLoc(),
31530b57cec5SDimitry Andric                                             D->hasTypename(), SS,
31540b57cec5SDimitry Andric                                             D->getLocation(), Prev))
31550b57cec5SDimitry Andric       NewUD->setInvalidDecl();
31560b57cec5SDimitry Andric   }
31570b57cec5SDimitry Andric 
31580b57cec5SDimitry Andric   if (!NewUD->isInvalidDecl() &&
3159fe6060f1SDimitry Andric       SemaRef.CheckUsingDeclQualifier(D->getUsingLoc(), D->hasTypename(), SS,
3160fe6060f1SDimitry Andric                                       NameInfo, D->getLocation(), nullptr, D))
31610b57cec5SDimitry Andric     NewUD->setInvalidDecl();
31620b57cec5SDimitry Andric 
31630b57cec5SDimitry Andric   SemaRef.Context.setInstantiatedFromUsingDecl(NewUD, D);
31640b57cec5SDimitry Andric   NewUD->setAccess(D->getAccess());
31650b57cec5SDimitry Andric   Owner->addDecl(NewUD);
31660b57cec5SDimitry Andric 
31670b57cec5SDimitry Andric   // Don't process the shadow decls for an invalid decl.
31680b57cec5SDimitry Andric   if (NewUD->isInvalidDecl())
31690b57cec5SDimitry Andric     return NewUD;
31700b57cec5SDimitry Andric 
3171fe6060f1SDimitry Andric   // If the using scope was dependent, or we had dependent bases, we need to
3172fe6060f1SDimitry Andric   // recheck the inheritance
31730b57cec5SDimitry Andric   if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName)
31740b57cec5SDimitry Andric     SemaRef.CheckInheritingConstructorUsingDecl(NewUD);
31750b57cec5SDimitry Andric 
3176fe6060f1SDimitry Andric   return VisitBaseUsingDecls(D, NewUD, CheckRedeclaration ? &Prev : nullptr);
3177fe6060f1SDimitry Andric }
31780b57cec5SDimitry Andric 
3179fe6060f1SDimitry Andric Decl *TemplateDeclInstantiator::VisitUsingEnumDecl(UsingEnumDecl *D) {
3180fe6060f1SDimitry Andric   // Cannot be a dependent type, but still could be an instantiation
3181fe6060f1SDimitry Andric   EnumDecl *EnumD = cast_or_null<EnumDecl>(SemaRef.FindInstantiatedDecl(
3182fe6060f1SDimitry Andric       D->getLocation(), D->getEnumDecl(), TemplateArgs));
31830b57cec5SDimitry Andric 
3184fe6060f1SDimitry Andric   if (SemaRef.RequireCompleteEnumDecl(EnumD, EnumD->getLocation()))
31850b57cec5SDimitry Andric     return nullptr;
31860b57cec5SDimitry Andric 
3187fe6060f1SDimitry Andric   UsingEnumDecl *NewUD =
3188fe6060f1SDimitry Andric       UsingEnumDecl::Create(SemaRef.Context, Owner, D->getUsingLoc(),
3189fe6060f1SDimitry Andric                             D->getEnumLoc(), D->getLocation(), EnumD);
31900b57cec5SDimitry Andric 
3191fe6060f1SDimitry Andric   SemaRef.Context.setInstantiatedFromUsingEnumDecl(NewUD, D);
3192fe6060f1SDimitry Andric   NewUD->setAccess(D->getAccess());
3193fe6060f1SDimitry Andric   Owner->addDecl(NewUD);
31940b57cec5SDimitry Andric 
3195fe6060f1SDimitry Andric   // Don't process the shadow decls for an invalid decl.
3196fe6060f1SDimitry Andric   if (NewUD->isInvalidDecl())
31970b57cec5SDimitry Andric     return NewUD;
3198fe6060f1SDimitry Andric 
3199fe6060f1SDimitry Andric   // We don't have to recheck for duplication of the UsingEnumDecl itself, as it
3200fe6060f1SDimitry Andric   // cannot be dependent, and will therefore have been checked during template
3201fe6060f1SDimitry Andric   // definition.
3202fe6060f1SDimitry Andric 
3203fe6060f1SDimitry Andric   return VisitBaseUsingDecls(D, NewUD, nullptr);
32040b57cec5SDimitry Andric }
32050b57cec5SDimitry Andric 
32060b57cec5SDimitry Andric Decl *TemplateDeclInstantiator::VisitUsingShadowDecl(UsingShadowDecl *D) {
32070b57cec5SDimitry Andric   // Ignore these;  we handle them in bulk when processing the UsingDecl.
32080b57cec5SDimitry Andric   return nullptr;
32090b57cec5SDimitry Andric }
32100b57cec5SDimitry Andric 
32110b57cec5SDimitry Andric Decl *TemplateDeclInstantiator::VisitConstructorUsingShadowDecl(
32120b57cec5SDimitry Andric     ConstructorUsingShadowDecl *D) {
32130b57cec5SDimitry Andric   // Ignore these;  we handle them in bulk when processing the UsingDecl.
32140b57cec5SDimitry Andric   return nullptr;
32150b57cec5SDimitry Andric }
32160b57cec5SDimitry Andric 
32170b57cec5SDimitry Andric template <typename T>
32180b57cec5SDimitry Andric Decl *TemplateDeclInstantiator::instantiateUnresolvedUsingDecl(
32190b57cec5SDimitry Andric     T *D, bool InstantiatingPackElement) {
32200b57cec5SDimitry Andric   // If this is a pack expansion, expand it now.
32210b57cec5SDimitry Andric   if (D->isPackExpansion() && !InstantiatingPackElement) {
32220b57cec5SDimitry Andric     SmallVector<UnexpandedParameterPack, 2> Unexpanded;
32230b57cec5SDimitry Andric     SemaRef.collectUnexpandedParameterPacks(D->getQualifierLoc(), Unexpanded);
32240b57cec5SDimitry Andric     SemaRef.collectUnexpandedParameterPacks(D->getNameInfo(), Unexpanded);
32250b57cec5SDimitry Andric 
32260b57cec5SDimitry Andric     // Determine whether the set of unexpanded parameter packs can and should
32270b57cec5SDimitry Andric     // be expanded.
32280b57cec5SDimitry Andric     bool Expand = true;
32290b57cec5SDimitry Andric     bool RetainExpansion = false;
32300b57cec5SDimitry Andric     Optional<unsigned> NumExpansions;
32310b57cec5SDimitry Andric     if (SemaRef.CheckParameterPacksForExpansion(
32320b57cec5SDimitry Andric           D->getEllipsisLoc(), D->getSourceRange(), Unexpanded, TemplateArgs,
32330b57cec5SDimitry Andric             Expand, RetainExpansion, NumExpansions))
32340b57cec5SDimitry Andric       return nullptr;
32350b57cec5SDimitry Andric 
32360b57cec5SDimitry Andric     // This declaration cannot appear within a function template signature,
32370b57cec5SDimitry Andric     // so we can't have a partial argument list for a parameter pack.
32380b57cec5SDimitry Andric     assert(!RetainExpansion &&
32390b57cec5SDimitry Andric            "should never need to retain an expansion for UsingPackDecl");
32400b57cec5SDimitry Andric 
32410b57cec5SDimitry Andric     if (!Expand) {
32420b57cec5SDimitry Andric       // We cannot fully expand the pack expansion now, so substitute into the
32430b57cec5SDimitry Andric       // pattern and create a new pack expansion.
32440b57cec5SDimitry Andric       Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
32450b57cec5SDimitry Andric       return instantiateUnresolvedUsingDecl(D, true);
32460b57cec5SDimitry Andric     }
32470b57cec5SDimitry Andric 
32480b57cec5SDimitry Andric     // Within a function, we don't have any normal way to check for conflicts
32490b57cec5SDimitry Andric     // between shadow declarations from different using declarations in the
32500b57cec5SDimitry Andric     // same pack expansion, but this is always ill-formed because all expansions
32510b57cec5SDimitry Andric     // must produce (conflicting) enumerators.
32520b57cec5SDimitry Andric     //
32530b57cec5SDimitry Andric     // Sadly we can't just reject this in the template definition because it
32540b57cec5SDimitry Andric     // could be valid if the pack is empty or has exactly one expansion.
32550b57cec5SDimitry Andric     if (D->getDeclContext()->isFunctionOrMethod() && *NumExpansions > 1) {
32560b57cec5SDimitry Andric       SemaRef.Diag(D->getEllipsisLoc(),
32570b57cec5SDimitry Andric                    diag::err_using_decl_redeclaration_expansion);
32580b57cec5SDimitry Andric       return nullptr;
32590b57cec5SDimitry Andric     }
32600b57cec5SDimitry Andric 
32610b57cec5SDimitry Andric     // Instantiate the slices of this pack and build a UsingPackDecl.
32620b57cec5SDimitry Andric     SmallVector<NamedDecl*, 8> Expansions;
32630b57cec5SDimitry Andric     for (unsigned I = 0; I != *NumExpansions; ++I) {
32640b57cec5SDimitry Andric       Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
32650b57cec5SDimitry Andric       Decl *Slice = instantiateUnresolvedUsingDecl(D, true);
32660b57cec5SDimitry Andric       if (!Slice)
32670b57cec5SDimitry Andric         return nullptr;
32680b57cec5SDimitry Andric       // Note that we can still get unresolved using declarations here, if we
32690b57cec5SDimitry Andric       // had arguments for all packs but the pattern also contained other
32700b57cec5SDimitry Andric       // template arguments (this only happens during partial substitution, eg
32710b57cec5SDimitry Andric       // into the body of a generic lambda in a function template).
32720b57cec5SDimitry Andric       Expansions.push_back(cast<NamedDecl>(Slice));
32730b57cec5SDimitry Andric     }
32740b57cec5SDimitry Andric 
32750b57cec5SDimitry Andric     auto *NewD = SemaRef.BuildUsingPackDecl(D, Expansions);
32760b57cec5SDimitry Andric     if (isDeclWithinFunction(D))
32770b57cec5SDimitry Andric       SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewD);
32780b57cec5SDimitry Andric     return NewD;
32790b57cec5SDimitry Andric   }
32800b57cec5SDimitry Andric 
32810b57cec5SDimitry Andric   UnresolvedUsingTypenameDecl *TD = dyn_cast<UnresolvedUsingTypenameDecl>(D);
32820b57cec5SDimitry Andric   SourceLocation TypenameLoc = TD ? TD->getTypenameLoc() : SourceLocation();
32830b57cec5SDimitry Andric 
32840b57cec5SDimitry Andric   NestedNameSpecifierLoc QualifierLoc
32850b57cec5SDimitry Andric     = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
32860b57cec5SDimitry Andric                                           TemplateArgs);
32870b57cec5SDimitry Andric   if (!QualifierLoc)
32880b57cec5SDimitry Andric     return nullptr;
32890b57cec5SDimitry Andric 
32900b57cec5SDimitry Andric   CXXScopeSpec SS;
32910b57cec5SDimitry Andric   SS.Adopt(QualifierLoc);
32920b57cec5SDimitry Andric 
32930b57cec5SDimitry Andric   DeclarationNameInfo NameInfo
32940b57cec5SDimitry Andric     = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
32950b57cec5SDimitry Andric 
32960b57cec5SDimitry Andric   // Produce a pack expansion only if we're not instantiating a particular
32970b57cec5SDimitry Andric   // slice of a pack expansion.
32980b57cec5SDimitry Andric   bool InstantiatingSlice = D->getEllipsisLoc().isValid() &&
32990b57cec5SDimitry Andric                             SemaRef.ArgumentPackSubstitutionIndex != -1;
33000b57cec5SDimitry Andric   SourceLocation EllipsisLoc =
33010b57cec5SDimitry Andric       InstantiatingSlice ? SourceLocation() : D->getEllipsisLoc();
33020b57cec5SDimitry Andric 
3303fe6060f1SDimitry Andric   bool IsUsingIfExists = D->template hasAttr<UsingIfExistsAttr>();
33040b57cec5SDimitry Andric   NamedDecl *UD = SemaRef.BuildUsingDeclaration(
33050b57cec5SDimitry Andric       /*Scope*/ nullptr, D->getAccess(), D->getUsingLoc(),
33060b57cec5SDimitry Andric       /*HasTypename*/ TD, TypenameLoc, SS, NameInfo, EllipsisLoc,
33070b57cec5SDimitry Andric       ParsedAttributesView(),
3308fe6060f1SDimitry Andric       /*IsInstantiation*/ true, IsUsingIfExists);
3309fe6060f1SDimitry Andric   if (UD) {
3310fe6060f1SDimitry Andric     SemaRef.InstantiateAttrs(TemplateArgs, D, UD);
33110b57cec5SDimitry Andric     SemaRef.Context.setInstantiatedFromUsingDecl(UD, D);
3312fe6060f1SDimitry Andric   }
33130b57cec5SDimitry Andric 
33140b57cec5SDimitry Andric   return UD;
33150b57cec5SDimitry Andric }
33160b57cec5SDimitry Andric 
33170b57cec5SDimitry Andric Decl *TemplateDeclInstantiator::VisitUnresolvedUsingTypenameDecl(
33180b57cec5SDimitry Andric     UnresolvedUsingTypenameDecl *D) {
33190b57cec5SDimitry Andric   return instantiateUnresolvedUsingDecl(D);
33200b57cec5SDimitry Andric }
33210b57cec5SDimitry Andric 
33220b57cec5SDimitry Andric Decl *TemplateDeclInstantiator::VisitUnresolvedUsingValueDecl(
33230b57cec5SDimitry Andric     UnresolvedUsingValueDecl *D) {
33240b57cec5SDimitry Andric   return instantiateUnresolvedUsingDecl(D);
33250b57cec5SDimitry Andric }
33260b57cec5SDimitry Andric 
3327fe6060f1SDimitry Andric Decl *TemplateDeclInstantiator::VisitUnresolvedUsingIfExistsDecl(
3328fe6060f1SDimitry Andric     UnresolvedUsingIfExistsDecl *D) {
3329fe6060f1SDimitry Andric   llvm_unreachable("referring to unresolved decl out of UsingShadowDecl");
3330fe6060f1SDimitry Andric }
3331fe6060f1SDimitry Andric 
33320b57cec5SDimitry Andric Decl *TemplateDeclInstantiator::VisitUsingPackDecl(UsingPackDecl *D) {
33330b57cec5SDimitry Andric   SmallVector<NamedDecl*, 8> Expansions;
33340b57cec5SDimitry Andric   for (auto *UD : D->expansions()) {
33350b57cec5SDimitry Andric     if (NamedDecl *NewUD =
33360b57cec5SDimitry Andric             SemaRef.FindInstantiatedDecl(D->getLocation(), UD, TemplateArgs))
33370b57cec5SDimitry Andric       Expansions.push_back(NewUD);
33380b57cec5SDimitry Andric     else
33390b57cec5SDimitry Andric       return nullptr;
33400b57cec5SDimitry Andric   }
33410b57cec5SDimitry Andric 
33420b57cec5SDimitry Andric   auto *NewD = SemaRef.BuildUsingPackDecl(D, Expansions);
33430b57cec5SDimitry Andric   if (isDeclWithinFunction(D))
33440b57cec5SDimitry Andric     SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewD);
33450b57cec5SDimitry Andric   return NewD;
33460b57cec5SDimitry Andric }
33470b57cec5SDimitry Andric 
33480b57cec5SDimitry Andric Decl *TemplateDeclInstantiator::VisitClassScopeFunctionSpecializationDecl(
33490b57cec5SDimitry Andric     ClassScopeFunctionSpecializationDecl *Decl) {
33500b57cec5SDimitry Andric   CXXMethodDecl *OldFD = Decl->getSpecialization();
33510b57cec5SDimitry Andric   return cast_or_null<CXXMethodDecl>(
33520b57cec5SDimitry Andric       VisitCXXMethodDecl(OldFD, nullptr, Decl->getTemplateArgsAsWritten()));
33530b57cec5SDimitry Andric }
33540b57cec5SDimitry Andric 
33550b57cec5SDimitry Andric Decl *TemplateDeclInstantiator::VisitOMPThreadPrivateDecl(
33560b57cec5SDimitry Andric                                      OMPThreadPrivateDecl *D) {
33570b57cec5SDimitry Andric   SmallVector<Expr *, 5> Vars;
33580b57cec5SDimitry Andric   for (auto *I : D->varlists()) {
33590b57cec5SDimitry Andric     Expr *Var = SemaRef.SubstExpr(I, TemplateArgs).get();
33600b57cec5SDimitry Andric     assert(isa<DeclRefExpr>(Var) && "threadprivate arg is not a DeclRefExpr");
33610b57cec5SDimitry Andric     Vars.push_back(Var);
33620b57cec5SDimitry Andric   }
33630b57cec5SDimitry Andric 
33640b57cec5SDimitry Andric   OMPThreadPrivateDecl *TD =
33650b57cec5SDimitry Andric     SemaRef.CheckOMPThreadPrivateDecl(D->getLocation(), Vars);
33660b57cec5SDimitry Andric 
33670b57cec5SDimitry Andric   TD->setAccess(AS_public);
33680b57cec5SDimitry Andric   Owner->addDecl(TD);
33690b57cec5SDimitry Andric 
33700b57cec5SDimitry Andric   return TD;
33710b57cec5SDimitry Andric }
33720b57cec5SDimitry Andric 
33730b57cec5SDimitry Andric Decl *TemplateDeclInstantiator::VisitOMPAllocateDecl(OMPAllocateDecl *D) {
33740b57cec5SDimitry Andric   SmallVector<Expr *, 5> Vars;
33750b57cec5SDimitry Andric   for (auto *I : D->varlists()) {
33760b57cec5SDimitry Andric     Expr *Var = SemaRef.SubstExpr(I, TemplateArgs).get();
33770b57cec5SDimitry Andric     assert(isa<DeclRefExpr>(Var) && "allocate arg is not a DeclRefExpr");
33780b57cec5SDimitry Andric     Vars.push_back(Var);
33790b57cec5SDimitry Andric   }
33800b57cec5SDimitry Andric   SmallVector<OMPClause *, 4> Clauses;
33810b57cec5SDimitry Andric   // Copy map clauses from the original mapper.
33820b57cec5SDimitry Andric   for (OMPClause *C : D->clauselists()) {
33830b57cec5SDimitry Andric     auto *AC = cast<OMPAllocatorClause>(C);
33840b57cec5SDimitry Andric     ExprResult NewE = SemaRef.SubstExpr(AC->getAllocator(), TemplateArgs);
33850b57cec5SDimitry Andric     if (!NewE.isUsable())
33860b57cec5SDimitry Andric       continue;
33870b57cec5SDimitry Andric     OMPClause *IC = SemaRef.ActOnOpenMPAllocatorClause(
33880b57cec5SDimitry Andric         NewE.get(), AC->getBeginLoc(), AC->getLParenLoc(), AC->getEndLoc());
33890b57cec5SDimitry Andric     Clauses.push_back(IC);
33900b57cec5SDimitry Andric   }
33910b57cec5SDimitry Andric 
33920b57cec5SDimitry Andric   Sema::DeclGroupPtrTy Res = SemaRef.ActOnOpenMPAllocateDirective(
33930b57cec5SDimitry Andric       D->getLocation(), Vars, Clauses, Owner);
33940b57cec5SDimitry Andric   if (Res.get().isNull())
33950b57cec5SDimitry Andric     return nullptr;
33960b57cec5SDimitry Andric   return Res.get().getSingleDecl();
33970b57cec5SDimitry Andric }
33980b57cec5SDimitry Andric 
33990b57cec5SDimitry Andric Decl *TemplateDeclInstantiator::VisitOMPRequiresDecl(OMPRequiresDecl *D) {
34000b57cec5SDimitry Andric   llvm_unreachable(
34010b57cec5SDimitry Andric       "Requires directive cannot be instantiated within a dependent context");
34020b57cec5SDimitry Andric }
34030b57cec5SDimitry Andric 
34040b57cec5SDimitry Andric Decl *TemplateDeclInstantiator::VisitOMPDeclareReductionDecl(
34050b57cec5SDimitry Andric     OMPDeclareReductionDecl *D) {
34060b57cec5SDimitry Andric   // Instantiate type and check if it is allowed.
34070b57cec5SDimitry Andric   const bool RequiresInstantiation =
34080b57cec5SDimitry Andric       D->getType()->isDependentType() ||
34090b57cec5SDimitry Andric       D->getType()->isInstantiationDependentType() ||
34100b57cec5SDimitry Andric       D->getType()->containsUnexpandedParameterPack();
34110b57cec5SDimitry Andric   QualType SubstReductionType;
34120b57cec5SDimitry Andric   if (RequiresInstantiation) {
34130b57cec5SDimitry Andric     SubstReductionType = SemaRef.ActOnOpenMPDeclareReductionType(
34140b57cec5SDimitry Andric         D->getLocation(),
34150b57cec5SDimitry Andric         ParsedType::make(SemaRef.SubstType(
34160b57cec5SDimitry Andric             D->getType(), TemplateArgs, D->getLocation(), DeclarationName())));
34170b57cec5SDimitry Andric   } else {
34180b57cec5SDimitry Andric     SubstReductionType = D->getType();
34190b57cec5SDimitry Andric   }
34200b57cec5SDimitry Andric   if (SubstReductionType.isNull())
34210b57cec5SDimitry Andric     return nullptr;
3422480093f4SDimitry Andric   Expr *Combiner = D->getCombiner();
3423480093f4SDimitry Andric   Expr *Init = D->getInitializer();
3424480093f4SDimitry Andric   bool IsCorrect = true;
34250b57cec5SDimitry Andric   // Create instantiated copy.
34260b57cec5SDimitry Andric   std::pair<QualType, SourceLocation> ReductionTypes[] = {
34270b57cec5SDimitry Andric       std::make_pair(SubstReductionType, D->getLocation())};
34280b57cec5SDimitry Andric   auto *PrevDeclInScope = D->getPrevDeclInScope();
34290b57cec5SDimitry Andric   if (PrevDeclInScope && !PrevDeclInScope->isInvalidDecl()) {
34300b57cec5SDimitry Andric     PrevDeclInScope = cast<OMPDeclareReductionDecl>(
34310b57cec5SDimitry Andric         SemaRef.CurrentInstantiationScope->findInstantiationOf(PrevDeclInScope)
34320b57cec5SDimitry Andric             ->get<Decl *>());
34330b57cec5SDimitry Andric   }
34340b57cec5SDimitry Andric   auto DRD = SemaRef.ActOnOpenMPDeclareReductionDirectiveStart(
34350b57cec5SDimitry Andric       /*S=*/nullptr, Owner, D->getDeclName(), ReductionTypes, D->getAccess(),
34360b57cec5SDimitry Andric       PrevDeclInScope);
34370b57cec5SDimitry Andric   auto *NewDRD = cast<OMPDeclareReductionDecl>(DRD.get().getSingleDecl());
34380b57cec5SDimitry Andric   SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewDRD);
34390b57cec5SDimitry Andric   Expr *SubstCombiner = nullptr;
34400b57cec5SDimitry Andric   Expr *SubstInitializer = nullptr;
34410b57cec5SDimitry Andric   // Combiners instantiation sequence.
3442480093f4SDimitry Andric   if (Combiner) {
34430b57cec5SDimitry Andric     SemaRef.ActOnOpenMPDeclareReductionCombinerStart(
34440b57cec5SDimitry Andric         /*S=*/nullptr, NewDRD);
34450b57cec5SDimitry Andric     SemaRef.CurrentInstantiationScope->InstantiatedLocal(
34460b57cec5SDimitry Andric         cast<DeclRefExpr>(D->getCombinerIn())->getDecl(),
34470b57cec5SDimitry Andric         cast<DeclRefExpr>(NewDRD->getCombinerIn())->getDecl());
34480b57cec5SDimitry Andric     SemaRef.CurrentInstantiationScope->InstantiatedLocal(
34490b57cec5SDimitry Andric         cast<DeclRefExpr>(D->getCombinerOut())->getDecl(),
34500b57cec5SDimitry Andric         cast<DeclRefExpr>(NewDRD->getCombinerOut())->getDecl());
34510b57cec5SDimitry Andric     auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(Owner);
34520b57cec5SDimitry Andric     Sema::CXXThisScopeRAII ThisScope(SemaRef, ThisContext, Qualifiers(),
34530b57cec5SDimitry Andric                                      ThisContext);
3454480093f4SDimitry Andric     SubstCombiner = SemaRef.SubstExpr(Combiner, TemplateArgs).get();
34550b57cec5SDimitry Andric     SemaRef.ActOnOpenMPDeclareReductionCombinerEnd(NewDRD, SubstCombiner);
3456480093f4SDimitry Andric   }
34570b57cec5SDimitry Andric   // Initializers instantiation sequence.
3458480093f4SDimitry Andric   if (Init) {
3459480093f4SDimitry Andric     VarDecl *OmpPrivParm = SemaRef.ActOnOpenMPDeclareReductionInitializerStart(
34600b57cec5SDimitry Andric         /*S=*/nullptr, NewDRD);
34610b57cec5SDimitry Andric     SemaRef.CurrentInstantiationScope->InstantiatedLocal(
34620b57cec5SDimitry Andric         cast<DeclRefExpr>(D->getInitOrig())->getDecl(),
34630b57cec5SDimitry Andric         cast<DeclRefExpr>(NewDRD->getInitOrig())->getDecl());
34640b57cec5SDimitry Andric     SemaRef.CurrentInstantiationScope->InstantiatedLocal(
34650b57cec5SDimitry Andric         cast<DeclRefExpr>(D->getInitPriv())->getDecl(),
34660b57cec5SDimitry Andric         cast<DeclRefExpr>(NewDRD->getInitPriv())->getDecl());
34670b57cec5SDimitry Andric     if (D->getInitializerKind() == OMPDeclareReductionDecl::CallInit) {
3468480093f4SDimitry Andric       SubstInitializer = SemaRef.SubstExpr(Init, TemplateArgs).get();
34690b57cec5SDimitry Andric     } else {
3470480093f4SDimitry Andric       auto *OldPrivParm =
3471480093f4SDimitry Andric           cast<VarDecl>(cast<DeclRefExpr>(D->getInitPriv())->getDecl());
3472480093f4SDimitry Andric       IsCorrect = IsCorrect && OldPrivParm->hasInit();
3473480093f4SDimitry Andric       if (IsCorrect)
3474480093f4SDimitry Andric         SemaRef.InstantiateVariableInitializer(OmpPrivParm, OldPrivParm,
3475480093f4SDimitry Andric                                                TemplateArgs);
34760b57cec5SDimitry Andric     }
3477480093f4SDimitry Andric     SemaRef.ActOnOpenMPDeclareReductionInitializerEnd(NewDRD, SubstInitializer,
3478480093f4SDimitry Andric                                                       OmpPrivParm);
34790b57cec5SDimitry Andric   }
3480480093f4SDimitry Andric   IsCorrect = IsCorrect && SubstCombiner &&
3481480093f4SDimitry Andric               (!Init ||
34820b57cec5SDimitry Andric                (D->getInitializerKind() == OMPDeclareReductionDecl::CallInit &&
34830b57cec5SDimitry Andric                 SubstInitializer) ||
34840b57cec5SDimitry Andric                (D->getInitializerKind() != OMPDeclareReductionDecl::CallInit &&
3485480093f4SDimitry Andric                 !SubstInitializer));
34860b57cec5SDimitry Andric 
3487480093f4SDimitry Andric   (void)SemaRef.ActOnOpenMPDeclareReductionDirectiveEnd(
3488480093f4SDimitry Andric       /*S=*/nullptr, DRD, IsCorrect && !D->isInvalidDecl());
34890b57cec5SDimitry Andric 
34900b57cec5SDimitry Andric   return NewDRD;
34910b57cec5SDimitry Andric }
34920b57cec5SDimitry Andric 
34930b57cec5SDimitry Andric Decl *
34940b57cec5SDimitry Andric TemplateDeclInstantiator::VisitOMPDeclareMapperDecl(OMPDeclareMapperDecl *D) {
34950b57cec5SDimitry Andric   // Instantiate type and check if it is allowed.
34960b57cec5SDimitry Andric   const bool RequiresInstantiation =
34970b57cec5SDimitry Andric       D->getType()->isDependentType() ||
34980b57cec5SDimitry Andric       D->getType()->isInstantiationDependentType() ||
34990b57cec5SDimitry Andric       D->getType()->containsUnexpandedParameterPack();
35000b57cec5SDimitry Andric   QualType SubstMapperTy;
35010b57cec5SDimitry Andric   DeclarationName VN = D->getVarName();
35020b57cec5SDimitry Andric   if (RequiresInstantiation) {
35030b57cec5SDimitry Andric     SubstMapperTy = SemaRef.ActOnOpenMPDeclareMapperType(
35040b57cec5SDimitry Andric         D->getLocation(),
35050b57cec5SDimitry Andric         ParsedType::make(SemaRef.SubstType(D->getType(), TemplateArgs,
35060b57cec5SDimitry Andric                                            D->getLocation(), VN)));
35070b57cec5SDimitry Andric   } else {
35080b57cec5SDimitry Andric     SubstMapperTy = D->getType();
35090b57cec5SDimitry Andric   }
35100b57cec5SDimitry Andric   if (SubstMapperTy.isNull())
35110b57cec5SDimitry Andric     return nullptr;
35120b57cec5SDimitry Andric   // Create an instantiated copy of mapper.
35130b57cec5SDimitry Andric   auto *PrevDeclInScope = D->getPrevDeclInScope();
35140b57cec5SDimitry Andric   if (PrevDeclInScope && !PrevDeclInScope->isInvalidDecl()) {
35150b57cec5SDimitry Andric     PrevDeclInScope = cast<OMPDeclareMapperDecl>(
35160b57cec5SDimitry Andric         SemaRef.CurrentInstantiationScope->findInstantiationOf(PrevDeclInScope)
35170b57cec5SDimitry Andric             ->get<Decl *>());
35180b57cec5SDimitry Andric   }
35190b57cec5SDimitry Andric   bool IsCorrect = true;
3520e8d8bef9SDimitry Andric   SmallVector<OMPClause *, 6> Clauses;
35210b57cec5SDimitry Andric   // Instantiate the mapper variable.
35220b57cec5SDimitry Andric   DeclarationNameInfo DirName;
3523480093f4SDimitry Andric   SemaRef.StartOpenMPDSABlock(llvm::omp::OMPD_declare_mapper, DirName,
3524480093f4SDimitry Andric                               /*S=*/nullptr,
35250b57cec5SDimitry Andric                               (*D->clauselist_begin())->getBeginLoc());
3526e8d8bef9SDimitry Andric   ExprResult MapperVarRef = SemaRef.ActOnOpenMPDeclareMapperDirectiveVarDecl(
3527e8d8bef9SDimitry Andric       /*S=*/nullptr, SubstMapperTy, D->getLocation(), VN);
35280b57cec5SDimitry Andric   SemaRef.CurrentInstantiationScope->InstantiatedLocal(
35290b57cec5SDimitry Andric       cast<DeclRefExpr>(D->getMapperVarRef())->getDecl(),
3530e8d8bef9SDimitry Andric       cast<DeclRefExpr>(MapperVarRef.get())->getDecl());
35310b57cec5SDimitry Andric   auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(Owner);
35320b57cec5SDimitry Andric   Sema::CXXThisScopeRAII ThisScope(SemaRef, ThisContext, Qualifiers(),
35330b57cec5SDimitry Andric                                    ThisContext);
35340b57cec5SDimitry Andric   // Instantiate map clauses.
35350b57cec5SDimitry Andric   for (OMPClause *C : D->clauselists()) {
35360b57cec5SDimitry Andric     auto *OldC = cast<OMPMapClause>(C);
35370b57cec5SDimitry Andric     SmallVector<Expr *, 4> NewVars;
35380b57cec5SDimitry Andric     for (Expr *OE : OldC->varlists()) {
35390b57cec5SDimitry Andric       Expr *NE = SemaRef.SubstExpr(OE, TemplateArgs).get();
35400b57cec5SDimitry Andric       if (!NE) {
35410b57cec5SDimitry Andric         IsCorrect = false;
35420b57cec5SDimitry Andric         break;
35430b57cec5SDimitry Andric       }
35440b57cec5SDimitry Andric       NewVars.push_back(NE);
35450b57cec5SDimitry Andric     }
35460b57cec5SDimitry Andric     if (!IsCorrect)
35470b57cec5SDimitry Andric       break;
35480b57cec5SDimitry Andric     NestedNameSpecifierLoc NewQualifierLoc =
35490b57cec5SDimitry Andric         SemaRef.SubstNestedNameSpecifierLoc(OldC->getMapperQualifierLoc(),
35500b57cec5SDimitry Andric                                             TemplateArgs);
35510b57cec5SDimitry Andric     CXXScopeSpec SS;
35520b57cec5SDimitry Andric     SS.Adopt(NewQualifierLoc);
3553e8d8bef9SDimitry Andric     DeclarationNameInfo NewNameInfo =
3554e8d8bef9SDimitry Andric         SemaRef.SubstDeclarationNameInfo(OldC->getMapperIdInfo(), TemplateArgs);
35550b57cec5SDimitry Andric     OMPVarListLocTy Locs(OldC->getBeginLoc(), OldC->getLParenLoc(),
35560b57cec5SDimitry Andric                          OldC->getEndLoc());
35570b57cec5SDimitry Andric     OMPClause *NewC = SemaRef.ActOnOpenMPMapClause(
35580b57cec5SDimitry Andric         OldC->getMapTypeModifiers(), OldC->getMapTypeModifiersLoc(), SS,
35590b57cec5SDimitry Andric         NewNameInfo, OldC->getMapType(), OldC->isImplicitMapType(),
35600b57cec5SDimitry Andric         OldC->getMapLoc(), OldC->getColonLoc(), NewVars, Locs);
35610b57cec5SDimitry Andric     Clauses.push_back(NewC);
35620b57cec5SDimitry Andric   }
35630b57cec5SDimitry Andric   SemaRef.EndOpenMPDSABlock(nullptr);
35640b57cec5SDimitry Andric   if (!IsCorrect)
35650b57cec5SDimitry Andric     return nullptr;
3566e8d8bef9SDimitry Andric   Sema::DeclGroupPtrTy DG = SemaRef.ActOnOpenMPDeclareMapperDirective(
3567e8d8bef9SDimitry Andric       /*S=*/nullptr, Owner, D->getDeclName(), SubstMapperTy, D->getLocation(),
3568e8d8bef9SDimitry Andric       VN, D->getAccess(), MapperVarRef.get(), Clauses, PrevDeclInScope);
3569e8d8bef9SDimitry Andric   Decl *NewDMD = DG.get().getSingleDecl();
3570e8d8bef9SDimitry Andric   SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewDMD);
35710b57cec5SDimitry Andric   return NewDMD;
35720b57cec5SDimitry Andric }
35730b57cec5SDimitry Andric 
35740b57cec5SDimitry Andric Decl *TemplateDeclInstantiator::VisitOMPCapturedExprDecl(
35750b57cec5SDimitry Andric     OMPCapturedExprDecl * /*D*/) {
35760b57cec5SDimitry Andric   llvm_unreachable("Should not be met in templates");
35770b57cec5SDimitry Andric }
35780b57cec5SDimitry Andric 
35790b57cec5SDimitry Andric Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D) {
35800b57cec5SDimitry Andric   return VisitFunctionDecl(D, nullptr);
35810b57cec5SDimitry Andric }
35820b57cec5SDimitry Andric 
35830b57cec5SDimitry Andric Decl *
35840b57cec5SDimitry Andric TemplateDeclInstantiator::VisitCXXDeductionGuideDecl(CXXDeductionGuideDecl *D) {
35850b57cec5SDimitry Andric   Decl *Inst = VisitFunctionDecl(D, nullptr);
35860b57cec5SDimitry Andric   if (Inst && !D->getDescribedFunctionTemplate())
35870b57cec5SDimitry Andric     Owner->addDecl(Inst);
35880b57cec5SDimitry Andric   return Inst;
35890b57cec5SDimitry Andric }
35900b57cec5SDimitry Andric 
35910b57cec5SDimitry Andric Decl *TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D) {
35920b57cec5SDimitry Andric   return VisitCXXMethodDecl(D, nullptr);
35930b57cec5SDimitry Andric }
35940b57cec5SDimitry Andric 
35950b57cec5SDimitry Andric Decl *TemplateDeclInstantiator::VisitRecordDecl(RecordDecl *D) {
35960b57cec5SDimitry Andric   llvm_unreachable("There are only CXXRecordDecls in C++");
35970b57cec5SDimitry Andric }
35980b57cec5SDimitry Andric 
35990b57cec5SDimitry Andric Decl *
36000b57cec5SDimitry Andric TemplateDeclInstantiator::VisitClassTemplateSpecializationDecl(
36010b57cec5SDimitry Andric     ClassTemplateSpecializationDecl *D) {
36020b57cec5SDimitry Andric   // As a MS extension, we permit class-scope explicit specialization
36030b57cec5SDimitry Andric   // of member class templates.
36040b57cec5SDimitry Andric   ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
36050b57cec5SDimitry Andric   assert(ClassTemplate->getDeclContext()->isRecord() &&
36060b57cec5SDimitry Andric          D->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
36070b57cec5SDimitry Andric          "can only instantiate an explicit specialization "
36080b57cec5SDimitry Andric          "for a member class template");
36090b57cec5SDimitry Andric 
36100b57cec5SDimitry Andric   // Lookup the already-instantiated declaration in the instantiation
36110b57cec5SDimitry Andric   // of the class template.
36120b57cec5SDimitry Andric   ClassTemplateDecl *InstClassTemplate =
36130b57cec5SDimitry Andric       cast_or_null<ClassTemplateDecl>(SemaRef.FindInstantiatedDecl(
36140b57cec5SDimitry Andric           D->getLocation(), ClassTemplate, TemplateArgs));
36150b57cec5SDimitry Andric   if (!InstClassTemplate)
36160b57cec5SDimitry Andric     return nullptr;
36170b57cec5SDimitry Andric 
36180b57cec5SDimitry Andric   // Substitute into the template arguments of the class template explicit
36190b57cec5SDimitry Andric   // specialization.
36200b57cec5SDimitry Andric   TemplateSpecializationTypeLoc Loc = D->getTypeAsWritten()->getTypeLoc().
36210b57cec5SDimitry Andric                                         castAs<TemplateSpecializationTypeLoc>();
36220b57cec5SDimitry Andric   TemplateArgumentListInfo InstTemplateArgs(Loc.getLAngleLoc(),
36230b57cec5SDimitry Andric                                             Loc.getRAngleLoc());
36240b57cec5SDimitry Andric   SmallVector<TemplateArgumentLoc, 4> ArgLocs;
36250b57cec5SDimitry Andric   for (unsigned I = 0; I != Loc.getNumArgs(); ++I)
36260b57cec5SDimitry Andric     ArgLocs.push_back(Loc.getArgLoc(I));
36270b57cec5SDimitry Andric   if (SemaRef.Subst(ArgLocs.data(), ArgLocs.size(),
36280b57cec5SDimitry Andric                     InstTemplateArgs, TemplateArgs))
36290b57cec5SDimitry Andric     return nullptr;
36300b57cec5SDimitry Andric 
36310b57cec5SDimitry Andric   // Check that the template argument list is well-formed for this
36320b57cec5SDimitry Andric   // class template.
36330b57cec5SDimitry Andric   SmallVector<TemplateArgument, 4> Converted;
36340b57cec5SDimitry Andric   if (SemaRef.CheckTemplateArgumentList(InstClassTemplate,
36350b57cec5SDimitry Andric                                         D->getLocation(),
36360b57cec5SDimitry Andric                                         InstTemplateArgs,
36370b57cec5SDimitry Andric                                         false,
3638480093f4SDimitry Andric                                         Converted,
3639480093f4SDimitry Andric                                         /*UpdateArgsWithConversion=*/true))
36400b57cec5SDimitry Andric     return nullptr;
36410b57cec5SDimitry Andric 
36420b57cec5SDimitry Andric   // Figure out where to insert this class template explicit specialization
36430b57cec5SDimitry Andric   // in the member template's set of class template explicit specializations.
36440b57cec5SDimitry Andric   void *InsertPos = nullptr;
36450b57cec5SDimitry Andric   ClassTemplateSpecializationDecl *PrevDecl =
36460b57cec5SDimitry Andric       InstClassTemplate->findSpecialization(Converted, InsertPos);
36470b57cec5SDimitry Andric 
36480b57cec5SDimitry Andric   // Check whether we've already seen a conflicting instantiation of this
36490b57cec5SDimitry Andric   // declaration (for instance, if there was a prior implicit instantiation).
36500b57cec5SDimitry Andric   bool Ignored;
36510b57cec5SDimitry Andric   if (PrevDecl &&
36520b57cec5SDimitry Andric       SemaRef.CheckSpecializationInstantiationRedecl(D->getLocation(),
36530b57cec5SDimitry Andric                                                      D->getSpecializationKind(),
36540b57cec5SDimitry Andric                                                      PrevDecl,
36550b57cec5SDimitry Andric                                                      PrevDecl->getSpecializationKind(),
36560b57cec5SDimitry Andric                                                      PrevDecl->getPointOfInstantiation(),
36570b57cec5SDimitry Andric                                                      Ignored))
36580b57cec5SDimitry Andric     return nullptr;
36590b57cec5SDimitry Andric 
36600b57cec5SDimitry Andric   // If PrevDecl was a definition and D is also a definition, diagnose.
36610b57cec5SDimitry Andric   // This happens in cases like:
36620b57cec5SDimitry Andric   //
36630b57cec5SDimitry Andric   //   template<typename T, typename U>
36640b57cec5SDimitry Andric   //   struct Outer {
36650b57cec5SDimitry Andric   //     template<typename X> struct Inner;
36660b57cec5SDimitry Andric   //     template<> struct Inner<T> {};
36670b57cec5SDimitry Andric   //     template<> struct Inner<U> {};
36680b57cec5SDimitry Andric   //   };
36690b57cec5SDimitry Andric   //
36700b57cec5SDimitry Andric   //   Outer<int, int> outer; // error: the explicit specializations of Inner
36710b57cec5SDimitry Andric   //                          // have the same signature.
36720b57cec5SDimitry Andric   if (PrevDecl && PrevDecl->getDefinition() &&
36730b57cec5SDimitry Andric       D->isThisDeclarationADefinition()) {
36740b57cec5SDimitry Andric     SemaRef.Diag(D->getLocation(), diag::err_redefinition) << PrevDecl;
36750b57cec5SDimitry Andric     SemaRef.Diag(PrevDecl->getDefinition()->getLocation(),
36760b57cec5SDimitry Andric                  diag::note_previous_definition);
36770b57cec5SDimitry Andric     return nullptr;
36780b57cec5SDimitry Andric   }
36790b57cec5SDimitry Andric 
36800b57cec5SDimitry Andric   // Create the class template partial specialization declaration.
36810b57cec5SDimitry Andric   ClassTemplateSpecializationDecl *InstD =
36820b57cec5SDimitry Andric       ClassTemplateSpecializationDecl::Create(
36830b57cec5SDimitry Andric           SemaRef.Context, D->getTagKind(), Owner, D->getBeginLoc(),
36840b57cec5SDimitry Andric           D->getLocation(), InstClassTemplate, Converted, PrevDecl);
36850b57cec5SDimitry Andric 
36860b57cec5SDimitry Andric   // Add this partial specialization to the set of class template partial
36870b57cec5SDimitry Andric   // specializations.
36880b57cec5SDimitry Andric   if (!PrevDecl)
36890b57cec5SDimitry Andric     InstClassTemplate->AddSpecialization(InstD, InsertPos);
36900b57cec5SDimitry Andric 
36910b57cec5SDimitry Andric   // Substitute the nested name specifier, if any.
36920b57cec5SDimitry Andric   if (SubstQualifier(D, InstD))
36930b57cec5SDimitry Andric     return nullptr;
36940b57cec5SDimitry Andric 
36950b57cec5SDimitry Andric   // Build the canonical type that describes the converted template
36960b57cec5SDimitry Andric   // arguments of the class template explicit specialization.
36970b57cec5SDimitry Andric   QualType CanonType = SemaRef.Context.getTemplateSpecializationType(
36980b57cec5SDimitry Andric       TemplateName(InstClassTemplate), Converted,
36990b57cec5SDimitry Andric       SemaRef.Context.getRecordType(InstD));
37000b57cec5SDimitry Andric 
37010b57cec5SDimitry Andric   // Build the fully-sugared type for this class template
37020b57cec5SDimitry Andric   // specialization as the user wrote in the specialization
37030b57cec5SDimitry Andric   // itself. This means that we'll pretty-print the type retrieved
37040b57cec5SDimitry Andric   // from the specialization's declaration the way that the user
37050b57cec5SDimitry Andric   // actually wrote the specialization, rather than formatting the
37060b57cec5SDimitry Andric   // name based on the "canonical" representation used to store the
37070b57cec5SDimitry Andric   // template arguments in the specialization.
37080b57cec5SDimitry Andric   TypeSourceInfo *WrittenTy = SemaRef.Context.getTemplateSpecializationTypeInfo(
37090b57cec5SDimitry Andric       TemplateName(InstClassTemplate), D->getLocation(), InstTemplateArgs,
37100b57cec5SDimitry Andric       CanonType);
37110b57cec5SDimitry Andric 
37120b57cec5SDimitry Andric   InstD->setAccess(D->getAccess());
37130b57cec5SDimitry Andric   InstD->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
37140b57cec5SDimitry Andric   InstD->setSpecializationKind(D->getSpecializationKind());
37150b57cec5SDimitry Andric   InstD->setTypeAsWritten(WrittenTy);
37160b57cec5SDimitry Andric   InstD->setExternLoc(D->getExternLoc());
37170b57cec5SDimitry Andric   InstD->setTemplateKeywordLoc(D->getTemplateKeywordLoc());
37180b57cec5SDimitry Andric 
37190b57cec5SDimitry Andric   Owner->addDecl(InstD);
37200b57cec5SDimitry Andric 
37210b57cec5SDimitry Andric   // Instantiate the members of the class-scope explicit specialization eagerly.
37220b57cec5SDimitry Andric   // We don't have support for lazy instantiation of an explicit specialization
37230b57cec5SDimitry Andric   // yet, and MSVC eagerly instantiates in this case.
37240b57cec5SDimitry Andric   // FIXME: This is wrong in standard C++.
37250b57cec5SDimitry Andric   if (D->isThisDeclarationADefinition() &&
37260b57cec5SDimitry Andric       SemaRef.InstantiateClass(D->getLocation(), InstD, D, TemplateArgs,
37270b57cec5SDimitry Andric                                TSK_ImplicitInstantiation,
37280b57cec5SDimitry Andric                                /*Complain=*/true))
37290b57cec5SDimitry Andric     return nullptr;
37300b57cec5SDimitry Andric 
37310b57cec5SDimitry Andric   return InstD;
37320b57cec5SDimitry Andric }
37330b57cec5SDimitry Andric 
37340b57cec5SDimitry Andric Decl *TemplateDeclInstantiator::VisitVarTemplateSpecializationDecl(
37350b57cec5SDimitry Andric     VarTemplateSpecializationDecl *D) {
37360b57cec5SDimitry Andric 
37370b57cec5SDimitry Andric   TemplateArgumentListInfo VarTemplateArgsInfo;
37380b57cec5SDimitry Andric   VarTemplateDecl *VarTemplate = D->getSpecializedTemplate();
37390b57cec5SDimitry Andric   assert(VarTemplate &&
37400b57cec5SDimitry Andric          "A template specialization without specialized template?");
37410b57cec5SDimitry Andric 
37420b57cec5SDimitry Andric   VarTemplateDecl *InstVarTemplate =
37430b57cec5SDimitry Andric       cast_or_null<VarTemplateDecl>(SemaRef.FindInstantiatedDecl(
37440b57cec5SDimitry Andric           D->getLocation(), VarTemplate, TemplateArgs));
37450b57cec5SDimitry Andric   if (!InstVarTemplate)
37460b57cec5SDimitry Andric     return nullptr;
37470b57cec5SDimitry Andric 
37480b57cec5SDimitry Andric   // Substitute the current template arguments.
37490b57cec5SDimitry Andric   const TemplateArgumentListInfo &TemplateArgsInfo = D->getTemplateArgsInfo();
37500b57cec5SDimitry Andric   VarTemplateArgsInfo.setLAngleLoc(TemplateArgsInfo.getLAngleLoc());
37510b57cec5SDimitry Andric   VarTemplateArgsInfo.setRAngleLoc(TemplateArgsInfo.getRAngleLoc());
37520b57cec5SDimitry Andric 
37530b57cec5SDimitry Andric   if (SemaRef.Subst(TemplateArgsInfo.getArgumentArray(),
37540b57cec5SDimitry Andric                     TemplateArgsInfo.size(), VarTemplateArgsInfo, TemplateArgs))
37550b57cec5SDimitry Andric     return nullptr;
37560b57cec5SDimitry Andric 
37570b57cec5SDimitry Andric   // Check that the template argument list is well-formed for this template.
37580b57cec5SDimitry Andric   SmallVector<TemplateArgument, 4> Converted;
37590b57cec5SDimitry Andric   if (SemaRef.CheckTemplateArgumentList(InstVarTemplate, D->getLocation(),
3760480093f4SDimitry Andric                                         VarTemplateArgsInfo, false, Converted,
3761480093f4SDimitry Andric                                         /*UpdateArgsWithConversion=*/true))
37620b57cec5SDimitry Andric     return nullptr;
37630b57cec5SDimitry Andric 
37640b57cec5SDimitry Andric   // Check whether we've already seen a declaration of this specialization.
37650b57cec5SDimitry Andric   void *InsertPos = nullptr;
37660b57cec5SDimitry Andric   VarTemplateSpecializationDecl *PrevDecl =
37670b57cec5SDimitry Andric       InstVarTemplate->findSpecialization(Converted, InsertPos);
37680b57cec5SDimitry Andric 
37690b57cec5SDimitry Andric   // Check whether we've already seen a conflicting instantiation of this
37700b57cec5SDimitry Andric   // declaration (for instance, if there was a prior implicit instantiation).
37710b57cec5SDimitry Andric   bool Ignored;
37720b57cec5SDimitry Andric   if (PrevDecl && SemaRef.CheckSpecializationInstantiationRedecl(
37730b57cec5SDimitry Andric                       D->getLocation(), D->getSpecializationKind(), PrevDecl,
37740b57cec5SDimitry Andric                       PrevDecl->getSpecializationKind(),
37750b57cec5SDimitry Andric                       PrevDecl->getPointOfInstantiation(), Ignored))
37760b57cec5SDimitry Andric     return nullptr;
37770b57cec5SDimitry Andric 
37780b57cec5SDimitry Andric   return VisitVarTemplateSpecializationDecl(
3779e8d8bef9SDimitry Andric       InstVarTemplate, D, VarTemplateArgsInfo, Converted, PrevDecl);
37800b57cec5SDimitry Andric }
37810b57cec5SDimitry Andric 
37820b57cec5SDimitry Andric Decl *TemplateDeclInstantiator::VisitVarTemplateSpecializationDecl(
3783e8d8bef9SDimitry Andric     VarTemplateDecl *VarTemplate, VarDecl *D,
37840b57cec5SDimitry Andric     const TemplateArgumentListInfo &TemplateArgsInfo,
37850b57cec5SDimitry Andric     ArrayRef<TemplateArgument> Converted,
37860b57cec5SDimitry Andric     VarTemplateSpecializationDecl *PrevDecl) {
37870b57cec5SDimitry Andric 
37880b57cec5SDimitry Andric   // Do substitution on the type of the declaration
37890b57cec5SDimitry Andric   TypeSourceInfo *DI =
37900b57cec5SDimitry Andric       SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs,
37910b57cec5SDimitry Andric                         D->getTypeSpecStartLoc(), D->getDeclName());
37920b57cec5SDimitry Andric   if (!DI)
37930b57cec5SDimitry Andric     return nullptr;
37940b57cec5SDimitry Andric 
37950b57cec5SDimitry Andric   if (DI->getType()->isFunctionType()) {
37960b57cec5SDimitry Andric     SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function)
37970b57cec5SDimitry Andric         << D->isStaticDataMember() << DI->getType();
37980b57cec5SDimitry Andric     return nullptr;
37990b57cec5SDimitry Andric   }
38000b57cec5SDimitry Andric 
38010b57cec5SDimitry Andric   // Build the instantiated declaration
38020b57cec5SDimitry Andric   VarTemplateSpecializationDecl *Var = VarTemplateSpecializationDecl::Create(
38030b57cec5SDimitry Andric       SemaRef.Context, Owner, D->getInnerLocStart(), D->getLocation(),
38040b57cec5SDimitry Andric       VarTemplate, DI->getType(), DI, D->getStorageClass(), Converted);
38050b57cec5SDimitry Andric   Var->setTemplateArgsInfo(TemplateArgsInfo);
3806eaeb601bSDimitry Andric   if (!PrevDecl) {
3807eaeb601bSDimitry Andric     void *InsertPos = nullptr;
3808eaeb601bSDimitry Andric     VarTemplate->findSpecialization(Converted, InsertPos);
38090b57cec5SDimitry Andric     VarTemplate->AddSpecialization(Var, InsertPos);
3810eaeb601bSDimitry Andric   }
38110b57cec5SDimitry Andric 
38125ffd83dbSDimitry Andric   if (SemaRef.getLangOpts().OpenCL)
38135ffd83dbSDimitry Andric     SemaRef.deduceOpenCLAddressSpace(Var);
38145ffd83dbSDimitry Andric 
38150b57cec5SDimitry Andric   // Substitute the nested name specifier, if any.
38160b57cec5SDimitry Andric   if (SubstQualifier(D, Var))
38170b57cec5SDimitry Andric     return nullptr;
38180b57cec5SDimitry Andric 
38190b57cec5SDimitry Andric   SemaRef.BuildVariableInstantiation(Var, D, TemplateArgs, LateAttrs, Owner,
38200b57cec5SDimitry Andric                                      StartingScope, false, PrevDecl);
38210b57cec5SDimitry Andric 
38220b57cec5SDimitry Andric   return Var;
38230b57cec5SDimitry Andric }
38240b57cec5SDimitry Andric 
38250b57cec5SDimitry Andric Decl *TemplateDeclInstantiator::VisitObjCAtDefsFieldDecl(ObjCAtDefsFieldDecl *D) {
38260b57cec5SDimitry Andric   llvm_unreachable("@defs is not supported in Objective-C++");
38270b57cec5SDimitry Andric }
38280b57cec5SDimitry Andric 
38290b57cec5SDimitry Andric Decl *TemplateDeclInstantiator::VisitFriendTemplateDecl(FriendTemplateDecl *D) {
38300b57cec5SDimitry Andric   // FIXME: We need to be able to instantiate FriendTemplateDecls.
38310b57cec5SDimitry Andric   unsigned DiagID = SemaRef.getDiagnostics().getCustomDiagID(
38320b57cec5SDimitry Andric                                                DiagnosticsEngine::Error,
38330b57cec5SDimitry Andric                                                "cannot instantiate %0 yet");
38340b57cec5SDimitry Andric   SemaRef.Diag(D->getLocation(), DiagID)
38350b57cec5SDimitry Andric     << D->getDeclKindName();
38360b57cec5SDimitry Andric 
38370b57cec5SDimitry Andric   return nullptr;
38380b57cec5SDimitry Andric }
38390b57cec5SDimitry Andric 
38400b57cec5SDimitry Andric Decl *TemplateDeclInstantiator::VisitConceptDecl(ConceptDecl *D) {
38410b57cec5SDimitry Andric   llvm_unreachable("Concept definitions cannot reside inside a template");
38420b57cec5SDimitry Andric }
38430b57cec5SDimitry Andric 
384455e4f9d5SDimitry Andric Decl *
384555e4f9d5SDimitry Andric TemplateDeclInstantiator::VisitRequiresExprBodyDecl(RequiresExprBodyDecl *D) {
384655e4f9d5SDimitry Andric   return RequiresExprBodyDecl::Create(SemaRef.Context, D->getDeclContext(),
384755e4f9d5SDimitry Andric                                       D->getBeginLoc());
384855e4f9d5SDimitry Andric }
384955e4f9d5SDimitry Andric 
38500b57cec5SDimitry Andric Decl *TemplateDeclInstantiator::VisitDecl(Decl *D) {
38510b57cec5SDimitry Andric   llvm_unreachable("Unexpected decl");
38520b57cec5SDimitry Andric }
38530b57cec5SDimitry Andric 
38540b57cec5SDimitry Andric Decl *Sema::SubstDecl(Decl *D, DeclContext *Owner,
38550b57cec5SDimitry Andric                       const MultiLevelTemplateArgumentList &TemplateArgs) {
38560b57cec5SDimitry Andric   TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
38570b57cec5SDimitry Andric   if (D->isInvalidDecl())
38580b57cec5SDimitry Andric     return nullptr;
38590b57cec5SDimitry Andric 
3860a7dea167SDimitry Andric   Decl *SubstD;
3861a7dea167SDimitry Andric   runWithSufficientStackSpace(D->getLocation(), [&] {
3862a7dea167SDimitry Andric     SubstD = Instantiator.Visit(D);
3863a7dea167SDimitry Andric   });
3864a7dea167SDimitry Andric   return SubstD;
38650b57cec5SDimitry Andric }
38660b57cec5SDimitry Andric 
3867480093f4SDimitry Andric void TemplateDeclInstantiator::adjustForRewrite(RewriteKind RK,
3868480093f4SDimitry Andric                                                 FunctionDecl *Orig, QualType &T,
3869480093f4SDimitry Andric                                                 TypeSourceInfo *&TInfo,
3870480093f4SDimitry Andric                                                 DeclarationNameInfo &NameInfo) {
3871480093f4SDimitry Andric   assert(RK == RewriteKind::RewriteSpaceshipAsEqualEqual);
3872480093f4SDimitry Andric 
3873480093f4SDimitry Andric   // C++2a [class.compare.default]p3:
3874480093f4SDimitry Andric   //   the return type is replaced with bool
3875480093f4SDimitry Andric   auto *FPT = T->castAs<FunctionProtoType>();
3876480093f4SDimitry Andric   T = SemaRef.Context.getFunctionType(
3877480093f4SDimitry Andric       SemaRef.Context.BoolTy, FPT->getParamTypes(), FPT->getExtProtoInfo());
3878480093f4SDimitry Andric 
3879480093f4SDimitry Andric   // Update the return type in the source info too. The most straightforward
3880480093f4SDimitry Andric   // way is to create new TypeSourceInfo for the new type. Use the location of
3881480093f4SDimitry Andric   // the '= default' as the location of the new type.
3882480093f4SDimitry Andric   //
3883480093f4SDimitry Andric   // FIXME: Set the correct return type when we initially transform the type,
3884480093f4SDimitry Andric   // rather than delaying it to now.
3885480093f4SDimitry Andric   TypeSourceInfo *NewTInfo =
3886480093f4SDimitry Andric       SemaRef.Context.getTrivialTypeSourceInfo(T, Orig->getEndLoc());
3887480093f4SDimitry Andric   auto OldLoc = TInfo->getTypeLoc().getAsAdjusted<FunctionProtoTypeLoc>();
3888480093f4SDimitry Andric   assert(OldLoc && "type of function is not a function type?");
3889480093f4SDimitry Andric   auto NewLoc = NewTInfo->getTypeLoc().castAs<FunctionProtoTypeLoc>();
3890480093f4SDimitry Andric   for (unsigned I = 0, N = OldLoc.getNumParams(); I != N; ++I)
3891480093f4SDimitry Andric     NewLoc.setParam(I, OldLoc.getParam(I));
3892480093f4SDimitry Andric   TInfo = NewTInfo;
3893480093f4SDimitry Andric 
3894480093f4SDimitry Andric   //   and the declarator-id is replaced with operator==
3895480093f4SDimitry Andric   NameInfo.setName(
3896480093f4SDimitry Andric       SemaRef.Context.DeclarationNames.getCXXOperatorName(OO_EqualEqual));
3897480093f4SDimitry Andric }
3898480093f4SDimitry Andric 
3899480093f4SDimitry Andric FunctionDecl *Sema::SubstSpaceshipAsEqualEqual(CXXRecordDecl *RD,
3900480093f4SDimitry Andric                                                FunctionDecl *Spaceship) {
3901480093f4SDimitry Andric   if (Spaceship->isInvalidDecl())
3902480093f4SDimitry Andric     return nullptr;
3903480093f4SDimitry Andric 
3904480093f4SDimitry Andric   // C++2a [class.compare.default]p3:
3905480093f4SDimitry Andric   //   an == operator function is declared implicitly [...] with the same
3906480093f4SDimitry Andric   //   access and function-definition and in the same class scope as the
3907480093f4SDimitry Andric   //   three-way comparison operator function
3908480093f4SDimitry Andric   MultiLevelTemplateArgumentList NoTemplateArgs;
39095ffd83dbSDimitry Andric   NoTemplateArgs.setKind(TemplateSubstitutionKind::Rewrite);
39105ffd83dbSDimitry Andric   NoTemplateArgs.addOuterRetainedLevels(RD->getTemplateDepth());
3911480093f4SDimitry Andric   TemplateDeclInstantiator Instantiator(*this, RD, NoTemplateArgs);
3912480093f4SDimitry Andric   Decl *R;
3913480093f4SDimitry Andric   if (auto *MD = dyn_cast<CXXMethodDecl>(Spaceship)) {
3914480093f4SDimitry Andric     R = Instantiator.VisitCXXMethodDecl(
3915480093f4SDimitry Andric         MD, nullptr, None,
3916480093f4SDimitry Andric         TemplateDeclInstantiator::RewriteKind::RewriteSpaceshipAsEqualEqual);
3917480093f4SDimitry Andric   } else {
3918480093f4SDimitry Andric     assert(Spaceship->getFriendObjectKind() &&
3919480093f4SDimitry Andric            "defaulted spaceship is neither a member nor a friend");
3920480093f4SDimitry Andric 
3921480093f4SDimitry Andric     R = Instantiator.VisitFunctionDecl(
3922480093f4SDimitry Andric         Spaceship, nullptr,
3923480093f4SDimitry Andric         TemplateDeclInstantiator::RewriteKind::RewriteSpaceshipAsEqualEqual);
3924480093f4SDimitry Andric     if (!R)
3925480093f4SDimitry Andric       return nullptr;
3926480093f4SDimitry Andric 
3927480093f4SDimitry Andric     FriendDecl *FD =
3928480093f4SDimitry Andric         FriendDecl::Create(Context, RD, Spaceship->getLocation(),
3929480093f4SDimitry Andric                            cast<NamedDecl>(R), Spaceship->getBeginLoc());
3930480093f4SDimitry Andric     FD->setAccess(AS_public);
3931480093f4SDimitry Andric     RD->addDecl(FD);
3932480093f4SDimitry Andric   }
3933480093f4SDimitry Andric   return cast_or_null<FunctionDecl>(R);
3934480093f4SDimitry Andric }
3935480093f4SDimitry Andric 
39360b57cec5SDimitry Andric /// Instantiates a nested template parameter list in the current
39370b57cec5SDimitry Andric /// instantiation context.
39380b57cec5SDimitry Andric ///
39390b57cec5SDimitry Andric /// \param L The parameter list to instantiate
39400b57cec5SDimitry Andric ///
39410b57cec5SDimitry Andric /// \returns NULL if there was an error
39420b57cec5SDimitry Andric TemplateParameterList *
39430b57cec5SDimitry Andric TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList *L) {
39440b57cec5SDimitry Andric   // Get errors for all the parameters before bailing out.
39450b57cec5SDimitry Andric   bool Invalid = false;
39460b57cec5SDimitry Andric 
39470b57cec5SDimitry Andric   unsigned N = L->size();
39480b57cec5SDimitry Andric   typedef SmallVector<NamedDecl *, 8> ParamVector;
39490b57cec5SDimitry Andric   ParamVector Params;
39500b57cec5SDimitry Andric   Params.reserve(N);
39510b57cec5SDimitry Andric   for (auto &P : *L) {
39520b57cec5SDimitry Andric     NamedDecl *D = cast_or_null<NamedDecl>(Visit(P));
39530b57cec5SDimitry Andric     Params.push_back(D);
39540b57cec5SDimitry Andric     Invalid = Invalid || !D || D->isInvalidDecl();
39550b57cec5SDimitry Andric   }
39560b57cec5SDimitry Andric 
39570b57cec5SDimitry Andric   // Clean up if we had an error.
39580b57cec5SDimitry Andric   if (Invalid)
39590b57cec5SDimitry Andric     return nullptr;
39600b57cec5SDimitry Andric 
3961a7dea167SDimitry Andric   // FIXME: Concepts: Substitution into requires clause should only happen when
3962a7dea167SDimitry Andric   // checking satisfaction.
3963a7dea167SDimitry Andric   Expr *InstRequiresClause = nullptr;
3964a7dea167SDimitry Andric   if (Expr *E = L->getRequiresClause()) {
396555e4f9d5SDimitry Andric     EnterExpressionEvaluationContext ConstantEvaluated(
396655e4f9d5SDimitry Andric         SemaRef, Sema::ExpressionEvaluationContext::Unevaluated);
3967a7dea167SDimitry Andric     ExprResult Res = SemaRef.SubstExpr(E, TemplateArgs);
3968a7dea167SDimitry Andric     if (Res.isInvalid() || !Res.isUsable()) {
3969a7dea167SDimitry Andric       return nullptr;
3970a7dea167SDimitry Andric     }
3971a7dea167SDimitry Andric     InstRequiresClause = Res.get();
3972a7dea167SDimitry Andric   }
39730b57cec5SDimitry Andric 
39740b57cec5SDimitry Andric   TemplateParameterList *InstL
39750b57cec5SDimitry Andric     = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(),
39760b57cec5SDimitry Andric                                     L->getLAngleLoc(), Params,
3977a7dea167SDimitry Andric                                     L->getRAngleLoc(), InstRequiresClause);
39780b57cec5SDimitry Andric   return InstL;
39790b57cec5SDimitry Andric }
39800b57cec5SDimitry Andric 
39810b57cec5SDimitry Andric TemplateParameterList *
39820b57cec5SDimitry Andric Sema::SubstTemplateParams(TemplateParameterList *Params, DeclContext *Owner,
39830b57cec5SDimitry Andric                           const MultiLevelTemplateArgumentList &TemplateArgs) {
39840b57cec5SDimitry Andric   TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
39850b57cec5SDimitry Andric   return Instantiator.SubstTemplateParams(Params);
39860b57cec5SDimitry Andric }
39870b57cec5SDimitry Andric 
39880b57cec5SDimitry Andric /// Instantiate the declaration of a class template partial
39890b57cec5SDimitry Andric /// specialization.
39900b57cec5SDimitry Andric ///
39910b57cec5SDimitry Andric /// \param ClassTemplate the (instantiated) class template that is partially
39920b57cec5SDimitry Andric // specialized by the instantiation of \p PartialSpec.
39930b57cec5SDimitry Andric ///
39940b57cec5SDimitry Andric /// \param PartialSpec the (uninstantiated) class template partial
39950b57cec5SDimitry Andric /// specialization that we are instantiating.
39960b57cec5SDimitry Andric ///
39970b57cec5SDimitry Andric /// \returns The instantiated partial specialization, if successful; otherwise,
39980b57cec5SDimitry Andric /// NULL to indicate an error.
39990b57cec5SDimitry Andric ClassTemplatePartialSpecializationDecl *
40000b57cec5SDimitry Andric TemplateDeclInstantiator::InstantiateClassTemplatePartialSpecialization(
40010b57cec5SDimitry Andric                                             ClassTemplateDecl *ClassTemplate,
40020b57cec5SDimitry Andric                           ClassTemplatePartialSpecializationDecl *PartialSpec) {
40030b57cec5SDimitry Andric   // Create a local instantiation scope for this class template partial
40040b57cec5SDimitry Andric   // specialization, which will contain the instantiations of the template
40050b57cec5SDimitry Andric   // parameters.
40060b57cec5SDimitry Andric   LocalInstantiationScope Scope(SemaRef);
40070b57cec5SDimitry Andric 
40080b57cec5SDimitry Andric   // Substitute into the template parameters of the class template partial
40090b57cec5SDimitry Andric   // specialization.
40100b57cec5SDimitry Andric   TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
40110b57cec5SDimitry Andric   TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
40120b57cec5SDimitry Andric   if (!InstParams)
40130b57cec5SDimitry Andric     return nullptr;
40140b57cec5SDimitry Andric 
40150b57cec5SDimitry Andric   // Substitute into the template arguments of the class template partial
40160b57cec5SDimitry Andric   // specialization.
40170b57cec5SDimitry Andric   const ASTTemplateArgumentListInfo *TemplArgInfo
40180b57cec5SDimitry Andric     = PartialSpec->getTemplateArgsAsWritten();
40190b57cec5SDimitry Andric   TemplateArgumentListInfo InstTemplateArgs(TemplArgInfo->LAngleLoc,
40200b57cec5SDimitry Andric                                             TemplArgInfo->RAngleLoc);
40210b57cec5SDimitry Andric   if (SemaRef.Subst(TemplArgInfo->getTemplateArgs(),
40220b57cec5SDimitry Andric                     TemplArgInfo->NumTemplateArgs,
40230b57cec5SDimitry Andric                     InstTemplateArgs, TemplateArgs))
40240b57cec5SDimitry Andric     return nullptr;
40250b57cec5SDimitry Andric 
40260b57cec5SDimitry Andric   // Check that the template argument list is well-formed for this
40270b57cec5SDimitry Andric   // class template.
40280b57cec5SDimitry Andric   SmallVector<TemplateArgument, 4> Converted;
40290b57cec5SDimitry Andric   if (SemaRef.CheckTemplateArgumentList(ClassTemplate,
40300b57cec5SDimitry Andric                                         PartialSpec->getLocation(),
40310b57cec5SDimitry Andric                                         InstTemplateArgs,
40320b57cec5SDimitry Andric                                         false,
40330b57cec5SDimitry Andric                                         Converted))
40340b57cec5SDimitry Andric     return nullptr;
40350b57cec5SDimitry Andric 
40360b57cec5SDimitry Andric   // Check these arguments are valid for a template partial specialization.
40370b57cec5SDimitry Andric   if (SemaRef.CheckTemplatePartialSpecializationArgs(
40380b57cec5SDimitry Andric           PartialSpec->getLocation(), ClassTemplate, InstTemplateArgs.size(),
40390b57cec5SDimitry Andric           Converted))
40400b57cec5SDimitry Andric     return nullptr;
40410b57cec5SDimitry Andric 
40420b57cec5SDimitry Andric   // Figure out where to insert this class template partial specialization
40430b57cec5SDimitry Andric   // in the member template's set of class template partial specializations.
40440b57cec5SDimitry Andric   void *InsertPos = nullptr;
40450b57cec5SDimitry Andric   ClassTemplateSpecializationDecl *PrevDecl
4046480093f4SDimitry Andric     = ClassTemplate->findPartialSpecialization(Converted, InstParams,
4047480093f4SDimitry Andric                                                InsertPos);
40480b57cec5SDimitry Andric 
40490b57cec5SDimitry Andric   // Build the canonical type that describes the converted template
40500b57cec5SDimitry Andric   // arguments of the class template partial specialization.
40510b57cec5SDimitry Andric   QualType CanonType
40520b57cec5SDimitry Andric     = SemaRef.Context.getTemplateSpecializationType(TemplateName(ClassTemplate),
40530b57cec5SDimitry Andric                                                     Converted);
40540b57cec5SDimitry Andric 
40550b57cec5SDimitry Andric   // Build the fully-sugared type for this class template
40560b57cec5SDimitry Andric   // specialization as the user wrote in the specialization
40570b57cec5SDimitry Andric   // itself. This means that we'll pretty-print the type retrieved
40580b57cec5SDimitry Andric   // from the specialization's declaration the way that the user
40590b57cec5SDimitry Andric   // actually wrote the specialization, rather than formatting the
40600b57cec5SDimitry Andric   // name based on the "canonical" representation used to store the
40610b57cec5SDimitry Andric   // template arguments in the specialization.
40620b57cec5SDimitry Andric   TypeSourceInfo *WrittenTy
40630b57cec5SDimitry Andric     = SemaRef.Context.getTemplateSpecializationTypeInfo(
40640b57cec5SDimitry Andric                                                     TemplateName(ClassTemplate),
40650b57cec5SDimitry Andric                                                     PartialSpec->getLocation(),
40660b57cec5SDimitry Andric                                                     InstTemplateArgs,
40670b57cec5SDimitry Andric                                                     CanonType);
40680b57cec5SDimitry Andric 
40690b57cec5SDimitry Andric   if (PrevDecl) {
40700b57cec5SDimitry Andric     // We've already seen a partial specialization with the same template
40710b57cec5SDimitry Andric     // parameters and template arguments. This can happen, for example, when
40720b57cec5SDimitry Andric     // substituting the outer template arguments ends up causing two
40730b57cec5SDimitry Andric     // class template partial specializations of a member class template
40740b57cec5SDimitry Andric     // to have identical forms, e.g.,
40750b57cec5SDimitry Andric     //
40760b57cec5SDimitry Andric     //   template<typename T, typename U>
40770b57cec5SDimitry Andric     //   struct Outer {
40780b57cec5SDimitry Andric     //     template<typename X, typename Y> struct Inner;
40790b57cec5SDimitry Andric     //     template<typename Y> struct Inner<T, Y>;
40800b57cec5SDimitry Andric     //     template<typename Y> struct Inner<U, Y>;
40810b57cec5SDimitry Andric     //   };
40820b57cec5SDimitry Andric     //
40830b57cec5SDimitry Andric     //   Outer<int, int> outer; // error: the partial specializations of Inner
40840b57cec5SDimitry Andric     //                          // have the same signature.
40850b57cec5SDimitry Andric     SemaRef.Diag(PartialSpec->getLocation(), diag::err_partial_spec_redeclared)
40860b57cec5SDimitry Andric       << WrittenTy->getType();
40870b57cec5SDimitry Andric     SemaRef.Diag(PrevDecl->getLocation(), diag::note_prev_partial_spec_here)
40880b57cec5SDimitry Andric       << SemaRef.Context.getTypeDeclType(PrevDecl);
40890b57cec5SDimitry Andric     return nullptr;
40900b57cec5SDimitry Andric   }
40910b57cec5SDimitry Andric 
40920b57cec5SDimitry Andric 
40930b57cec5SDimitry Andric   // Create the class template partial specialization declaration.
40940b57cec5SDimitry Andric   ClassTemplatePartialSpecializationDecl *InstPartialSpec =
40950b57cec5SDimitry Andric       ClassTemplatePartialSpecializationDecl::Create(
40960b57cec5SDimitry Andric           SemaRef.Context, PartialSpec->getTagKind(), Owner,
40970b57cec5SDimitry Andric           PartialSpec->getBeginLoc(), PartialSpec->getLocation(), InstParams,
40980b57cec5SDimitry Andric           ClassTemplate, Converted, InstTemplateArgs, CanonType, nullptr);
40990b57cec5SDimitry Andric   // Substitute the nested name specifier, if any.
41000b57cec5SDimitry Andric   if (SubstQualifier(PartialSpec, InstPartialSpec))
41010b57cec5SDimitry Andric     return nullptr;
41020b57cec5SDimitry Andric 
41030b57cec5SDimitry Andric   InstPartialSpec->setInstantiatedFromMember(PartialSpec);
41040b57cec5SDimitry Andric   InstPartialSpec->setTypeAsWritten(WrittenTy);
41050b57cec5SDimitry Andric 
41060b57cec5SDimitry Andric   // Check the completed partial specialization.
41070b57cec5SDimitry Andric   SemaRef.CheckTemplatePartialSpecialization(InstPartialSpec);
41080b57cec5SDimitry Andric 
41090b57cec5SDimitry Andric   // Add this partial specialization to the set of class template partial
41100b57cec5SDimitry Andric   // specializations.
41110b57cec5SDimitry Andric   ClassTemplate->AddPartialSpecialization(InstPartialSpec,
41120b57cec5SDimitry Andric                                           /*InsertPos=*/nullptr);
41130b57cec5SDimitry Andric   return InstPartialSpec;
41140b57cec5SDimitry Andric }
41150b57cec5SDimitry Andric 
41160b57cec5SDimitry Andric /// Instantiate the declaration of a variable template partial
41170b57cec5SDimitry Andric /// specialization.
41180b57cec5SDimitry Andric ///
41190b57cec5SDimitry Andric /// \param VarTemplate the (instantiated) variable template that is partially
41200b57cec5SDimitry Andric /// specialized by the instantiation of \p PartialSpec.
41210b57cec5SDimitry Andric ///
41220b57cec5SDimitry Andric /// \param PartialSpec the (uninstantiated) variable template partial
41230b57cec5SDimitry Andric /// specialization that we are instantiating.
41240b57cec5SDimitry Andric ///
41250b57cec5SDimitry Andric /// \returns The instantiated partial specialization, if successful; otherwise,
41260b57cec5SDimitry Andric /// NULL to indicate an error.
41270b57cec5SDimitry Andric VarTemplatePartialSpecializationDecl *
41280b57cec5SDimitry Andric TemplateDeclInstantiator::InstantiateVarTemplatePartialSpecialization(
41290b57cec5SDimitry Andric     VarTemplateDecl *VarTemplate,
41300b57cec5SDimitry Andric     VarTemplatePartialSpecializationDecl *PartialSpec) {
41310b57cec5SDimitry Andric   // Create a local instantiation scope for this variable template partial
41320b57cec5SDimitry Andric   // specialization, which will contain the instantiations of the template
41330b57cec5SDimitry Andric   // parameters.
41340b57cec5SDimitry Andric   LocalInstantiationScope Scope(SemaRef);
41350b57cec5SDimitry Andric 
41360b57cec5SDimitry Andric   // Substitute into the template parameters of the variable template partial
41370b57cec5SDimitry Andric   // specialization.
41380b57cec5SDimitry Andric   TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
41390b57cec5SDimitry Andric   TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
41400b57cec5SDimitry Andric   if (!InstParams)
41410b57cec5SDimitry Andric     return nullptr;
41420b57cec5SDimitry Andric 
41430b57cec5SDimitry Andric   // Substitute into the template arguments of the variable template partial
41440b57cec5SDimitry Andric   // specialization.
41450b57cec5SDimitry Andric   const ASTTemplateArgumentListInfo *TemplArgInfo
41460b57cec5SDimitry Andric     = PartialSpec->getTemplateArgsAsWritten();
41470b57cec5SDimitry Andric   TemplateArgumentListInfo InstTemplateArgs(TemplArgInfo->LAngleLoc,
41480b57cec5SDimitry Andric                                             TemplArgInfo->RAngleLoc);
41490b57cec5SDimitry Andric   if (SemaRef.Subst(TemplArgInfo->getTemplateArgs(),
41500b57cec5SDimitry Andric                     TemplArgInfo->NumTemplateArgs,
41510b57cec5SDimitry Andric                     InstTemplateArgs, TemplateArgs))
41520b57cec5SDimitry Andric     return nullptr;
41530b57cec5SDimitry Andric 
41540b57cec5SDimitry Andric   // Check that the template argument list is well-formed for this
41550b57cec5SDimitry Andric   // class template.
41560b57cec5SDimitry Andric   SmallVector<TemplateArgument, 4> Converted;
41570b57cec5SDimitry Andric   if (SemaRef.CheckTemplateArgumentList(VarTemplate, PartialSpec->getLocation(),
41580b57cec5SDimitry Andric                                         InstTemplateArgs, false, Converted))
41590b57cec5SDimitry Andric     return nullptr;
41600b57cec5SDimitry Andric 
41610b57cec5SDimitry Andric   // Check these arguments are valid for a template partial specialization.
41620b57cec5SDimitry Andric   if (SemaRef.CheckTemplatePartialSpecializationArgs(
41630b57cec5SDimitry Andric           PartialSpec->getLocation(), VarTemplate, InstTemplateArgs.size(),
41640b57cec5SDimitry Andric           Converted))
41650b57cec5SDimitry Andric     return nullptr;
41660b57cec5SDimitry Andric 
41670b57cec5SDimitry Andric   // Figure out where to insert this variable template partial specialization
41680b57cec5SDimitry Andric   // in the member template's set of variable template partial specializations.
41690b57cec5SDimitry Andric   void *InsertPos = nullptr;
41700b57cec5SDimitry Andric   VarTemplateSpecializationDecl *PrevDecl =
4171480093f4SDimitry Andric       VarTemplate->findPartialSpecialization(Converted, InstParams, InsertPos);
41720b57cec5SDimitry Andric 
41730b57cec5SDimitry Andric   // Build the canonical type that describes the converted template
41740b57cec5SDimitry Andric   // arguments of the variable template partial specialization.
41750b57cec5SDimitry Andric   QualType CanonType = SemaRef.Context.getTemplateSpecializationType(
41760b57cec5SDimitry Andric       TemplateName(VarTemplate), Converted);
41770b57cec5SDimitry Andric 
41780b57cec5SDimitry Andric   // Build the fully-sugared type for this variable template
41790b57cec5SDimitry Andric   // specialization as the user wrote in the specialization
41800b57cec5SDimitry Andric   // itself. This means that we'll pretty-print the type retrieved
41810b57cec5SDimitry Andric   // from the specialization's declaration the way that the user
41820b57cec5SDimitry Andric   // actually wrote the specialization, rather than formatting the
41830b57cec5SDimitry Andric   // name based on the "canonical" representation used to store the
41840b57cec5SDimitry Andric   // template arguments in the specialization.
41850b57cec5SDimitry Andric   TypeSourceInfo *WrittenTy = SemaRef.Context.getTemplateSpecializationTypeInfo(
41860b57cec5SDimitry Andric       TemplateName(VarTemplate), PartialSpec->getLocation(), InstTemplateArgs,
41870b57cec5SDimitry Andric       CanonType);
41880b57cec5SDimitry Andric 
41890b57cec5SDimitry Andric   if (PrevDecl) {
41900b57cec5SDimitry Andric     // We've already seen a partial specialization with the same template
41910b57cec5SDimitry Andric     // parameters and template arguments. This can happen, for example, when
41920b57cec5SDimitry Andric     // substituting the outer template arguments ends up causing two
41930b57cec5SDimitry Andric     // variable template partial specializations of a member variable template
41940b57cec5SDimitry Andric     // to have identical forms, e.g.,
41950b57cec5SDimitry Andric     //
41960b57cec5SDimitry Andric     //   template<typename T, typename U>
41970b57cec5SDimitry Andric     //   struct Outer {
41980b57cec5SDimitry Andric     //     template<typename X, typename Y> pair<X,Y> p;
41990b57cec5SDimitry Andric     //     template<typename Y> pair<T, Y> p;
42000b57cec5SDimitry Andric     //     template<typename Y> pair<U, Y> p;
42010b57cec5SDimitry Andric     //   };
42020b57cec5SDimitry Andric     //
42030b57cec5SDimitry Andric     //   Outer<int, int> outer; // error: the partial specializations of Inner
42040b57cec5SDimitry Andric     //                          // have the same signature.
42050b57cec5SDimitry Andric     SemaRef.Diag(PartialSpec->getLocation(),
42060b57cec5SDimitry Andric                  diag::err_var_partial_spec_redeclared)
42070b57cec5SDimitry Andric         << WrittenTy->getType();
42080b57cec5SDimitry Andric     SemaRef.Diag(PrevDecl->getLocation(),
42090b57cec5SDimitry Andric                  diag::note_var_prev_partial_spec_here);
42100b57cec5SDimitry Andric     return nullptr;
42110b57cec5SDimitry Andric   }
42120b57cec5SDimitry Andric 
42130b57cec5SDimitry Andric   // Do substitution on the type of the declaration
42140b57cec5SDimitry Andric   TypeSourceInfo *DI = SemaRef.SubstType(
42150b57cec5SDimitry Andric       PartialSpec->getTypeSourceInfo(), TemplateArgs,
42160b57cec5SDimitry Andric       PartialSpec->getTypeSpecStartLoc(), PartialSpec->getDeclName());
42170b57cec5SDimitry Andric   if (!DI)
42180b57cec5SDimitry Andric     return nullptr;
42190b57cec5SDimitry Andric 
42200b57cec5SDimitry Andric   if (DI->getType()->isFunctionType()) {
42210b57cec5SDimitry Andric     SemaRef.Diag(PartialSpec->getLocation(),
42220b57cec5SDimitry Andric                  diag::err_variable_instantiates_to_function)
42230b57cec5SDimitry Andric         << PartialSpec->isStaticDataMember() << DI->getType();
42240b57cec5SDimitry Andric     return nullptr;
42250b57cec5SDimitry Andric   }
42260b57cec5SDimitry Andric 
42270b57cec5SDimitry Andric   // Create the variable template partial specialization declaration.
42280b57cec5SDimitry Andric   VarTemplatePartialSpecializationDecl *InstPartialSpec =
42290b57cec5SDimitry Andric       VarTemplatePartialSpecializationDecl::Create(
42300b57cec5SDimitry Andric           SemaRef.Context, Owner, PartialSpec->getInnerLocStart(),
42310b57cec5SDimitry Andric           PartialSpec->getLocation(), InstParams, VarTemplate, DI->getType(),
42320b57cec5SDimitry Andric           DI, PartialSpec->getStorageClass(), Converted, InstTemplateArgs);
42330b57cec5SDimitry Andric 
42340b57cec5SDimitry Andric   // Substitute the nested name specifier, if any.
42350b57cec5SDimitry Andric   if (SubstQualifier(PartialSpec, InstPartialSpec))
42360b57cec5SDimitry Andric     return nullptr;
42370b57cec5SDimitry Andric 
42380b57cec5SDimitry Andric   InstPartialSpec->setInstantiatedFromMember(PartialSpec);
42390b57cec5SDimitry Andric   InstPartialSpec->setTypeAsWritten(WrittenTy);
42400b57cec5SDimitry Andric 
42410b57cec5SDimitry Andric   // Check the completed partial specialization.
42420b57cec5SDimitry Andric   SemaRef.CheckTemplatePartialSpecialization(InstPartialSpec);
42430b57cec5SDimitry Andric 
42440b57cec5SDimitry Andric   // Add this partial specialization to the set of variable template partial
42450b57cec5SDimitry Andric   // specializations. The instantiation of the initializer is not necessary.
42460b57cec5SDimitry Andric   VarTemplate->AddPartialSpecialization(InstPartialSpec, /*InsertPos=*/nullptr);
42470b57cec5SDimitry Andric 
42480b57cec5SDimitry Andric   SemaRef.BuildVariableInstantiation(InstPartialSpec, PartialSpec, TemplateArgs,
42490b57cec5SDimitry Andric                                      LateAttrs, Owner, StartingScope);
42500b57cec5SDimitry Andric 
42510b57cec5SDimitry Andric   return InstPartialSpec;
42520b57cec5SDimitry Andric }
42530b57cec5SDimitry Andric 
42540b57cec5SDimitry Andric TypeSourceInfo*
42550b57cec5SDimitry Andric TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D,
42560b57cec5SDimitry Andric                               SmallVectorImpl<ParmVarDecl *> &Params) {
42570b57cec5SDimitry Andric   TypeSourceInfo *OldTInfo = D->getTypeSourceInfo();
42580b57cec5SDimitry Andric   assert(OldTInfo && "substituting function without type source info");
42590b57cec5SDimitry Andric   assert(Params.empty() && "parameter vector is non-empty at start");
42600b57cec5SDimitry Andric 
42610b57cec5SDimitry Andric   CXXRecordDecl *ThisContext = nullptr;
42620b57cec5SDimitry Andric   Qualifiers ThisTypeQuals;
42630b57cec5SDimitry Andric   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
42640b57cec5SDimitry Andric     ThisContext = cast<CXXRecordDecl>(Owner);
42650b57cec5SDimitry Andric     ThisTypeQuals = Method->getMethodQualifiers();
42660b57cec5SDimitry Andric   }
42670b57cec5SDimitry Andric 
42680b57cec5SDimitry Andric   TypeSourceInfo *NewTInfo
42690b57cec5SDimitry Andric     = SemaRef.SubstFunctionDeclType(OldTInfo, TemplateArgs,
42700b57cec5SDimitry Andric                                     D->getTypeSpecStartLoc(),
42710b57cec5SDimitry Andric                                     D->getDeclName(),
42720b57cec5SDimitry Andric                                     ThisContext, ThisTypeQuals);
42730b57cec5SDimitry Andric   if (!NewTInfo)
42740b57cec5SDimitry Andric     return nullptr;
42750b57cec5SDimitry Andric 
42760b57cec5SDimitry Andric   TypeLoc OldTL = OldTInfo->getTypeLoc().IgnoreParens();
42770b57cec5SDimitry Andric   if (FunctionProtoTypeLoc OldProtoLoc = OldTL.getAs<FunctionProtoTypeLoc>()) {
42780b57cec5SDimitry Andric     if (NewTInfo != OldTInfo) {
42790b57cec5SDimitry Andric       // Get parameters from the new type info.
42800b57cec5SDimitry Andric       TypeLoc NewTL = NewTInfo->getTypeLoc().IgnoreParens();
42810b57cec5SDimitry Andric       FunctionProtoTypeLoc NewProtoLoc = NewTL.castAs<FunctionProtoTypeLoc>();
42820b57cec5SDimitry Andric       unsigned NewIdx = 0;
42830b57cec5SDimitry Andric       for (unsigned OldIdx = 0, NumOldParams = OldProtoLoc.getNumParams();
42840b57cec5SDimitry Andric            OldIdx != NumOldParams; ++OldIdx) {
42850b57cec5SDimitry Andric         ParmVarDecl *OldParam = OldProtoLoc.getParam(OldIdx);
4286e8d8bef9SDimitry Andric         if (!OldParam)
4287e8d8bef9SDimitry Andric           return nullptr;
4288e8d8bef9SDimitry Andric 
42890b57cec5SDimitry Andric         LocalInstantiationScope *Scope = SemaRef.CurrentInstantiationScope;
42900b57cec5SDimitry Andric 
42910b57cec5SDimitry Andric         Optional<unsigned> NumArgumentsInExpansion;
42920b57cec5SDimitry Andric         if (OldParam->isParameterPack())
42930b57cec5SDimitry Andric           NumArgumentsInExpansion =
42940b57cec5SDimitry Andric               SemaRef.getNumArgumentsInExpansion(OldParam->getType(),
42950b57cec5SDimitry Andric                                                  TemplateArgs);
42960b57cec5SDimitry Andric         if (!NumArgumentsInExpansion) {
42970b57cec5SDimitry Andric           // Simple case: normal parameter, or a parameter pack that's
42980b57cec5SDimitry Andric           // instantiated to a (still-dependent) parameter pack.
42990b57cec5SDimitry Andric           ParmVarDecl *NewParam = NewProtoLoc.getParam(NewIdx++);
43000b57cec5SDimitry Andric           Params.push_back(NewParam);
43010b57cec5SDimitry Andric           Scope->InstantiatedLocal(OldParam, NewParam);
43020b57cec5SDimitry Andric         } else {
43030b57cec5SDimitry Andric           // Parameter pack expansion: make the instantiation an argument pack.
43040b57cec5SDimitry Andric           Scope->MakeInstantiatedLocalArgPack(OldParam);
43050b57cec5SDimitry Andric           for (unsigned I = 0; I != *NumArgumentsInExpansion; ++I) {
43060b57cec5SDimitry Andric             ParmVarDecl *NewParam = NewProtoLoc.getParam(NewIdx++);
43070b57cec5SDimitry Andric             Params.push_back(NewParam);
43080b57cec5SDimitry Andric             Scope->InstantiatedLocalPackArg(OldParam, NewParam);
43090b57cec5SDimitry Andric           }
43100b57cec5SDimitry Andric         }
43110b57cec5SDimitry Andric       }
43120b57cec5SDimitry Andric     } else {
43130b57cec5SDimitry Andric       // The function type itself was not dependent and therefore no
43140b57cec5SDimitry Andric       // substitution occurred. However, we still need to instantiate
43150b57cec5SDimitry Andric       // the function parameters themselves.
43160b57cec5SDimitry Andric       const FunctionProtoType *OldProto =
43170b57cec5SDimitry Andric           cast<FunctionProtoType>(OldProtoLoc.getType());
43180b57cec5SDimitry Andric       for (unsigned i = 0, i_end = OldProtoLoc.getNumParams(); i != i_end;
43190b57cec5SDimitry Andric            ++i) {
43200b57cec5SDimitry Andric         ParmVarDecl *OldParam = OldProtoLoc.getParam(i);
43210b57cec5SDimitry Andric         if (!OldParam) {
43220b57cec5SDimitry Andric           Params.push_back(SemaRef.BuildParmVarDeclForTypedef(
43230b57cec5SDimitry Andric               D, D->getLocation(), OldProto->getParamType(i)));
43240b57cec5SDimitry Andric           continue;
43250b57cec5SDimitry Andric         }
43260b57cec5SDimitry Andric 
43270b57cec5SDimitry Andric         ParmVarDecl *Parm =
43280b57cec5SDimitry Andric             cast_or_null<ParmVarDecl>(VisitParmVarDecl(OldParam));
43290b57cec5SDimitry Andric         if (!Parm)
43300b57cec5SDimitry Andric           return nullptr;
43310b57cec5SDimitry Andric         Params.push_back(Parm);
43320b57cec5SDimitry Andric       }
43330b57cec5SDimitry Andric     }
43340b57cec5SDimitry Andric   } else {
43350b57cec5SDimitry Andric     // If the type of this function, after ignoring parentheses, is not
43360b57cec5SDimitry Andric     // *directly* a function type, then we're instantiating a function that
43370b57cec5SDimitry Andric     // was declared via a typedef or with attributes, e.g.,
43380b57cec5SDimitry Andric     //
43390b57cec5SDimitry Andric     //   typedef int functype(int, int);
43400b57cec5SDimitry Andric     //   functype func;
43410b57cec5SDimitry Andric     //   int __cdecl meth(int, int);
43420b57cec5SDimitry Andric     //
43430b57cec5SDimitry Andric     // In this case, we'll just go instantiate the ParmVarDecls that we
43440b57cec5SDimitry Andric     // synthesized in the method declaration.
43450b57cec5SDimitry Andric     SmallVector<QualType, 4> ParamTypes;
43460b57cec5SDimitry Andric     Sema::ExtParameterInfoBuilder ExtParamInfos;
43470b57cec5SDimitry Andric     if (SemaRef.SubstParmTypes(D->getLocation(), D->parameters(), nullptr,
43480b57cec5SDimitry Andric                                TemplateArgs, ParamTypes, &Params,
43490b57cec5SDimitry Andric                                ExtParamInfos))
43500b57cec5SDimitry Andric       return nullptr;
43510b57cec5SDimitry Andric   }
43520b57cec5SDimitry Andric 
43530b57cec5SDimitry Andric   return NewTInfo;
43540b57cec5SDimitry Andric }
43550b57cec5SDimitry Andric 
43560b57cec5SDimitry Andric /// Introduce the instantiated function parameters into the local
43570b57cec5SDimitry Andric /// instantiation scope, and set the parameter names to those used
43580b57cec5SDimitry Andric /// in the template.
43590b57cec5SDimitry Andric static bool addInstantiatedParametersToScope(Sema &S, FunctionDecl *Function,
43600b57cec5SDimitry Andric                                              const FunctionDecl *PatternDecl,
43610b57cec5SDimitry Andric                                              LocalInstantiationScope &Scope,
43620b57cec5SDimitry Andric                            const MultiLevelTemplateArgumentList &TemplateArgs) {
43630b57cec5SDimitry Andric   unsigned FParamIdx = 0;
43640b57cec5SDimitry Andric   for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I) {
43650b57cec5SDimitry Andric     const ParmVarDecl *PatternParam = PatternDecl->getParamDecl(I);
43660b57cec5SDimitry Andric     if (!PatternParam->isParameterPack()) {
43670b57cec5SDimitry Andric       // Simple case: not a parameter pack.
43680b57cec5SDimitry Andric       assert(FParamIdx < Function->getNumParams());
43690b57cec5SDimitry Andric       ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
43700b57cec5SDimitry Andric       FunctionParam->setDeclName(PatternParam->getDeclName());
43710b57cec5SDimitry Andric       // If the parameter's type is not dependent, update it to match the type
43720b57cec5SDimitry Andric       // in the pattern. They can differ in top-level cv-qualifiers, and we want
43730b57cec5SDimitry Andric       // the pattern's type here. If the type is dependent, they can't differ,
43740b57cec5SDimitry Andric       // per core issue 1668. Substitute into the type from the pattern, in case
43750b57cec5SDimitry Andric       // it's instantiation-dependent.
43760b57cec5SDimitry Andric       // FIXME: Updating the type to work around this is at best fragile.
43770b57cec5SDimitry Andric       if (!PatternDecl->getType()->isDependentType()) {
43780b57cec5SDimitry Andric         QualType T = S.SubstType(PatternParam->getType(), TemplateArgs,
43790b57cec5SDimitry Andric                                  FunctionParam->getLocation(),
43800b57cec5SDimitry Andric                                  FunctionParam->getDeclName());
43810b57cec5SDimitry Andric         if (T.isNull())
43820b57cec5SDimitry Andric           return true;
43830b57cec5SDimitry Andric         FunctionParam->setType(T);
43840b57cec5SDimitry Andric       }
43850b57cec5SDimitry Andric 
43860b57cec5SDimitry Andric       Scope.InstantiatedLocal(PatternParam, FunctionParam);
43870b57cec5SDimitry Andric       ++FParamIdx;
43880b57cec5SDimitry Andric       continue;
43890b57cec5SDimitry Andric     }
43900b57cec5SDimitry Andric 
43910b57cec5SDimitry Andric     // Expand the parameter pack.
43920b57cec5SDimitry Andric     Scope.MakeInstantiatedLocalArgPack(PatternParam);
43930b57cec5SDimitry Andric     Optional<unsigned> NumArgumentsInExpansion
43940b57cec5SDimitry Andric       = S.getNumArgumentsInExpansion(PatternParam->getType(), TemplateArgs);
43950b57cec5SDimitry Andric     if (NumArgumentsInExpansion) {
43960b57cec5SDimitry Andric       QualType PatternType =
43970b57cec5SDimitry Andric           PatternParam->getType()->castAs<PackExpansionType>()->getPattern();
43980b57cec5SDimitry Andric       for (unsigned Arg = 0; Arg < *NumArgumentsInExpansion; ++Arg) {
43990b57cec5SDimitry Andric         ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
44000b57cec5SDimitry Andric         FunctionParam->setDeclName(PatternParam->getDeclName());
44010b57cec5SDimitry Andric         if (!PatternDecl->getType()->isDependentType()) {
44020b57cec5SDimitry Andric           Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(S, Arg);
44030b57cec5SDimitry Andric           QualType T = S.SubstType(PatternType, TemplateArgs,
44040b57cec5SDimitry Andric                                    FunctionParam->getLocation(),
44050b57cec5SDimitry Andric                                    FunctionParam->getDeclName());
44060b57cec5SDimitry Andric           if (T.isNull())
44070b57cec5SDimitry Andric             return true;
44080b57cec5SDimitry Andric           FunctionParam->setType(T);
44090b57cec5SDimitry Andric         }
44100b57cec5SDimitry Andric 
44110b57cec5SDimitry Andric         Scope.InstantiatedLocalPackArg(PatternParam, FunctionParam);
44120b57cec5SDimitry Andric         ++FParamIdx;
44130b57cec5SDimitry Andric       }
44140b57cec5SDimitry Andric     }
44150b57cec5SDimitry Andric   }
44160b57cec5SDimitry Andric 
44170b57cec5SDimitry Andric   return false;
44180b57cec5SDimitry Andric }
44190b57cec5SDimitry Andric 
44205ffd83dbSDimitry Andric bool Sema::InstantiateDefaultArgument(SourceLocation CallLoc, FunctionDecl *FD,
44215ffd83dbSDimitry Andric                                       ParmVarDecl *Param) {
44225ffd83dbSDimitry Andric   assert(Param->hasUninstantiatedDefaultArg());
44235ffd83dbSDimitry Andric   Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
44245ffd83dbSDimitry Andric 
44255ffd83dbSDimitry Andric   EnterExpressionEvaluationContext EvalContext(
44265ffd83dbSDimitry Andric       *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param);
44275ffd83dbSDimitry Andric 
44285ffd83dbSDimitry Andric   // Instantiate the expression.
44295ffd83dbSDimitry Andric   //
44305ffd83dbSDimitry Andric   // FIXME: Pass in a correct Pattern argument, otherwise
44315ffd83dbSDimitry Andric   // getTemplateInstantiationArgs uses the lexical context of FD, e.g.
44325ffd83dbSDimitry Andric   //
44335ffd83dbSDimitry Andric   // template<typename T>
44345ffd83dbSDimitry Andric   // struct A {
44355ffd83dbSDimitry Andric   //   static int FooImpl();
44365ffd83dbSDimitry Andric   //
44375ffd83dbSDimitry Andric   //   template<typename Tp>
44385ffd83dbSDimitry Andric   //   // bug: default argument A<T>::FooImpl() is evaluated with 2-level
44395ffd83dbSDimitry Andric   //   // template argument list [[T], [Tp]], should be [[Tp]].
44405ffd83dbSDimitry Andric   //   friend A<Tp> Foo(int a);
44415ffd83dbSDimitry Andric   // };
44425ffd83dbSDimitry Andric   //
44435ffd83dbSDimitry Andric   // template<typename T>
44445ffd83dbSDimitry Andric   // A<T> Foo(int a = A<T>::FooImpl());
44455ffd83dbSDimitry Andric   MultiLevelTemplateArgumentList TemplateArgs
44465ffd83dbSDimitry Andric     = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true);
44475ffd83dbSDimitry Andric 
44485ffd83dbSDimitry Andric   InstantiatingTemplate Inst(*this, CallLoc, Param,
44495ffd83dbSDimitry Andric                              TemplateArgs.getInnermost());
44505ffd83dbSDimitry Andric   if (Inst.isInvalid())
44515ffd83dbSDimitry Andric     return true;
44525ffd83dbSDimitry Andric   if (Inst.isAlreadyInstantiating()) {
44535ffd83dbSDimitry Andric     Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
44545ffd83dbSDimitry Andric     Param->setInvalidDecl();
44555ffd83dbSDimitry Andric     return true;
44565ffd83dbSDimitry Andric   }
44575ffd83dbSDimitry Andric 
44585ffd83dbSDimitry Andric   ExprResult Result;
44595ffd83dbSDimitry Andric   {
44605ffd83dbSDimitry Andric     // C++ [dcl.fct.default]p5:
44615ffd83dbSDimitry Andric     //   The names in the [default argument] expression are bound, and
44625ffd83dbSDimitry Andric     //   the semantic constraints are checked, at the point where the
44635ffd83dbSDimitry Andric     //   default argument expression appears.
44645ffd83dbSDimitry Andric     ContextRAII SavedContext(*this, FD);
44655ffd83dbSDimitry Andric     LocalInstantiationScope Local(*this);
44665ffd83dbSDimitry Andric 
44675ffd83dbSDimitry Andric     FunctionDecl *Pattern = FD->getTemplateInstantiationPattern(
44685ffd83dbSDimitry Andric         /*ForDefinition*/ false);
44695ffd83dbSDimitry Andric     if (addInstantiatedParametersToScope(*this, FD, Pattern, Local,
44705ffd83dbSDimitry Andric                                          TemplateArgs))
44715ffd83dbSDimitry Andric       return true;
44725ffd83dbSDimitry Andric 
44735ffd83dbSDimitry Andric     runWithSufficientStackSpace(CallLoc, [&] {
44745ffd83dbSDimitry Andric       Result = SubstInitializer(UninstExpr, TemplateArgs,
44755ffd83dbSDimitry Andric                                 /*DirectInit*/false);
44765ffd83dbSDimitry Andric     });
44775ffd83dbSDimitry Andric   }
44785ffd83dbSDimitry Andric   if (Result.isInvalid())
44795ffd83dbSDimitry Andric     return true;
44805ffd83dbSDimitry Andric 
44815ffd83dbSDimitry Andric   // Check the expression as an initializer for the parameter.
44825ffd83dbSDimitry Andric   InitializedEntity Entity
44835ffd83dbSDimitry Andric     = InitializedEntity::InitializeParameter(Context, Param);
44845ffd83dbSDimitry Andric   InitializationKind Kind = InitializationKind::CreateCopy(
44855ffd83dbSDimitry Andric       Param->getLocation(),
44865ffd83dbSDimitry Andric       /*FIXME:EqualLoc*/ UninstExpr->getBeginLoc());
44875ffd83dbSDimitry Andric   Expr *ResultE = Result.getAs<Expr>();
44885ffd83dbSDimitry Andric 
44895ffd83dbSDimitry Andric   InitializationSequence InitSeq(*this, Entity, Kind, ResultE);
44905ffd83dbSDimitry Andric   Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
44915ffd83dbSDimitry Andric   if (Result.isInvalid())
44925ffd83dbSDimitry Andric     return true;
44935ffd83dbSDimitry Andric 
44945ffd83dbSDimitry Andric   Result =
44955ffd83dbSDimitry Andric       ActOnFinishFullExpr(Result.getAs<Expr>(), Param->getOuterLocStart(),
44965ffd83dbSDimitry Andric                           /*DiscardedValue*/ false);
44975ffd83dbSDimitry Andric   if (Result.isInvalid())
44985ffd83dbSDimitry Andric     return true;
44995ffd83dbSDimitry Andric 
45005ffd83dbSDimitry Andric   // Remember the instantiated default argument.
45015ffd83dbSDimitry Andric   Param->setDefaultArg(Result.getAs<Expr>());
45025ffd83dbSDimitry Andric   if (ASTMutationListener *L = getASTMutationListener())
45035ffd83dbSDimitry Andric     L->DefaultArgumentInstantiated(Param);
45045ffd83dbSDimitry Andric 
45055ffd83dbSDimitry Andric   return false;
45065ffd83dbSDimitry Andric }
45075ffd83dbSDimitry Andric 
45080b57cec5SDimitry Andric void Sema::InstantiateExceptionSpec(SourceLocation PointOfInstantiation,
45090b57cec5SDimitry Andric                                     FunctionDecl *Decl) {
45100b57cec5SDimitry Andric   const FunctionProtoType *Proto = Decl->getType()->castAs<FunctionProtoType>();
45110b57cec5SDimitry Andric   if (Proto->getExceptionSpecType() != EST_Uninstantiated)
45120b57cec5SDimitry Andric     return;
45130b57cec5SDimitry Andric 
45140b57cec5SDimitry Andric   InstantiatingTemplate Inst(*this, PointOfInstantiation, Decl,
45150b57cec5SDimitry Andric                              InstantiatingTemplate::ExceptionSpecification());
45160b57cec5SDimitry Andric   if (Inst.isInvalid()) {
45170b57cec5SDimitry Andric     // We hit the instantiation depth limit. Clear the exception specification
45180b57cec5SDimitry Andric     // so that our callers don't have to cope with EST_Uninstantiated.
45190b57cec5SDimitry Andric     UpdateExceptionSpec(Decl, EST_None);
45200b57cec5SDimitry Andric     return;
45210b57cec5SDimitry Andric   }
45220b57cec5SDimitry Andric   if (Inst.isAlreadyInstantiating()) {
45230b57cec5SDimitry Andric     // This exception specification indirectly depends on itself. Reject.
45240b57cec5SDimitry Andric     // FIXME: Corresponding rule in the standard?
45250b57cec5SDimitry Andric     Diag(PointOfInstantiation, diag::err_exception_spec_cycle) << Decl;
45260b57cec5SDimitry Andric     UpdateExceptionSpec(Decl, EST_None);
45270b57cec5SDimitry Andric     return;
45280b57cec5SDimitry Andric   }
45290b57cec5SDimitry Andric 
45300b57cec5SDimitry Andric   // Enter the scope of this instantiation. We don't use
45310b57cec5SDimitry Andric   // PushDeclContext because we don't have a scope.
45320b57cec5SDimitry Andric   Sema::ContextRAII savedContext(*this, Decl);
45330b57cec5SDimitry Andric   LocalInstantiationScope Scope(*this);
45340b57cec5SDimitry Andric 
45350b57cec5SDimitry Andric   MultiLevelTemplateArgumentList TemplateArgs =
45360b57cec5SDimitry Andric     getTemplateInstantiationArgs(Decl, nullptr, /*RelativeToPrimary*/true);
45370b57cec5SDimitry Andric 
45385ffd83dbSDimitry Andric   // FIXME: We can't use getTemplateInstantiationPattern(false) in general
45395ffd83dbSDimitry Andric   // here, because for a non-defining friend declaration in a class template,
45405ffd83dbSDimitry Andric   // we don't store enough information to map back to the friend declaration in
45415ffd83dbSDimitry Andric   // the template.
45420b57cec5SDimitry Andric   FunctionDecl *Template = Proto->getExceptionSpecTemplate();
45430b57cec5SDimitry Andric   if (addInstantiatedParametersToScope(*this, Decl, Template, Scope,
45440b57cec5SDimitry Andric                                        TemplateArgs)) {
45450b57cec5SDimitry Andric     UpdateExceptionSpec(Decl, EST_None);
45460b57cec5SDimitry Andric     return;
45470b57cec5SDimitry Andric   }
45480b57cec5SDimitry Andric 
45490b57cec5SDimitry Andric   SubstExceptionSpec(Decl, Template->getType()->castAs<FunctionProtoType>(),
45500b57cec5SDimitry Andric                      TemplateArgs);
45510b57cec5SDimitry Andric }
45520b57cec5SDimitry Andric 
4553480093f4SDimitry Andric bool Sema::CheckInstantiatedFunctionTemplateConstraints(
4554480093f4SDimitry Andric     SourceLocation PointOfInstantiation, FunctionDecl *Decl,
4555480093f4SDimitry Andric     ArrayRef<TemplateArgument> TemplateArgs,
4556480093f4SDimitry Andric     ConstraintSatisfaction &Satisfaction) {
4557480093f4SDimitry Andric   // In most cases we're not going to have constraints, so check for that first.
4558480093f4SDimitry Andric   FunctionTemplateDecl *Template = Decl->getPrimaryTemplate();
4559480093f4SDimitry Andric   // Note - code synthesis context for the constraints check is created
4560480093f4SDimitry Andric   // inside CheckConstraintsSatisfaction.
4561480093f4SDimitry Andric   SmallVector<const Expr *, 3> TemplateAC;
4562480093f4SDimitry Andric   Template->getAssociatedConstraints(TemplateAC);
4563480093f4SDimitry Andric   if (TemplateAC.empty()) {
4564480093f4SDimitry Andric     Satisfaction.IsSatisfied = true;
4565480093f4SDimitry Andric     return false;
4566480093f4SDimitry Andric   }
4567480093f4SDimitry Andric 
4568480093f4SDimitry Andric   // Enter the scope of this instantiation. We don't use
4569480093f4SDimitry Andric   // PushDeclContext because we don't have a scope.
4570480093f4SDimitry Andric   Sema::ContextRAII savedContext(*this, Decl);
4571480093f4SDimitry Andric   LocalInstantiationScope Scope(*this);
4572480093f4SDimitry Andric 
4573480093f4SDimitry Andric   // If this is not an explicit specialization - we need to get the instantiated
4574480093f4SDimitry Andric   // version of the template arguments and add them to scope for the
4575480093f4SDimitry Andric   // substitution.
4576480093f4SDimitry Andric   if (Decl->isTemplateInstantiation()) {
4577480093f4SDimitry Andric     InstantiatingTemplate Inst(*this, Decl->getPointOfInstantiation(),
4578480093f4SDimitry Andric         InstantiatingTemplate::ConstraintsCheck{}, Decl->getPrimaryTemplate(),
457913138422SDimitry Andric         TemplateArgs, SourceRange());
4580480093f4SDimitry Andric     if (Inst.isInvalid())
4581480093f4SDimitry Andric       return true;
458213138422SDimitry Andric     MultiLevelTemplateArgumentList MLTAL(
458313138422SDimitry Andric         *Decl->getTemplateSpecializationArgs());
458455e4f9d5SDimitry Andric     if (addInstantiatedParametersToScope(
458555e4f9d5SDimitry Andric             *this, Decl, Decl->getPrimaryTemplate()->getTemplatedDecl(),
4586480093f4SDimitry Andric             Scope, MLTAL))
4587480093f4SDimitry Andric       return true;
4588480093f4SDimitry Andric   }
458913138422SDimitry Andric   Qualifiers ThisQuals;
459013138422SDimitry Andric   CXXRecordDecl *Record = nullptr;
459113138422SDimitry Andric   if (auto *Method = dyn_cast<CXXMethodDecl>(Decl)) {
459213138422SDimitry Andric     ThisQuals = Method->getMethodQualifiers();
459313138422SDimitry Andric     Record = Method->getParent();
459413138422SDimitry Andric   }
459513138422SDimitry Andric   CXXThisScopeRAII ThisScope(*this, Record, ThisQuals, Record != nullptr);
4596480093f4SDimitry Andric   return CheckConstraintSatisfaction(Template, TemplateAC, TemplateArgs,
4597480093f4SDimitry Andric                                      PointOfInstantiation, Satisfaction);
4598480093f4SDimitry Andric }
4599480093f4SDimitry Andric 
46000b57cec5SDimitry Andric /// Initializes the common fields of an instantiation function
46010b57cec5SDimitry Andric /// declaration (New) from the corresponding fields of its template (Tmpl).
46020b57cec5SDimitry Andric ///
46030b57cec5SDimitry Andric /// \returns true if there was an error
46040b57cec5SDimitry Andric bool
46050b57cec5SDimitry Andric TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New,
46060b57cec5SDimitry Andric                                                     FunctionDecl *Tmpl) {
46070b57cec5SDimitry Andric   New->setImplicit(Tmpl->isImplicit());
46080b57cec5SDimitry Andric 
46090b57cec5SDimitry Andric   // Forward the mangling number from the template to the instantiated decl.
46100b57cec5SDimitry Andric   SemaRef.Context.setManglingNumber(New,
46110b57cec5SDimitry Andric                                     SemaRef.Context.getManglingNumber(Tmpl));
46120b57cec5SDimitry Andric 
46130b57cec5SDimitry Andric   // If we are performing substituting explicitly-specified template arguments
46140b57cec5SDimitry Andric   // or deduced template arguments into a function template and we reach this
46150b57cec5SDimitry Andric   // point, we are now past the point where SFINAE applies and have committed
46160b57cec5SDimitry Andric   // to keeping the new function template specialization. We therefore
46170b57cec5SDimitry Andric   // convert the active template instantiation for the function template
46180b57cec5SDimitry Andric   // into a template instantiation for this specific function template
46190b57cec5SDimitry Andric   // specialization, which is not a SFINAE context, so that we diagnose any
46200b57cec5SDimitry Andric   // further errors in the declaration itself.
4621e8d8bef9SDimitry Andric   //
4622e8d8bef9SDimitry Andric   // FIXME: This is a hack.
46230b57cec5SDimitry Andric   typedef Sema::CodeSynthesisContext ActiveInstType;
46240b57cec5SDimitry Andric   ActiveInstType &ActiveInst = SemaRef.CodeSynthesisContexts.back();
46250b57cec5SDimitry Andric   if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution ||
46260b57cec5SDimitry Andric       ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) {
46270b57cec5SDimitry Andric     if (FunctionTemplateDecl *FunTmpl
46280b57cec5SDimitry Andric           = dyn_cast<FunctionTemplateDecl>(ActiveInst.Entity)) {
46290b57cec5SDimitry Andric       assert(FunTmpl->getTemplatedDecl() == Tmpl &&
46300b57cec5SDimitry Andric              "Deduction from the wrong function template?");
46310b57cec5SDimitry Andric       (void) FunTmpl;
4632e8d8bef9SDimitry Andric       SemaRef.InstantiatingSpecializations.erase(
4633e8d8bef9SDimitry Andric           {ActiveInst.Entity->getCanonicalDecl(), ActiveInst.Kind});
46340b57cec5SDimitry Andric       atTemplateEnd(SemaRef.TemplateInstCallbacks, SemaRef, ActiveInst);
46350b57cec5SDimitry Andric       ActiveInst.Kind = ActiveInstType::TemplateInstantiation;
46360b57cec5SDimitry Andric       ActiveInst.Entity = New;
46370b57cec5SDimitry Andric       atTemplateBegin(SemaRef.TemplateInstCallbacks, SemaRef, ActiveInst);
46380b57cec5SDimitry Andric     }
46390b57cec5SDimitry Andric   }
46400b57cec5SDimitry Andric 
46410b57cec5SDimitry Andric   const FunctionProtoType *Proto = Tmpl->getType()->getAs<FunctionProtoType>();
46420b57cec5SDimitry Andric   assert(Proto && "Function template without prototype?");
46430b57cec5SDimitry Andric 
46440b57cec5SDimitry Andric   if (Proto->hasExceptionSpec() || Proto->getNoReturnAttr()) {
46450b57cec5SDimitry Andric     FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
46460b57cec5SDimitry Andric 
46470b57cec5SDimitry Andric     // DR1330: In C++11, defer instantiation of a non-trivial
46480b57cec5SDimitry Andric     // exception specification.
46490b57cec5SDimitry Andric     // DR1484: Local classes and their members are instantiated along with the
46500b57cec5SDimitry Andric     // containing function.
46510b57cec5SDimitry Andric     if (SemaRef.getLangOpts().CPlusPlus11 &&
46520b57cec5SDimitry Andric         EPI.ExceptionSpec.Type != EST_None &&
46530b57cec5SDimitry Andric         EPI.ExceptionSpec.Type != EST_DynamicNone &&
46540b57cec5SDimitry Andric         EPI.ExceptionSpec.Type != EST_BasicNoexcept &&
46555ffd83dbSDimitry Andric         !Tmpl->isInLocalScopeForInstantiation()) {
46560b57cec5SDimitry Andric       FunctionDecl *ExceptionSpecTemplate = Tmpl;
46570b57cec5SDimitry Andric       if (EPI.ExceptionSpec.Type == EST_Uninstantiated)
46580b57cec5SDimitry Andric         ExceptionSpecTemplate = EPI.ExceptionSpec.SourceTemplate;
46590b57cec5SDimitry Andric       ExceptionSpecificationType NewEST = EST_Uninstantiated;
46600b57cec5SDimitry Andric       if (EPI.ExceptionSpec.Type == EST_Unevaluated)
46610b57cec5SDimitry Andric         NewEST = EST_Unevaluated;
46620b57cec5SDimitry Andric 
46630b57cec5SDimitry Andric       // Mark the function has having an uninstantiated exception specification.
46640b57cec5SDimitry Andric       const FunctionProtoType *NewProto
46650b57cec5SDimitry Andric         = New->getType()->getAs<FunctionProtoType>();
46660b57cec5SDimitry Andric       assert(NewProto && "Template instantiation without function prototype?");
46670b57cec5SDimitry Andric       EPI = NewProto->getExtProtoInfo();
46680b57cec5SDimitry Andric       EPI.ExceptionSpec.Type = NewEST;
46690b57cec5SDimitry Andric       EPI.ExceptionSpec.SourceDecl = New;
46700b57cec5SDimitry Andric       EPI.ExceptionSpec.SourceTemplate = ExceptionSpecTemplate;
46710b57cec5SDimitry Andric       New->setType(SemaRef.Context.getFunctionType(
46720b57cec5SDimitry Andric           NewProto->getReturnType(), NewProto->getParamTypes(), EPI));
46730b57cec5SDimitry Andric     } else {
46740b57cec5SDimitry Andric       Sema::ContextRAII SwitchContext(SemaRef, New);
46750b57cec5SDimitry Andric       SemaRef.SubstExceptionSpec(New, Proto, TemplateArgs);
46760b57cec5SDimitry Andric     }
46770b57cec5SDimitry Andric   }
46780b57cec5SDimitry Andric 
46790b57cec5SDimitry Andric   // Get the definition. Leaves the variable unchanged if undefined.
46800b57cec5SDimitry Andric   const FunctionDecl *Definition = Tmpl;
46810b57cec5SDimitry Andric   Tmpl->isDefined(Definition);
46820b57cec5SDimitry Andric 
46830b57cec5SDimitry Andric   SemaRef.InstantiateAttrs(TemplateArgs, Definition, New,
46840b57cec5SDimitry Andric                            LateAttrs, StartingScope);
46850b57cec5SDimitry Andric 
46860b57cec5SDimitry Andric   return false;
46870b57cec5SDimitry Andric }
46880b57cec5SDimitry Andric 
46890b57cec5SDimitry Andric /// Initializes common fields of an instantiated method
46900b57cec5SDimitry Andric /// declaration (New) from the corresponding fields of its template
46910b57cec5SDimitry Andric /// (Tmpl).
46920b57cec5SDimitry Andric ///
46930b57cec5SDimitry Andric /// \returns true if there was an error
46940b57cec5SDimitry Andric bool
46950b57cec5SDimitry Andric TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New,
46960b57cec5SDimitry Andric                                                   CXXMethodDecl *Tmpl) {
46970b57cec5SDimitry Andric   if (InitFunctionInstantiation(New, Tmpl))
46980b57cec5SDimitry Andric     return true;
46990b57cec5SDimitry Andric 
47000b57cec5SDimitry Andric   if (isa<CXXDestructorDecl>(New) && SemaRef.getLangOpts().CPlusPlus11)
47010b57cec5SDimitry Andric     SemaRef.AdjustDestructorExceptionSpec(cast<CXXDestructorDecl>(New));
47020b57cec5SDimitry Andric 
47030b57cec5SDimitry Andric   New->setAccess(Tmpl->getAccess());
47040b57cec5SDimitry Andric   if (Tmpl->isVirtualAsWritten())
47050b57cec5SDimitry Andric     New->setVirtualAsWritten(true);
47060b57cec5SDimitry Andric 
47070b57cec5SDimitry Andric   // FIXME: New needs a pointer to Tmpl
47080b57cec5SDimitry Andric   return false;
47090b57cec5SDimitry Andric }
47100b57cec5SDimitry Andric 
4711480093f4SDimitry Andric bool TemplateDeclInstantiator::SubstDefaultedFunction(FunctionDecl *New,
4712480093f4SDimitry Andric                                                       FunctionDecl *Tmpl) {
4713480093f4SDimitry Andric   // Transfer across any unqualified lookups.
4714480093f4SDimitry Andric   if (auto *DFI = Tmpl->getDefaultedFunctionInfo()) {
4715480093f4SDimitry Andric     SmallVector<DeclAccessPair, 32> Lookups;
4716480093f4SDimitry Andric     Lookups.reserve(DFI->getUnqualifiedLookups().size());
4717480093f4SDimitry Andric     bool AnyChanged = false;
4718480093f4SDimitry Andric     for (DeclAccessPair DA : DFI->getUnqualifiedLookups()) {
4719480093f4SDimitry Andric       NamedDecl *D = SemaRef.FindInstantiatedDecl(New->getLocation(),
4720480093f4SDimitry Andric                                                   DA.getDecl(), TemplateArgs);
4721480093f4SDimitry Andric       if (!D)
4722480093f4SDimitry Andric         return true;
4723480093f4SDimitry Andric       AnyChanged |= (D != DA.getDecl());
4724480093f4SDimitry Andric       Lookups.push_back(DeclAccessPair::make(D, DA.getAccess()));
4725480093f4SDimitry Andric     }
4726480093f4SDimitry Andric 
4727480093f4SDimitry Andric     // It's unlikely that substitution will change any declarations. Don't
4728480093f4SDimitry Andric     // store an unnecessary copy in that case.
4729480093f4SDimitry Andric     New->setDefaultedFunctionInfo(
4730480093f4SDimitry Andric         AnyChanged ? FunctionDecl::DefaultedFunctionInfo::Create(
4731480093f4SDimitry Andric                          SemaRef.Context, Lookups)
4732480093f4SDimitry Andric                    : DFI);
4733480093f4SDimitry Andric   }
4734480093f4SDimitry Andric 
4735480093f4SDimitry Andric   SemaRef.SetDeclDefaulted(New, Tmpl->getLocation());
4736480093f4SDimitry Andric   return false;
4737480093f4SDimitry Andric }
4738480093f4SDimitry Andric 
47390b57cec5SDimitry Andric /// Instantiate (or find existing instantiation of) a function template with a
47400b57cec5SDimitry Andric /// given set of template arguments.
47410b57cec5SDimitry Andric ///
47420b57cec5SDimitry Andric /// Usually this should not be used, and template argument deduction should be
47430b57cec5SDimitry Andric /// used in its place.
47440b57cec5SDimitry Andric FunctionDecl *
47450b57cec5SDimitry Andric Sema::InstantiateFunctionDeclaration(FunctionTemplateDecl *FTD,
47460b57cec5SDimitry Andric                                      const TemplateArgumentList *Args,
47470b57cec5SDimitry Andric                                      SourceLocation Loc) {
47480b57cec5SDimitry Andric   FunctionDecl *FD = FTD->getTemplatedDecl();
47490b57cec5SDimitry Andric 
47500b57cec5SDimitry Andric   sema::TemplateDeductionInfo Info(Loc);
47510b57cec5SDimitry Andric   InstantiatingTemplate Inst(
47520b57cec5SDimitry Andric       *this, Loc, FTD, Args->asArray(),
47530b57cec5SDimitry Andric       CodeSynthesisContext::ExplicitTemplateArgumentSubstitution, Info);
47540b57cec5SDimitry Andric   if (Inst.isInvalid())
47550b57cec5SDimitry Andric     return nullptr;
47560b57cec5SDimitry Andric 
47570b57cec5SDimitry Andric   ContextRAII SavedContext(*this, FD);
47580b57cec5SDimitry Andric   MultiLevelTemplateArgumentList MArgs(*Args);
47590b57cec5SDimitry Andric 
47600b57cec5SDimitry Andric   return cast_or_null<FunctionDecl>(SubstDecl(FD, FD->getParent(), MArgs));
47610b57cec5SDimitry Andric }
47620b57cec5SDimitry Andric 
47630b57cec5SDimitry Andric /// Instantiate the definition of the given function from its
47640b57cec5SDimitry Andric /// template.
47650b57cec5SDimitry Andric ///
47660b57cec5SDimitry Andric /// \param PointOfInstantiation the point at which the instantiation was
47670b57cec5SDimitry Andric /// required. Note that this is not precisely a "point of instantiation"
47680b57cec5SDimitry Andric /// for the function, but it's close.
47690b57cec5SDimitry Andric ///
47700b57cec5SDimitry Andric /// \param Function the already-instantiated declaration of a
47710b57cec5SDimitry Andric /// function template specialization or member function of a class template
47720b57cec5SDimitry Andric /// specialization.
47730b57cec5SDimitry Andric ///
47740b57cec5SDimitry Andric /// \param Recursive if true, recursively instantiates any functions that
47750b57cec5SDimitry Andric /// are required by this instantiation.
47760b57cec5SDimitry Andric ///
47770b57cec5SDimitry Andric /// \param DefinitionRequired if true, then we are performing an explicit
47780b57cec5SDimitry Andric /// instantiation where the body of the function is required. Complain if
47790b57cec5SDimitry Andric /// there is no such body.
47800b57cec5SDimitry Andric void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
47810b57cec5SDimitry Andric                                          FunctionDecl *Function,
47820b57cec5SDimitry Andric                                          bool Recursive,
47830b57cec5SDimitry Andric                                          bool DefinitionRequired,
47840b57cec5SDimitry Andric                                          bool AtEndOfTU) {
4785e8d8bef9SDimitry Andric   if (Function->isInvalidDecl() || isa<CXXDeductionGuideDecl>(Function))
47860b57cec5SDimitry Andric     return;
47870b57cec5SDimitry Andric 
47880b57cec5SDimitry Andric   // Never instantiate an explicit specialization except if it is a class scope
47890b57cec5SDimitry Andric   // explicit specialization.
47900b57cec5SDimitry Andric   TemplateSpecializationKind TSK =
47910b57cec5SDimitry Andric       Function->getTemplateSpecializationKindForInstantiation();
47920b57cec5SDimitry Andric   if (TSK == TSK_ExplicitSpecialization)
47930b57cec5SDimitry Andric     return;
47940b57cec5SDimitry Andric 
4795e8d8bef9SDimitry Andric   // Don't instantiate a definition if we already have one.
4796e8d8bef9SDimitry Andric   const FunctionDecl *ExistingDefn = nullptr;
4797e8d8bef9SDimitry Andric   if (Function->isDefined(ExistingDefn,
4798e8d8bef9SDimitry Andric                           /*CheckForPendingFriendDefinition=*/true)) {
4799e8d8bef9SDimitry Andric     if (ExistingDefn->isThisDeclarationADefinition())
4800e8d8bef9SDimitry Andric       return;
4801e8d8bef9SDimitry Andric 
4802e8d8bef9SDimitry Andric     // If we're asked to instantiate a function whose body comes from an
4803e8d8bef9SDimitry Andric     // instantiated friend declaration, attach the instantiated body to the
4804e8d8bef9SDimitry Andric     // corresponding declaration of the function.
4805e8d8bef9SDimitry Andric     assert(ExistingDefn->isThisDeclarationInstantiatedFromAFriendDefinition());
4806e8d8bef9SDimitry Andric     Function = const_cast<FunctionDecl*>(ExistingDefn);
4807e8d8bef9SDimitry Andric   }
4808e8d8bef9SDimitry Andric 
48090b57cec5SDimitry Andric   // Find the function body that we'll be substituting.
48100b57cec5SDimitry Andric   const FunctionDecl *PatternDecl = Function->getTemplateInstantiationPattern();
48110b57cec5SDimitry Andric   assert(PatternDecl && "instantiating a non-template");
48120b57cec5SDimitry Andric 
48130b57cec5SDimitry Andric   const FunctionDecl *PatternDef = PatternDecl->getDefinition();
48140b57cec5SDimitry Andric   Stmt *Pattern = nullptr;
48150b57cec5SDimitry Andric   if (PatternDef) {
48160b57cec5SDimitry Andric     Pattern = PatternDef->getBody(PatternDef);
48170b57cec5SDimitry Andric     PatternDecl = PatternDef;
48180b57cec5SDimitry Andric     if (PatternDef->willHaveBody())
48190b57cec5SDimitry Andric       PatternDef = nullptr;
48200b57cec5SDimitry Andric   }
48210b57cec5SDimitry Andric 
48220b57cec5SDimitry Andric   // FIXME: We need to track the instantiation stack in order to know which
48230b57cec5SDimitry Andric   // definitions should be visible within this instantiation.
48240b57cec5SDimitry Andric   if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Function,
48250b57cec5SDimitry Andric                                 Function->getInstantiatedFromMemberFunction(),
48260b57cec5SDimitry Andric                                      PatternDecl, PatternDef, TSK,
48270b57cec5SDimitry Andric                                      /*Complain*/DefinitionRequired)) {
48280b57cec5SDimitry Andric     if (DefinitionRequired)
48290b57cec5SDimitry Andric       Function->setInvalidDecl();
48300b57cec5SDimitry Andric     else if (TSK == TSK_ExplicitInstantiationDefinition) {
48310b57cec5SDimitry Andric       // Try again at the end of the translation unit (at which point a
48320b57cec5SDimitry Andric       // definition will be required).
48330b57cec5SDimitry Andric       assert(!Recursive);
48340b57cec5SDimitry Andric       Function->setInstantiationIsPending(true);
48350b57cec5SDimitry Andric       PendingInstantiations.push_back(
48360b57cec5SDimitry Andric         std::make_pair(Function, PointOfInstantiation));
48370b57cec5SDimitry Andric     } else if (TSK == TSK_ImplicitInstantiation) {
48380b57cec5SDimitry Andric       if (AtEndOfTU && !getDiagnostics().hasErrorOccurred() &&
48390b57cec5SDimitry Andric           !getSourceManager().isInSystemHeader(PatternDecl->getBeginLoc())) {
48400b57cec5SDimitry Andric         Diag(PointOfInstantiation, diag::warn_func_template_missing)
48410b57cec5SDimitry Andric           << Function;
48420b57cec5SDimitry Andric         Diag(PatternDecl->getLocation(), diag::note_forward_template_decl);
48430b57cec5SDimitry Andric         if (getLangOpts().CPlusPlus11)
48440b57cec5SDimitry Andric           Diag(PointOfInstantiation, diag::note_inst_declaration_hint)
48450b57cec5SDimitry Andric             << Function;
48460b57cec5SDimitry Andric       }
48470b57cec5SDimitry Andric     }
48480b57cec5SDimitry Andric 
48490b57cec5SDimitry Andric     return;
48500b57cec5SDimitry Andric   }
48510b57cec5SDimitry Andric 
48520b57cec5SDimitry Andric   // Postpone late parsed template instantiations.
48530b57cec5SDimitry Andric   if (PatternDecl->isLateTemplateParsed() &&
48540b57cec5SDimitry Andric       !LateTemplateParser) {
48550b57cec5SDimitry Andric     Function->setInstantiationIsPending(true);
48560b57cec5SDimitry Andric     LateParsedInstantiations.push_back(
48570b57cec5SDimitry Andric         std::make_pair(Function, PointOfInstantiation));
48580b57cec5SDimitry Andric     return;
48590b57cec5SDimitry Andric   }
48600b57cec5SDimitry Andric 
48610b57cec5SDimitry Andric   llvm::TimeTraceScope TimeScope("InstantiateFunction", [&]() {
48620b57cec5SDimitry Andric     std::string Name;
48630b57cec5SDimitry Andric     llvm::raw_string_ostream OS(Name);
48640b57cec5SDimitry Andric     Function->getNameForDiagnostic(OS, getPrintingPolicy(),
48650b57cec5SDimitry Andric                                    /*Qualified=*/true);
48660b57cec5SDimitry Andric     return Name;
48670b57cec5SDimitry Andric   });
48680b57cec5SDimitry Andric 
48690b57cec5SDimitry Andric   // If we're performing recursive template instantiation, create our own
48700b57cec5SDimitry Andric   // queue of pending implicit instantiations that we will instantiate later,
48710b57cec5SDimitry Andric   // while we're still within our own instantiation context.
48720b57cec5SDimitry Andric   // This has to happen before LateTemplateParser below is called, so that
48730b57cec5SDimitry Andric   // it marks vtables used in late parsed templates as used.
48740b57cec5SDimitry Andric   GlobalEagerInstantiationScope GlobalInstantiations(*this,
48750b57cec5SDimitry Andric                                                      /*Enabled=*/Recursive);
48760b57cec5SDimitry Andric   LocalEagerInstantiationScope LocalInstantiations(*this);
48770b57cec5SDimitry Andric 
48780b57cec5SDimitry Andric   // Call the LateTemplateParser callback if there is a need to late parse
48790b57cec5SDimitry Andric   // a templated function definition.
48800b57cec5SDimitry Andric   if (!Pattern && PatternDecl->isLateTemplateParsed() &&
48810b57cec5SDimitry Andric       LateTemplateParser) {
48820b57cec5SDimitry Andric     // FIXME: Optimize to allow individual templates to be deserialized.
48830b57cec5SDimitry Andric     if (PatternDecl->isFromASTFile())
48840b57cec5SDimitry Andric       ExternalSource->ReadLateParsedTemplates(LateParsedTemplateMap);
48850b57cec5SDimitry Andric 
48860b57cec5SDimitry Andric     auto LPTIter = LateParsedTemplateMap.find(PatternDecl);
48870b57cec5SDimitry Andric     assert(LPTIter != LateParsedTemplateMap.end() &&
48880b57cec5SDimitry Andric            "missing LateParsedTemplate");
48890b57cec5SDimitry Andric     LateTemplateParser(OpaqueParser, *LPTIter->second);
48900b57cec5SDimitry Andric     Pattern = PatternDecl->getBody(PatternDecl);
48910b57cec5SDimitry Andric   }
48920b57cec5SDimitry Andric 
48930b57cec5SDimitry Andric   // Note, we should never try to instantiate a deleted function template.
48940b57cec5SDimitry Andric   assert((Pattern || PatternDecl->isDefaulted() ||
48950b57cec5SDimitry Andric           PatternDecl->hasSkippedBody()) &&
48960b57cec5SDimitry Andric          "unexpected kind of function template definition");
48970b57cec5SDimitry Andric 
48980b57cec5SDimitry Andric   // C++1y [temp.explicit]p10:
48990b57cec5SDimitry Andric   //   Except for inline functions, declarations with types deduced from their
49000b57cec5SDimitry Andric   //   initializer or return value, and class template specializations, other
49010b57cec5SDimitry Andric   //   explicit instantiation declarations have the effect of suppressing the
49020b57cec5SDimitry Andric   //   implicit instantiation of the entity to which they refer.
49030b57cec5SDimitry Andric   if (TSK == TSK_ExplicitInstantiationDeclaration &&
49040b57cec5SDimitry Andric       !PatternDecl->isInlined() &&
49050b57cec5SDimitry Andric       !PatternDecl->getReturnType()->getContainedAutoType())
49060b57cec5SDimitry Andric     return;
49070b57cec5SDimitry Andric 
49080b57cec5SDimitry Andric   if (PatternDecl->isInlined()) {
49090b57cec5SDimitry Andric     // Function, and all later redeclarations of it (from imported modules,
49100b57cec5SDimitry Andric     // for instance), are now implicitly inline.
49110b57cec5SDimitry Andric     for (auto *D = Function->getMostRecentDecl(); /**/;
49120b57cec5SDimitry Andric          D = D->getPreviousDecl()) {
49130b57cec5SDimitry Andric       D->setImplicitlyInline();
49140b57cec5SDimitry Andric       if (D == Function)
49150b57cec5SDimitry Andric         break;
49160b57cec5SDimitry Andric     }
49170b57cec5SDimitry Andric   }
49180b57cec5SDimitry Andric 
49190b57cec5SDimitry Andric   InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
49200b57cec5SDimitry Andric   if (Inst.isInvalid() || Inst.isAlreadyInstantiating())
49210b57cec5SDimitry Andric     return;
49220b57cec5SDimitry Andric   PrettyDeclStackTraceEntry CrashInfo(Context, Function, SourceLocation(),
49230b57cec5SDimitry Andric                                       "instantiating function definition");
49240b57cec5SDimitry Andric 
49250b57cec5SDimitry Andric   // The instantiation is visible here, even if it was first declared in an
49260b57cec5SDimitry Andric   // unimported module.
49270b57cec5SDimitry Andric   Function->setVisibleDespiteOwningModule();
49280b57cec5SDimitry Andric 
49290b57cec5SDimitry Andric   // Copy the inner loc start from the pattern.
49300b57cec5SDimitry Andric   Function->setInnerLocStart(PatternDecl->getInnerLocStart());
49310b57cec5SDimitry Andric 
49320b57cec5SDimitry Andric   EnterExpressionEvaluationContext EvalContext(
49330b57cec5SDimitry Andric       *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
49340b57cec5SDimitry Andric 
49350b57cec5SDimitry Andric   // Introduce a new scope where local variable instantiations will be
49360b57cec5SDimitry Andric   // recorded, unless we're actually a member function within a local
49370b57cec5SDimitry Andric   // class, in which case we need to merge our results with the parent
4938efa485d5SDimitry Andric   // scope (of the enclosing function). The exception is instantiating
4939efa485d5SDimitry Andric   // a function template specialization, since the template to be
4940efa485d5SDimitry Andric   // instantiated already has references to locals properly substituted.
49410b57cec5SDimitry Andric   bool MergeWithParentScope = false;
49420b57cec5SDimitry Andric   if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Function->getDeclContext()))
4943efa485d5SDimitry Andric     MergeWithParentScope =
4944efa485d5SDimitry Andric         Rec->isLocalClass() && !Function->isFunctionTemplateSpecialization();
49450b57cec5SDimitry Andric 
49460b57cec5SDimitry Andric   LocalInstantiationScope Scope(*this, MergeWithParentScope);
4947fe6060f1SDimitry Andric   auto RebuildTypeSourceInfoForDefaultSpecialMembers = [&]() {
4948fe6060f1SDimitry Andric     // Special members might get their TypeSourceInfo set up w.r.t the
4949fe6060f1SDimitry Andric     // PatternDecl context, in which case parameters could still be pointing
4950fe6060f1SDimitry Andric     // back to the original class, make sure arguments are bound to the
4951fe6060f1SDimitry Andric     // instantiated record instead.
4952fe6060f1SDimitry Andric     assert(PatternDecl->isDefaulted() &&
4953fe6060f1SDimitry Andric            "Special member needs to be defaulted");
4954fe6060f1SDimitry Andric     auto PatternSM = getDefaultedFunctionKind(PatternDecl).asSpecialMember();
4955fe6060f1SDimitry Andric     if (!(PatternSM == Sema::CXXCopyConstructor ||
4956fe6060f1SDimitry Andric           PatternSM == Sema::CXXCopyAssignment ||
4957fe6060f1SDimitry Andric           PatternSM == Sema::CXXMoveConstructor ||
4958fe6060f1SDimitry Andric           PatternSM == Sema::CXXMoveAssignment))
4959fe6060f1SDimitry Andric       return;
49600b57cec5SDimitry Andric 
4961fe6060f1SDimitry Andric     auto *NewRec = dyn_cast<CXXRecordDecl>(Function->getDeclContext());
4962fe6060f1SDimitry Andric     const auto *PatternRec =
4963fe6060f1SDimitry Andric         dyn_cast<CXXRecordDecl>(PatternDecl->getDeclContext());
4964fe6060f1SDimitry Andric     if (!NewRec || !PatternRec)
4965fe6060f1SDimitry Andric       return;
4966fe6060f1SDimitry Andric     if (!PatternRec->isLambda())
4967fe6060f1SDimitry Andric       return;
4968fe6060f1SDimitry Andric 
4969fe6060f1SDimitry Andric     struct SpecialMemberTypeInfoRebuilder
4970fe6060f1SDimitry Andric         : TreeTransform<SpecialMemberTypeInfoRebuilder> {
4971fe6060f1SDimitry Andric       using Base = TreeTransform<SpecialMemberTypeInfoRebuilder>;
4972fe6060f1SDimitry Andric       const CXXRecordDecl *OldDecl;
4973fe6060f1SDimitry Andric       CXXRecordDecl *NewDecl;
4974fe6060f1SDimitry Andric 
4975fe6060f1SDimitry Andric       SpecialMemberTypeInfoRebuilder(Sema &SemaRef, const CXXRecordDecl *O,
4976fe6060f1SDimitry Andric                                      CXXRecordDecl *N)
4977fe6060f1SDimitry Andric           : TreeTransform(SemaRef), OldDecl(O), NewDecl(N) {}
4978fe6060f1SDimitry Andric 
4979fe6060f1SDimitry Andric       bool TransformExceptionSpec(SourceLocation Loc,
4980fe6060f1SDimitry Andric                                   FunctionProtoType::ExceptionSpecInfo &ESI,
4981fe6060f1SDimitry Andric                                   SmallVectorImpl<QualType> &Exceptions,
4982fe6060f1SDimitry Andric                                   bool &Changed) {
4983fe6060f1SDimitry Andric         return false;
4984fe6060f1SDimitry Andric       }
4985fe6060f1SDimitry Andric 
4986fe6060f1SDimitry Andric       QualType TransformRecordType(TypeLocBuilder &TLB, RecordTypeLoc TL) {
4987fe6060f1SDimitry Andric         const RecordType *T = TL.getTypePtr();
4988fe6060f1SDimitry Andric         RecordDecl *Record = cast_or_null<RecordDecl>(
4989fe6060f1SDimitry Andric             getDerived().TransformDecl(TL.getNameLoc(), T->getDecl()));
4990fe6060f1SDimitry Andric         if (Record != OldDecl)
4991fe6060f1SDimitry Andric           return Base::TransformRecordType(TLB, TL);
4992fe6060f1SDimitry Andric 
4993fe6060f1SDimitry Andric         QualType Result = getDerived().RebuildRecordType(NewDecl);
4994fe6060f1SDimitry Andric         if (Result.isNull())
4995fe6060f1SDimitry Andric           return QualType();
4996fe6060f1SDimitry Andric 
4997fe6060f1SDimitry Andric         RecordTypeLoc NewTL = TLB.push<RecordTypeLoc>(Result);
4998fe6060f1SDimitry Andric         NewTL.setNameLoc(TL.getNameLoc());
4999fe6060f1SDimitry Andric         return Result;
5000fe6060f1SDimitry Andric       }
5001fe6060f1SDimitry Andric     } IR{*this, PatternRec, NewRec};
5002fe6060f1SDimitry Andric 
5003fe6060f1SDimitry Andric     TypeSourceInfo *NewSI = IR.TransformType(Function->getTypeSourceInfo());
5004fe6060f1SDimitry Andric     Function->setType(NewSI->getType());
5005fe6060f1SDimitry Andric     Function->setTypeSourceInfo(NewSI);
5006fe6060f1SDimitry Andric 
5007fe6060f1SDimitry Andric     ParmVarDecl *Parm = Function->getParamDecl(0);
5008fe6060f1SDimitry Andric     TypeSourceInfo *NewParmSI = IR.TransformType(Parm->getTypeSourceInfo());
5009fe6060f1SDimitry Andric     Parm->setType(NewParmSI->getType());
5010fe6060f1SDimitry Andric     Parm->setTypeSourceInfo(NewParmSI);
5011fe6060f1SDimitry Andric   };
5012fe6060f1SDimitry Andric 
5013fe6060f1SDimitry Andric   if (PatternDecl->isDefaulted()) {
5014fe6060f1SDimitry Andric     RebuildTypeSourceInfoForDefaultSpecialMembers();
50150b57cec5SDimitry Andric     SetDeclDefaulted(Function, PatternDecl->getLocation());
5016fe6060f1SDimitry Andric   } else {
50170b57cec5SDimitry Andric     MultiLevelTemplateArgumentList TemplateArgs =
50180b57cec5SDimitry Andric       getTemplateInstantiationArgs(Function, nullptr, false, PatternDecl);
50190b57cec5SDimitry Andric 
50200b57cec5SDimitry Andric     // Substitute into the qualifier; we can get a substitution failure here
50210b57cec5SDimitry Andric     // through evil use of alias templates.
50220b57cec5SDimitry Andric     // FIXME: Is CurContext correct for this? Should we go to the (instantiation
50230b57cec5SDimitry Andric     // of the) lexical context of the pattern?
50240b57cec5SDimitry Andric     SubstQualifier(*this, PatternDecl, Function, TemplateArgs);
50250b57cec5SDimitry Andric 
50260b57cec5SDimitry Andric     ActOnStartOfFunctionDef(nullptr, Function);
50270b57cec5SDimitry Andric 
50280b57cec5SDimitry Andric     // Enter the scope of this instantiation. We don't use
50290b57cec5SDimitry Andric     // PushDeclContext because we don't have a scope.
50300b57cec5SDimitry Andric     Sema::ContextRAII savedContext(*this, Function);
50310b57cec5SDimitry Andric 
50320b57cec5SDimitry Andric     if (addInstantiatedParametersToScope(*this, Function, PatternDecl, Scope,
50330b57cec5SDimitry Andric                                          TemplateArgs))
50340b57cec5SDimitry Andric       return;
50350b57cec5SDimitry Andric 
50360b57cec5SDimitry Andric     StmtResult Body;
50370b57cec5SDimitry Andric     if (PatternDecl->hasSkippedBody()) {
50380b57cec5SDimitry Andric       ActOnSkippedFunctionBody(Function);
50390b57cec5SDimitry Andric       Body = nullptr;
50400b57cec5SDimitry Andric     } else {
50410b57cec5SDimitry Andric       if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Function)) {
50420b57cec5SDimitry Andric         // If this is a constructor, instantiate the member initializers.
50430b57cec5SDimitry Andric         InstantiateMemInitializers(Ctor, cast<CXXConstructorDecl>(PatternDecl),
50440b57cec5SDimitry Andric                                    TemplateArgs);
50450b57cec5SDimitry Andric 
50460b57cec5SDimitry Andric         // If this is an MS ABI dllexport default constructor, instantiate any
50470b57cec5SDimitry Andric         // default arguments.
50480b57cec5SDimitry Andric         if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
50490b57cec5SDimitry Andric             Ctor->isDefaultConstructor()) {
5050e8d8bef9SDimitry Andric           InstantiateDefaultCtorDefaultArgs(Ctor);
50510b57cec5SDimitry Andric         }
50520b57cec5SDimitry Andric       }
50530b57cec5SDimitry Andric 
50540b57cec5SDimitry Andric       // Instantiate the function body.
50550b57cec5SDimitry Andric       Body = SubstStmt(Pattern, TemplateArgs);
50560b57cec5SDimitry Andric 
50570b57cec5SDimitry Andric       if (Body.isInvalid())
50580b57cec5SDimitry Andric         Function->setInvalidDecl();
50590b57cec5SDimitry Andric     }
50600b57cec5SDimitry Andric     // FIXME: finishing the function body while in an expression evaluation
50610b57cec5SDimitry Andric     // context seems wrong. Investigate more.
50620b57cec5SDimitry Andric     ActOnFinishFunctionBody(Function, Body.get(), /*IsInstantiation=*/true);
50630b57cec5SDimitry Andric 
50640b57cec5SDimitry Andric     PerformDependentDiagnostics(PatternDecl, TemplateArgs);
50650b57cec5SDimitry Andric 
50660b57cec5SDimitry Andric     if (auto *Listener = getASTMutationListener())
50670b57cec5SDimitry Andric       Listener->FunctionDefinitionInstantiated(Function);
50680b57cec5SDimitry Andric 
50690b57cec5SDimitry Andric     savedContext.pop();
50700b57cec5SDimitry Andric   }
50710b57cec5SDimitry Andric 
50720b57cec5SDimitry Andric   DeclGroupRef DG(Function);
50730b57cec5SDimitry Andric   Consumer.HandleTopLevelDecl(DG);
50740b57cec5SDimitry Andric 
50750b57cec5SDimitry Andric   // This class may have local implicit instantiations that need to be
50760b57cec5SDimitry Andric   // instantiation within this scope.
50770b57cec5SDimitry Andric   LocalInstantiations.perform();
50780b57cec5SDimitry Andric   Scope.Exit();
50790b57cec5SDimitry Andric   GlobalInstantiations.perform();
50800b57cec5SDimitry Andric }
50810b57cec5SDimitry Andric 
50820b57cec5SDimitry Andric VarTemplateSpecializationDecl *Sema::BuildVarTemplateInstantiation(
50830b57cec5SDimitry Andric     VarTemplateDecl *VarTemplate, VarDecl *FromVar,
50840b57cec5SDimitry Andric     const TemplateArgumentList &TemplateArgList,
50850b57cec5SDimitry Andric     const TemplateArgumentListInfo &TemplateArgsInfo,
50860b57cec5SDimitry Andric     SmallVectorImpl<TemplateArgument> &Converted,
5087e8d8bef9SDimitry Andric     SourceLocation PointOfInstantiation,
50880b57cec5SDimitry Andric     LateInstantiatedAttrVec *LateAttrs,
50890b57cec5SDimitry Andric     LocalInstantiationScope *StartingScope) {
50900b57cec5SDimitry Andric   if (FromVar->isInvalidDecl())
50910b57cec5SDimitry Andric     return nullptr;
50920b57cec5SDimitry Andric 
50930b57cec5SDimitry Andric   InstantiatingTemplate Inst(*this, PointOfInstantiation, FromVar);
50940b57cec5SDimitry Andric   if (Inst.isInvalid())
50950b57cec5SDimitry Andric     return nullptr;
50960b57cec5SDimitry Andric 
50970b57cec5SDimitry Andric   MultiLevelTemplateArgumentList TemplateArgLists;
50980b57cec5SDimitry Andric   TemplateArgLists.addOuterTemplateArguments(&TemplateArgList);
50990b57cec5SDimitry Andric 
51000b57cec5SDimitry Andric   // Instantiate the first declaration of the variable template: for a partial
51010b57cec5SDimitry Andric   // specialization of a static data member template, the first declaration may
51020b57cec5SDimitry Andric   // or may not be the declaration in the class; if it's in the class, we want
51030b57cec5SDimitry Andric   // to instantiate a member in the class (a declaration), and if it's outside,
51040b57cec5SDimitry Andric   // we want to instantiate a definition.
51050b57cec5SDimitry Andric   //
51060b57cec5SDimitry Andric   // If we're instantiating an explicitly-specialized member template or member
51070b57cec5SDimitry Andric   // partial specialization, don't do this. The member specialization completely
51080b57cec5SDimitry Andric   // replaces the original declaration in this case.
51090b57cec5SDimitry Andric   bool IsMemberSpec = false;
51100b57cec5SDimitry Andric   if (VarTemplatePartialSpecializationDecl *PartialSpec =
51110b57cec5SDimitry Andric           dyn_cast<VarTemplatePartialSpecializationDecl>(FromVar))
51120b57cec5SDimitry Andric     IsMemberSpec = PartialSpec->isMemberSpecialization();
51130b57cec5SDimitry Andric   else if (VarTemplateDecl *FromTemplate = FromVar->getDescribedVarTemplate())
51140b57cec5SDimitry Andric     IsMemberSpec = FromTemplate->isMemberSpecialization();
51150b57cec5SDimitry Andric   if (!IsMemberSpec)
51160b57cec5SDimitry Andric     FromVar = FromVar->getFirstDecl();
51170b57cec5SDimitry Andric 
51180b57cec5SDimitry Andric   MultiLevelTemplateArgumentList MultiLevelList(TemplateArgList);
51190b57cec5SDimitry Andric   TemplateDeclInstantiator Instantiator(*this, FromVar->getDeclContext(),
51200b57cec5SDimitry Andric                                         MultiLevelList);
51210b57cec5SDimitry Andric 
51220b57cec5SDimitry Andric   // TODO: Set LateAttrs and StartingScope ...
51230b57cec5SDimitry Andric 
51240b57cec5SDimitry Andric   return cast_or_null<VarTemplateSpecializationDecl>(
51250b57cec5SDimitry Andric       Instantiator.VisitVarTemplateSpecializationDecl(
5126e8d8bef9SDimitry Andric           VarTemplate, FromVar, TemplateArgsInfo, Converted));
51270b57cec5SDimitry Andric }
51280b57cec5SDimitry Andric 
51290b57cec5SDimitry Andric /// Instantiates a variable template specialization by completing it
51300b57cec5SDimitry Andric /// with appropriate type information and initializer.
51310b57cec5SDimitry Andric VarTemplateSpecializationDecl *Sema::CompleteVarTemplateSpecializationDecl(
51320b57cec5SDimitry Andric     VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl,
51330b57cec5SDimitry Andric     const MultiLevelTemplateArgumentList &TemplateArgs) {
51340b57cec5SDimitry Andric   assert(PatternDecl->isThisDeclarationADefinition() &&
51350b57cec5SDimitry Andric          "don't have a definition to instantiate from");
51360b57cec5SDimitry Andric 
51370b57cec5SDimitry Andric   // Do substitution on the type of the declaration
51380b57cec5SDimitry Andric   TypeSourceInfo *DI =
51390b57cec5SDimitry Andric       SubstType(PatternDecl->getTypeSourceInfo(), TemplateArgs,
51400b57cec5SDimitry Andric                 PatternDecl->getTypeSpecStartLoc(), PatternDecl->getDeclName());
51410b57cec5SDimitry Andric   if (!DI)
51420b57cec5SDimitry Andric     return nullptr;
51430b57cec5SDimitry Andric 
51440b57cec5SDimitry Andric   // Update the type of this variable template specialization.
51450b57cec5SDimitry Andric   VarSpec->setType(DI->getType());
51460b57cec5SDimitry Andric 
51470b57cec5SDimitry Andric   // Convert the declaration into a definition now.
51480b57cec5SDimitry Andric   VarSpec->setCompleteDefinition();
51490b57cec5SDimitry Andric 
51500b57cec5SDimitry Andric   // Instantiate the initializer.
51510b57cec5SDimitry Andric   InstantiateVariableInitializer(VarSpec, PatternDecl, TemplateArgs);
51520b57cec5SDimitry Andric 
51535ffd83dbSDimitry Andric   if (getLangOpts().OpenCL)
51545ffd83dbSDimitry Andric     deduceOpenCLAddressSpace(VarSpec);
51555ffd83dbSDimitry Andric 
51560b57cec5SDimitry Andric   return VarSpec;
51570b57cec5SDimitry Andric }
51580b57cec5SDimitry Andric 
51590b57cec5SDimitry Andric /// BuildVariableInstantiation - Used after a new variable has been created.
51600b57cec5SDimitry Andric /// Sets basic variable data and decides whether to postpone the
51610b57cec5SDimitry Andric /// variable instantiation.
51620b57cec5SDimitry Andric void Sema::BuildVariableInstantiation(
51630b57cec5SDimitry Andric     VarDecl *NewVar, VarDecl *OldVar,
51640b57cec5SDimitry Andric     const MultiLevelTemplateArgumentList &TemplateArgs,
51650b57cec5SDimitry Andric     LateInstantiatedAttrVec *LateAttrs, DeclContext *Owner,
51660b57cec5SDimitry Andric     LocalInstantiationScope *StartingScope,
51670b57cec5SDimitry Andric     bool InstantiatingVarTemplate,
51680b57cec5SDimitry Andric     VarTemplateSpecializationDecl *PrevDeclForVarTemplateSpecialization) {
51690b57cec5SDimitry Andric   // Instantiating a partial specialization to produce a partial
51700b57cec5SDimitry Andric   // specialization.
51710b57cec5SDimitry Andric   bool InstantiatingVarTemplatePartialSpec =
51720b57cec5SDimitry Andric       isa<VarTemplatePartialSpecializationDecl>(OldVar) &&
51730b57cec5SDimitry Andric       isa<VarTemplatePartialSpecializationDecl>(NewVar);
51740b57cec5SDimitry Andric   // Instantiating from a variable template (or partial specialization) to
51750b57cec5SDimitry Andric   // produce a variable template specialization.
51760b57cec5SDimitry Andric   bool InstantiatingSpecFromTemplate =
51770b57cec5SDimitry Andric       isa<VarTemplateSpecializationDecl>(NewVar) &&
51780b57cec5SDimitry Andric       (OldVar->getDescribedVarTemplate() ||
51790b57cec5SDimitry Andric        isa<VarTemplatePartialSpecializationDecl>(OldVar));
51800b57cec5SDimitry Andric 
51810b57cec5SDimitry Andric   // If we are instantiating a local extern declaration, the
51820b57cec5SDimitry Andric   // instantiation belongs lexically to the containing function.
51830b57cec5SDimitry Andric   // If we are instantiating a static data member defined
51840b57cec5SDimitry Andric   // out-of-line, the instantiation will have the same lexical
51850b57cec5SDimitry Andric   // context (which will be a namespace scope) as the template.
51860b57cec5SDimitry Andric   if (OldVar->isLocalExternDecl()) {
51870b57cec5SDimitry Andric     NewVar->setLocalExternDecl();
51880b57cec5SDimitry Andric     NewVar->setLexicalDeclContext(Owner);
51890b57cec5SDimitry Andric   } else if (OldVar->isOutOfLine())
51900b57cec5SDimitry Andric     NewVar->setLexicalDeclContext(OldVar->getLexicalDeclContext());
51910b57cec5SDimitry Andric   NewVar->setTSCSpec(OldVar->getTSCSpec());
51920b57cec5SDimitry Andric   NewVar->setInitStyle(OldVar->getInitStyle());
51930b57cec5SDimitry Andric   NewVar->setCXXForRangeDecl(OldVar->isCXXForRangeDecl());
51940b57cec5SDimitry Andric   NewVar->setObjCForDecl(OldVar->isObjCForDecl());
51950b57cec5SDimitry Andric   NewVar->setConstexpr(OldVar->isConstexpr());
51960b57cec5SDimitry Andric   NewVar->setInitCapture(OldVar->isInitCapture());
51970b57cec5SDimitry Andric   NewVar->setPreviousDeclInSameBlockScope(
51980b57cec5SDimitry Andric       OldVar->isPreviousDeclInSameBlockScope());
51990b57cec5SDimitry Andric   NewVar->setAccess(OldVar->getAccess());
52000b57cec5SDimitry Andric 
52010b57cec5SDimitry Andric   if (!OldVar->isStaticDataMember()) {
52020b57cec5SDimitry Andric     if (OldVar->isUsed(false))
52030b57cec5SDimitry Andric       NewVar->setIsUsed();
52040b57cec5SDimitry Andric     NewVar->setReferenced(OldVar->isReferenced());
52050b57cec5SDimitry Andric   }
52060b57cec5SDimitry Andric 
52070b57cec5SDimitry Andric   InstantiateAttrs(TemplateArgs, OldVar, NewVar, LateAttrs, StartingScope);
52080b57cec5SDimitry Andric 
52090b57cec5SDimitry Andric   LookupResult Previous(
52100b57cec5SDimitry Andric       *this, NewVar->getDeclName(), NewVar->getLocation(),
52110b57cec5SDimitry Andric       NewVar->isLocalExternDecl() ? Sema::LookupRedeclarationWithLinkage
52120b57cec5SDimitry Andric                                   : Sema::LookupOrdinaryName,
52130b57cec5SDimitry Andric       NewVar->isLocalExternDecl() ? Sema::ForExternalRedeclaration
52140b57cec5SDimitry Andric                                   : forRedeclarationInCurContext());
52150b57cec5SDimitry Andric 
52160b57cec5SDimitry Andric   if (NewVar->isLocalExternDecl() && OldVar->getPreviousDecl() &&
52170b57cec5SDimitry Andric       (!OldVar->getPreviousDecl()->getDeclContext()->isDependentContext() ||
52180b57cec5SDimitry Andric        OldVar->getPreviousDecl()->getDeclContext()==OldVar->getDeclContext())) {
52190b57cec5SDimitry Andric     // We have a previous declaration. Use that one, so we merge with the
52200b57cec5SDimitry Andric     // right type.
52210b57cec5SDimitry Andric     if (NamedDecl *NewPrev = FindInstantiatedDecl(
52220b57cec5SDimitry Andric             NewVar->getLocation(), OldVar->getPreviousDecl(), TemplateArgs))
52230b57cec5SDimitry Andric       Previous.addDecl(NewPrev);
52240b57cec5SDimitry Andric   } else if (!isa<VarTemplateSpecializationDecl>(NewVar) &&
52250b57cec5SDimitry Andric              OldVar->hasLinkage()) {
52260b57cec5SDimitry Andric     LookupQualifiedName(Previous, NewVar->getDeclContext(), false);
52270b57cec5SDimitry Andric   } else if (PrevDeclForVarTemplateSpecialization) {
52280b57cec5SDimitry Andric     Previous.addDecl(PrevDeclForVarTemplateSpecialization);
52290b57cec5SDimitry Andric   }
52300b57cec5SDimitry Andric   CheckVariableDeclaration(NewVar, Previous);
52310b57cec5SDimitry Andric 
52320b57cec5SDimitry Andric   if (!InstantiatingVarTemplate) {
52330b57cec5SDimitry Andric     NewVar->getLexicalDeclContext()->addHiddenDecl(NewVar);
52340b57cec5SDimitry Andric     if (!NewVar->isLocalExternDecl() || !NewVar->getPreviousDecl())
52350b57cec5SDimitry Andric       NewVar->getDeclContext()->makeDeclVisibleInContext(NewVar);
52360b57cec5SDimitry Andric   }
52370b57cec5SDimitry Andric 
52380b57cec5SDimitry Andric   if (!OldVar->isOutOfLine()) {
52390b57cec5SDimitry Andric     if (NewVar->getDeclContext()->isFunctionOrMethod())
52400b57cec5SDimitry Andric       CurrentInstantiationScope->InstantiatedLocal(OldVar, NewVar);
52410b57cec5SDimitry Andric   }
52420b57cec5SDimitry Andric 
52430b57cec5SDimitry Andric   // Link instantiations of static data members back to the template from
52440b57cec5SDimitry Andric   // which they were instantiated.
52450b57cec5SDimitry Andric   //
52460b57cec5SDimitry Andric   // Don't do this when instantiating a template (we link the template itself
52470b57cec5SDimitry Andric   // back in that case) nor when instantiating a static data member template
52480b57cec5SDimitry Andric   // (that's not a member specialization).
52490b57cec5SDimitry Andric   if (NewVar->isStaticDataMember() && !InstantiatingVarTemplate &&
52500b57cec5SDimitry Andric       !InstantiatingSpecFromTemplate)
52510b57cec5SDimitry Andric     NewVar->setInstantiationOfStaticDataMember(OldVar,
52520b57cec5SDimitry Andric                                                TSK_ImplicitInstantiation);
52530b57cec5SDimitry Andric 
52540b57cec5SDimitry Andric   // If the pattern is an (in-class) explicit specialization, then the result
52550b57cec5SDimitry Andric   // is also an explicit specialization.
52560b57cec5SDimitry Andric   if (VarTemplateSpecializationDecl *OldVTSD =
52570b57cec5SDimitry Andric           dyn_cast<VarTemplateSpecializationDecl>(OldVar)) {
52580b57cec5SDimitry Andric     if (OldVTSD->getSpecializationKind() == TSK_ExplicitSpecialization &&
52590b57cec5SDimitry Andric         !isa<VarTemplatePartialSpecializationDecl>(OldVTSD))
52600b57cec5SDimitry Andric       cast<VarTemplateSpecializationDecl>(NewVar)->setSpecializationKind(
52610b57cec5SDimitry Andric           TSK_ExplicitSpecialization);
52620b57cec5SDimitry Andric   }
52630b57cec5SDimitry Andric 
52640b57cec5SDimitry Andric   // Forward the mangling number from the template to the instantiated decl.
52650b57cec5SDimitry Andric   Context.setManglingNumber(NewVar, Context.getManglingNumber(OldVar));
52660b57cec5SDimitry Andric   Context.setStaticLocalNumber(NewVar, Context.getStaticLocalNumber(OldVar));
52670b57cec5SDimitry Andric 
52680b57cec5SDimitry Andric   // Figure out whether to eagerly instantiate the initializer.
52690b57cec5SDimitry Andric   if (InstantiatingVarTemplate || InstantiatingVarTemplatePartialSpec) {
52700b57cec5SDimitry Andric     // We're producing a template. Don't instantiate the initializer yet.
52710b57cec5SDimitry Andric   } else if (NewVar->getType()->isUndeducedType()) {
52720b57cec5SDimitry Andric     // We need the type to complete the declaration of the variable.
52730b57cec5SDimitry Andric     InstantiateVariableInitializer(NewVar, OldVar, TemplateArgs);
52740b57cec5SDimitry Andric   } else if (InstantiatingSpecFromTemplate ||
52750b57cec5SDimitry Andric              (OldVar->isInline() && OldVar->isThisDeclarationADefinition() &&
52760b57cec5SDimitry Andric               !NewVar->isThisDeclarationADefinition())) {
52770b57cec5SDimitry Andric     // Delay instantiation of the initializer for variable template
52780b57cec5SDimitry Andric     // specializations or inline static data members until a definition of the
52790b57cec5SDimitry Andric     // variable is needed.
52800b57cec5SDimitry Andric   } else {
52810b57cec5SDimitry Andric     InstantiateVariableInitializer(NewVar, OldVar, TemplateArgs);
52820b57cec5SDimitry Andric   }
52830b57cec5SDimitry Andric 
52840b57cec5SDimitry Andric   // Diagnose unused local variables with dependent types, where the diagnostic
52850b57cec5SDimitry Andric   // will have been deferred.
52860b57cec5SDimitry Andric   if (!NewVar->isInvalidDecl() &&
52870b57cec5SDimitry Andric       NewVar->getDeclContext()->isFunctionOrMethod() &&
52880b57cec5SDimitry Andric       OldVar->getType()->isDependentType())
52890b57cec5SDimitry Andric     DiagnoseUnusedDecl(NewVar);
52900b57cec5SDimitry Andric }
52910b57cec5SDimitry Andric 
52920b57cec5SDimitry Andric /// Instantiate the initializer of a variable.
52930b57cec5SDimitry Andric void Sema::InstantiateVariableInitializer(
52940b57cec5SDimitry Andric     VarDecl *Var, VarDecl *OldVar,
52950b57cec5SDimitry Andric     const MultiLevelTemplateArgumentList &TemplateArgs) {
52960b57cec5SDimitry Andric   if (ASTMutationListener *L = getASTContext().getASTMutationListener())
52970b57cec5SDimitry Andric     L->VariableDefinitionInstantiated(Var);
52980b57cec5SDimitry Andric 
52990b57cec5SDimitry Andric   // We propagate the 'inline' flag with the initializer, because it
53000b57cec5SDimitry Andric   // would otherwise imply that the variable is a definition for a
53010b57cec5SDimitry Andric   // non-static data member.
53020b57cec5SDimitry Andric   if (OldVar->isInlineSpecified())
53030b57cec5SDimitry Andric     Var->setInlineSpecified();
53040b57cec5SDimitry Andric   else if (OldVar->isInline())
53050b57cec5SDimitry Andric     Var->setImplicitlyInline();
53060b57cec5SDimitry Andric 
53070b57cec5SDimitry Andric   if (OldVar->getInit()) {
53080b57cec5SDimitry Andric     EnterExpressionEvaluationContext Evaluated(
53090b57cec5SDimitry Andric         *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated, Var);
53100b57cec5SDimitry Andric 
53110b57cec5SDimitry Andric     // Instantiate the initializer.
53120b57cec5SDimitry Andric     ExprResult Init;
53130b57cec5SDimitry Andric 
53140b57cec5SDimitry Andric     {
53150b57cec5SDimitry Andric       ContextRAII SwitchContext(*this, Var->getDeclContext());
53160b57cec5SDimitry Andric       Init = SubstInitializer(OldVar->getInit(), TemplateArgs,
53170b57cec5SDimitry Andric                               OldVar->getInitStyle() == VarDecl::CallInit);
53180b57cec5SDimitry Andric     }
53190b57cec5SDimitry Andric 
53200b57cec5SDimitry Andric     if (!Init.isInvalid()) {
53210b57cec5SDimitry Andric       Expr *InitExpr = Init.get();
53220b57cec5SDimitry Andric 
53230b57cec5SDimitry Andric       if (Var->hasAttr<DLLImportAttr>() &&
53240b57cec5SDimitry Andric           (!InitExpr ||
53250b57cec5SDimitry Andric            !InitExpr->isConstantInitializer(getASTContext(), false))) {
53260b57cec5SDimitry Andric         // Do not dynamically initialize dllimport variables.
53270b57cec5SDimitry Andric       } else if (InitExpr) {
53280b57cec5SDimitry Andric         bool DirectInit = OldVar->isDirectInit();
53290b57cec5SDimitry Andric         AddInitializerToDecl(Var, InitExpr, DirectInit);
53300b57cec5SDimitry Andric       } else
53310b57cec5SDimitry Andric         ActOnUninitializedDecl(Var);
53320b57cec5SDimitry Andric     } else {
53330b57cec5SDimitry Andric       // FIXME: Not too happy about invalidating the declaration
53340b57cec5SDimitry Andric       // because of a bogus initializer.
53350b57cec5SDimitry Andric       Var->setInvalidDecl();
53360b57cec5SDimitry Andric     }
53370b57cec5SDimitry Andric   } else {
53380b57cec5SDimitry Andric     // `inline` variables are a definition and declaration all in one; we won't
53390b57cec5SDimitry Andric     // pick up an initializer from anywhere else.
53400b57cec5SDimitry Andric     if (Var->isStaticDataMember() && !Var->isInline()) {
53410b57cec5SDimitry Andric       if (!Var->isOutOfLine())
53420b57cec5SDimitry Andric         return;
53430b57cec5SDimitry Andric 
53440b57cec5SDimitry Andric       // If the declaration inside the class had an initializer, don't add
53450b57cec5SDimitry Andric       // another one to the out-of-line definition.
53460b57cec5SDimitry Andric       if (OldVar->getFirstDecl()->hasInit())
53470b57cec5SDimitry Andric         return;
53480b57cec5SDimitry Andric     }
53490b57cec5SDimitry Andric 
53500b57cec5SDimitry Andric     // We'll add an initializer to a for-range declaration later.
53510b57cec5SDimitry Andric     if (Var->isCXXForRangeDecl() || Var->isObjCForDecl())
53520b57cec5SDimitry Andric       return;
53530b57cec5SDimitry Andric 
53540b57cec5SDimitry Andric     ActOnUninitializedDecl(Var);
53550b57cec5SDimitry Andric   }
53560b57cec5SDimitry Andric 
53570b57cec5SDimitry Andric   if (getLangOpts().CUDA)
53580b57cec5SDimitry Andric     checkAllowedCUDAInitializer(Var);
53590b57cec5SDimitry Andric }
53600b57cec5SDimitry Andric 
53610b57cec5SDimitry Andric /// Instantiate the definition of the given variable from its
53620b57cec5SDimitry Andric /// template.
53630b57cec5SDimitry Andric ///
53640b57cec5SDimitry Andric /// \param PointOfInstantiation the point at which the instantiation was
53650b57cec5SDimitry Andric /// required. Note that this is not precisely a "point of instantiation"
53660b57cec5SDimitry Andric /// for the variable, but it's close.
53670b57cec5SDimitry Andric ///
53680b57cec5SDimitry Andric /// \param Var the already-instantiated declaration of a templated variable.
53690b57cec5SDimitry Andric ///
53700b57cec5SDimitry Andric /// \param Recursive if true, recursively instantiates any functions that
53710b57cec5SDimitry Andric /// are required by this instantiation.
53720b57cec5SDimitry Andric ///
53730b57cec5SDimitry Andric /// \param DefinitionRequired if true, then we are performing an explicit
53740b57cec5SDimitry Andric /// instantiation where a definition of the variable is required. Complain
53750b57cec5SDimitry Andric /// if there is no such definition.
53760b57cec5SDimitry Andric void Sema::InstantiateVariableDefinition(SourceLocation PointOfInstantiation,
53770b57cec5SDimitry Andric                                          VarDecl *Var, bool Recursive,
53780b57cec5SDimitry Andric                                       bool DefinitionRequired, bool AtEndOfTU) {
53790b57cec5SDimitry Andric   if (Var->isInvalidDecl())
53800b57cec5SDimitry Andric     return;
53810b57cec5SDimitry Andric 
53820b57cec5SDimitry Andric   // Never instantiate an explicitly-specialized entity.
53830b57cec5SDimitry Andric   TemplateSpecializationKind TSK =
53840b57cec5SDimitry Andric       Var->getTemplateSpecializationKindForInstantiation();
53850b57cec5SDimitry Andric   if (TSK == TSK_ExplicitSpecialization)
53860b57cec5SDimitry Andric     return;
53870b57cec5SDimitry Andric 
53880b57cec5SDimitry Andric   // Find the pattern and the arguments to substitute into it.
53890b57cec5SDimitry Andric   VarDecl *PatternDecl = Var->getTemplateInstantiationPattern();
53900b57cec5SDimitry Andric   assert(PatternDecl && "no pattern for templated variable");
53910b57cec5SDimitry Andric   MultiLevelTemplateArgumentList TemplateArgs =
53920b57cec5SDimitry Andric       getTemplateInstantiationArgs(Var);
53930b57cec5SDimitry Andric 
53940b57cec5SDimitry Andric   VarTemplateSpecializationDecl *VarSpec =
53950b57cec5SDimitry Andric       dyn_cast<VarTemplateSpecializationDecl>(Var);
53960b57cec5SDimitry Andric   if (VarSpec) {
53970b57cec5SDimitry Andric     // If this is a static data member template, there might be an
53980b57cec5SDimitry Andric     // uninstantiated initializer on the declaration. If so, instantiate
53990b57cec5SDimitry Andric     // it now.
54000b57cec5SDimitry Andric     //
54010b57cec5SDimitry Andric     // FIXME: This largely duplicates what we would do below. The difference
54020b57cec5SDimitry Andric     // is that along this path we may instantiate an initializer from an
54030b57cec5SDimitry Andric     // in-class declaration of the template and instantiate the definition
54040b57cec5SDimitry Andric     // from a separate out-of-class definition.
54050b57cec5SDimitry Andric     if (PatternDecl->isStaticDataMember() &&
54060b57cec5SDimitry Andric         (PatternDecl = PatternDecl->getFirstDecl())->hasInit() &&
54070b57cec5SDimitry Andric         !Var->hasInit()) {
54080b57cec5SDimitry Andric       // FIXME: Factor out the duplicated instantiation context setup/tear down
54090b57cec5SDimitry Andric       // code here.
54100b57cec5SDimitry Andric       InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
54110b57cec5SDimitry Andric       if (Inst.isInvalid() || Inst.isAlreadyInstantiating())
54120b57cec5SDimitry Andric         return;
54130b57cec5SDimitry Andric       PrettyDeclStackTraceEntry CrashInfo(Context, Var, SourceLocation(),
54140b57cec5SDimitry Andric                                           "instantiating variable initializer");
54150b57cec5SDimitry Andric 
54160b57cec5SDimitry Andric       // The instantiation is visible here, even if it was first declared in an
54170b57cec5SDimitry Andric       // unimported module.
54180b57cec5SDimitry Andric       Var->setVisibleDespiteOwningModule();
54190b57cec5SDimitry Andric 
54200b57cec5SDimitry Andric       // If we're performing recursive template instantiation, create our own
54210b57cec5SDimitry Andric       // queue of pending implicit instantiations that we will instantiate
54220b57cec5SDimitry Andric       // later, while we're still within our own instantiation context.
54230b57cec5SDimitry Andric       GlobalEagerInstantiationScope GlobalInstantiations(*this,
54240b57cec5SDimitry Andric                                                          /*Enabled=*/Recursive);
54250b57cec5SDimitry Andric       LocalInstantiationScope Local(*this);
54260b57cec5SDimitry Andric       LocalEagerInstantiationScope LocalInstantiations(*this);
54270b57cec5SDimitry Andric 
54280b57cec5SDimitry Andric       // Enter the scope of this instantiation. We don't use
54290b57cec5SDimitry Andric       // PushDeclContext because we don't have a scope.
54300b57cec5SDimitry Andric       ContextRAII PreviousContext(*this, Var->getDeclContext());
54310b57cec5SDimitry Andric       InstantiateVariableInitializer(Var, PatternDecl, TemplateArgs);
54320b57cec5SDimitry Andric       PreviousContext.pop();
54330b57cec5SDimitry Andric 
54340b57cec5SDimitry Andric       // This variable may have local implicit instantiations that need to be
54350b57cec5SDimitry Andric       // instantiated within this scope.
54360b57cec5SDimitry Andric       LocalInstantiations.perform();
54370b57cec5SDimitry Andric       Local.Exit();
54380b57cec5SDimitry Andric       GlobalInstantiations.perform();
54390b57cec5SDimitry Andric     }
54400b57cec5SDimitry Andric   } else {
54410b57cec5SDimitry Andric     assert(Var->isStaticDataMember() && PatternDecl->isStaticDataMember() &&
54420b57cec5SDimitry Andric            "not a static data member?");
54430b57cec5SDimitry Andric   }
54440b57cec5SDimitry Andric 
54450b57cec5SDimitry Andric   VarDecl *Def = PatternDecl->getDefinition(getASTContext());
54460b57cec5SDimitry Andric 
54470b57cec5SDimitry Andric   // If we don't have a definition of the variable template, we won't perform
54480b57cec5SDimitry Andric   // any instantiation. Rather, we rely on the user to instantiate this
54490b57cec5SDimitry Andric   // definition (or provide a specialization for it) in another translation
54500b57cec5SDimitry Andric   // unit.
54510b57cec5SDimitry Andric   if (!Def && !DefinitionRequired) {
54520b57cec5SDimitry Andric     if (TSK == TSK_ExplicitInstantiationDefinition) {
54530b57cec5SDimitry Andric       PendingInstantiations.push_back(
54540b57cec5SDimitry Andric         std::make_pair(Var, PointOfInstantiation));
54550b57cec5SDimitry Andric     } else if (TSK == TSK_ImplicitInstantiation) {
54560b57cec5SDimitry Andric       // Warn about missing definition at the end of translation unit.
54570b57cec5SDimitry Andric       if (AtEndOfTU && !getDiagnostics().hasErrorOccurred() &&
54580b57cec5SDimitry Andric           !getSourceManager().isInSystemHeader(PatternDecl->getBeginLoc())) {
54590b57cec5SDimitry Andric         Diag(PointOfInstantiation, diag::warn_var_template_missing)
54600b57cec5SDimitry Andric           << Var;
54610b57cec5SDimitry Andric         Diag(PatternDecl->getLocation(), diag::note_forward_template_decl);
54620b57cec5SDimitry Andric         if (getLangOpts().CPlusPlus11)
54630b57cec5SDimitry Andric           Diag(PointOfInstantiation, diag::note_inst_declaration_hint) << Var;
54640b57cec5SDimitry Andric       }
54650b57cec5SDimitry Andric       return;
54660b57cec5SDimitry Andric     }
54670b57cec5SDimitry Andric   }
54680b57cec5SDimitry Andric 
54690b57cec5SDimitry Andric   // FIXME: We need to track the instantiation stack in order to know which
54700b57cec5SDimitry Andric   // definitions should be visible within this instantiation.
54710b57cec5SDimitry Andric   // FIXME: Produce diagnostics when Var->getInstantiatedFromStaticDataMember().
54720b57cec5SDimitry Andric   if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Var,
54730b57cec5SDimitry Andric                                      /*InstantiatedFromMember*/false,
54740b57cec5SDimitry Andric                                      PatternDecl, Def, TSK,
54750b57cec5SDimitry Andric                                      /*Complain*/DefinitionRequired))
54760b57cec5SDimitry Andric     return;
54770b57cec5SDimitry Andric 
54780b57cec5SDimitry Andric   // C++11 [temp.explicit]p10:
54790b57cec5SDimitry Andric   //   Except for inline functions, const variables of literal types, variables
54800b57cec5SDimitry Andric   //   of reference types, [...] explicit instantiation declarations
54810b57cec5SDimitry Andric   //   have the effect of suppressing the implicit instantiation of the entity
54820b57cec5SDimitry Andric   //   to which they refer.
54830b57cec5SDimitry Andric   //
54840b57cec5SDimitry Andric   // FIXME: That's not exactly the same as "might be usable in constant
54850b57cec5SDimitry Andric   // expressions", which only allows constexpr variables and const integral
54860b57cec5SDimitry Andric   // types, not arbitrary const literal types.
54870b57cec5SDimitry Andric   if (TSK == TSK_ExplicitInstantiationDeclaration &&
54880b57cec5SDimitry Andric       !Var->mightBeUsableInConstantExpressions(getASTContext()))
54890b57cec5SDimitry Andric     return;
54900b57cec5SDimitry Andric 
54910b57cec5SDimitry Andric   // Make sure to pass the instantiated variable to the consumer at the end.
54920b57cec5SDimitry Andric   struct PassToConsumerRAII {
54930b57cec5SDimitry Andric     ASTConsumer &Consumer;
54940b57cec5SDimitry Andric     VarDecl *Var;
54950b57cec5SDimitry Andric 
54960b57cec5SDimitry Andric     PassToConsumerRAII(ASTConsumer &Consumer, VarDecl *Var)
54970b57cec5SDimitry Andric       : Consumer(Consumer), Var(Var) { }
54980b57cec5SDimitry Andric 
54990b57cec5SDimitry Andric     ~PassToConsumerRAII() {
55000b57cec5SDimitry Andric       Consumer.HandleCXXStaticMemberVarInstantiation(Var);
55010b57cec5SDimitry Andric     }
55020b57cec5SDimitry Andric   } PassToConsumerRAII(Consumer, Var);
55030b57cec5SDimitry Andric 
55040b57cec5SDimitry Andric   // If we already have a definition, we're done.
55050b57cec5SDimitry Andric   if (VarDecl *Def = Var->getDefinition()) {
55060b57cec5SDimitry Andric     // We may be explicitly instantiating something we've already implicitly
55070b57cec5SDimitry Andric     // instantiated.
55080b57cec5SDimitry Andric     Def->setTemplateSpecializationKind(Var->getTemplateSpecializationKind(),
55090b57cec5SDimitry Andric                                        PointOfInstantiation);
55100b57cec5SDimitry Andric     return;
55110b57cec5SDimitry Andric   }
55120b57cec5SDimitry Andric 
55130b57cec5SDimitry Andric   InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
55140b57cec5SDimitry Andric   if (Inst.isInvalid() || Inst.isAlreadyInstantiating())
55150b57cec5SDimitry Andric     return;
55160b57cec5SDimitry Andric   PrettyDeclStackTraceEntry CrashInfo(Context, Var, SourceLocation(),
55170b57cec5SDimitry Andric                                       "instantiating variable definition");
55180b57cec5SDimitry Andric 
55190b57cec5SDimitry Andric   // If we're performing recursive template instantiation, create our own
55200b57cec5SDimitry Andric   // queue of pending implicit instantiations that we will instantiate later,
55210b57cec5SDimitry Andric   // while we're still within our own instantiation context.
55220b57cec5SDimitry Andric   GlobalEagerInstantiationScope GlobalInstantiations(*this,
55230b57cec5SDimitry Andric                                                      /*Enabled=*/Recursive);
55240b57cec5SDimitry Andric 
55250b57cec5SDimitry Andric   // Enter the scope of this instantiation. We don't use
55260b57cec5SDimitry Andric   // PushDeclContext because we don't have a scope.
55270b57cec5SDimitry Andric   ContextRAII PreviousContext(*this, Var->getDeclContext());
55280b57cec5SDimitry Andric   LocalInstantiationScope Local(*this);
55290b57cec5SDimitry Andric 
55300b57cec5SDimitry Andric   LocalEagerInstantiationScope LocalInstantiations(*this);
55310b57cec5SDimitry Andric 
55320b57cec5SDimitry Andric   VarDecl *OldVar = Var;
55330b57cec5SDimitry Andric   if (Def->isStaticDataMember() && !Def->isOutOfLine()) {
55340b57cec5SDimitry Andric     // We're instantiating an inline static data member whose definition was
55350b57cec5SDimitry Andric     // provided inside the class.
55360b57cec5SDimitry Andric     InstantiateVariableInitializer(Var, Def, TemplateArgs);
55370b57cec5SDimitry Andric   } else if (!VarSpec) {
55380b57cec5SDimitry Andric     Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(),
55390b57cec5SDimitry Andric                                           TemplateArgs));
55400b57cec5SDimitry Andric   } else if (Var->isStaticDataMember() &&
55410b57cec5SDimitry Andric              Var->getLexicalDeclContext()->isRecord()) {
55420b57cec5SDimitry Andric     // We need to instantiate the definition of a static data member template,
55430b57cec5SDimitry Andric     // and all we have is the in-class declaration of it. Instantiate a separate
55440b57cec5SDimitry Andric     // declaration of the definition.
55450b57cec5SDimitry Andric     TemplateDeclInstantiator Instantiator(*this, Var->getDeclContext(),
55460b57cec5SDimitry Andric                                           TemplateArgs);
55470b57cec5SDimitry Andric     Var = cast_or_null<VarDecl>(Instantiator.VisitVarTemplateSpecializationDecl(
5548e8d8bef9SDimitry Andric         VarSpec->getSpecializedTemplate(), Def, VarSpec->getTemplateArgsInfo(),
5549e8d8bef9SDimitry Andric         VarSpec->getTemplateArgs().asArray(), VarSpec));
55500b57cec5SDimitry Andric     if (Var) {
55510b57cec5SDimitry Andric       llvm::PointerUnion<VarTemplateDecl *,
55520b57cec5SDimitry Andric                          VarTemplatePartialSpecializationDecl *> PatternPtr =
55530b57cec5SDimitry Andric           VarSpec->getSpecializedTemplateOrPartial();
55540b57cec5SDimitry Andric       if (VarTemplatePartialSpecializationDecl *Partial =
55550b57cec5SDimitry Andric           PatternPtr.dyn_cast<VarTemplatePartialSpecializationDecl *>())
55560b57cec5SDimitry Andric         cast<VarTemplateSpecializationDecl>(Var)->setInstantiationOf(
55570b57cec5SDimitry Andric             Partial, &VarSpec->getTemplateInstantiationArgs());
55580b57cec5SDimitry Andric 
55590b57cec5SDimitry Andric       // Attach the initializer.
55600b57cec5SDimitry Andric       InstantiateVariableInitializer(Var, Def, TemplateArgs);
55610b57cec5SDimitry Andric     }
55620b57cec5SDimitry Andric   } else
55630b57cec5SDimitry Andric     // Complete the existing variable's definition with an appropriately
55640b57cec5SDimitry Andric     // substituted type and initializer.
55650b57cec5SDimitry Andric     Var = CompleteVarTemplateSpecializationDecl(VarSpec, Def, TemplateArgs);
55660b57cec5SDimitry Andric 
55670b57cec5SDimitry Andric   PreviousContext.pop();
55680b57cec5SDimitry Andric 
55690b57cec5SDimitry Andric   if (Var) {
55700b57cec5SDimitry Andric     PassToConsumerRAII.Var = Var;
55710b57cec5SDimitry Andric     Var->setTemplateSpecializationKind(OldVar->getTemplateSpecializationKind(),
55720b57cec5SDimitry Andric                                        OldVar->getPointOfInstantiation());
55730b57cec5SDimitry Andric   }
55740b57cec5SDimitry Andric 
55750b57cec5SDimitry Andric   // This variable may have local implicit instantiations that need to be
55760b57cec5SDimitry Andric   // instantiated within this scope.
55770b57cec5SDimitry Andric   LocalInstantiations.perform();
55780b57cec5SDimitry Andric   Local.Exit();
55790b57cec5SDimitry Andric   GlobalInstantiations.perform();
55800b57cec5SDimitry Andric }
55810b57cec5SDimitry Andric 
55820b57cec5SDimitry Andric void
55830b57cec5SDimitry Andric Sema::InstantiateMemInitializers(CXXConstructorDecl *New,
55840b57cec5SDimitry Andric                                  const CXXConstructorDecl *Tmpl,
55850b57cec5SDimitry Andric                            const MultiLevelTemplateArgumentList &TemplateArgs) {
55860b57cec5SDimitry Andric 
55870b57cec5SDimitry Andric   SmallVector<CXXCtorInitializer*, 4> NewInits;
55880b57cec5SDimitry Andric   bool AnyErrors = Tmpl->isInvalidDecl();
55890b57cec5SDimitry Andric 
55900b57cec5SDimitry Andric   // Instantiate all the initializers.
55910b57cec5SDimitry Andric   for (const auto *Init : Tmpl->inits()) {
55920b57cec5SDimitry Andric     // Only instantiate written initializers, let Sema re-construct implicit
55930b57cec5SDimitry Andric     // ones.
55940b57cec5SDimitry Andric     if (!Init->isWritten())
55950b57cec5SDimitry Andric       continue;
55960b57cec5SDimitry Andric 
55970b57cec5SDimitry Andric     SourceLocation EllipsisLoc;
55980b57cec5SDimitry Andric 
55990b57cec5SDimitry Andric     if (Init->isPackExpansion()) {
56000b57cec5SDimitry Andric       // This is a pack expansion. We should expand it now.
56010b57cec5SDimitry Andric       TypeLoc BaseTL = Init->getTypeSourceInfo()->getTypeLoc();
56020b57cec5SDimitry Andric       SmallVector<UnexpandedParameterPack, 4> Unexpanded;
56030b57cec5SDimitry Andric       collectUnexpandedParameterPacks(BaseTL, Unexpanded);
56040b57cec5SDimitry Andric       collectUnexpandedParameterPacks(Init->getInit(), Unexpanded);
56050b57cec5SDimitry Andric       bool ShouldExpand = false;
56060b57cec5SDimitry Andric       bool RetainExpansion = false;
56070b57cec5SDimitry Andric       Optional<unsigned> NumExpansions;
56080b57cec5SDimitry Andric       if (CheckParameterPacksForExpansion(Init->getEllipsisLoc(),
56090b57cec5SDimitry Andric                                           BaseTL.getSourceRange(),
56100b57cec5SDimitry Andric                                           Unexpanded,
56110b57cec5SDimitry Andric                                           TemplateArgs, ShouldExpand,
56120b57cec5SDimitry Andric                                           RetainExpansion,
56130b57cec5SDimitry Andric                                           NumExpansions)) {
56140b57cec5SDimitry Andric         AnyErrors = true;
56150b57cec5SDimitry Andric         New->setInvalidDecl();
56160b57cec5SDimitry Andric         continue;
56170b57cec5SDimitry Andric       }
56180b57cec5SDimitry Andric       assert(ShouldExpand && "Partial instantiation of base initializer?");
56190b57cec5SDimitry Andric 
56200b57cec5SDimitry Andric       // Loop over all of the arguments in the argument pack(s),
56210b57cec5SDimitry Andric       for (unsigned I = 0; I != *NumExpansions; ++I) {
56220b57cec5SDimitry Andric         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
56230b57cec5SDimitry Andric 
56240b57cec5SDimitry Andric         // Instantiate the initializer.
56250b57cec5SDimitry Andric         ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs,
56260b57cec5SDimitry Andric                                                /*CXXDirectInit=*/true);
56270b57cec5SDimitry Andric         if (TempInit.isInvalid()) {
56280b57cec5SDimitry Andric           AnyErrors = true;
56290b57cec5SDimitry Andric           break;
56300b57cec5SDimitry Andric         }
56310b57cec5SDimitry Andric 
56320b57cec5SDimitry Andric         // Instantiate the base type.
56330b57cec5SDimitry Andric         TypeSourceInfo *BaseTInfo = SubstType(Init->getTypeSourceInfo(),
56340b57cec5SDimitry Andric                                               TemplateArgs,
56350b57cec5SDimitry Andric                                               Init->getSourceLocation(),
56360b57cec5SDimitry Andric                                               New->getDeclName());
56370b57cec5SDimitry Andric         if (!BaseTInfo) {
56380b57cec5SDimitry Andric           AnyErrors = true;
56390b57cec5SDimitry Andric           break;
56400b57cec5SDimitry Andric         }
56410b57cec5SDimitry Andric 
56420b57cec5SDimitry Andric         // Build the initializer.
56430b57cec5SDimitry Andric         MemInitResult NewInit = BuildBaseInitializer(BaseTInfo->getType(),
56440b57cec5SDimitry Andric                                                      BaseTInfo, TempInit.get(),
56450b57cec5SDimitry Andric                                                      New->getParent(),
56460b57cec5SDimitry Andric                                                      SourceLocation());
56470b57cec5SDimitry Andric         if (NewInit.isInvalid()) {
56480b57cec5SDimitry Andric           AnyErrors = true;
56490b57cec5SDimitry Andric           break;
56500b57cec5SDimitry Andric         }
56510b57cec5SDimitry Andric 
56520b57cec5SDimitry Andric         NewInits.push_back(NewInit.get());
56530b57cec5SDimitry Andric       }
56540b57cec5SDimitry Andric 
56550b57cec5SDimitry Andric       continue;
56560b57cec5SDimitry Andric     }
56570b57cec5SDimitry Andric 
56580b57cec5SDimitry Andric     // Instantiate the initializer.
56590b57cec5SDimitry Andric     ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs,
56600b57cec5SDimitry Andric                                            /*CXXDirectInit=*/true);
56610b57cec5SDimitry Andric     if (TempInit.isInvalid()) {
56620b57cec5SDimitry Andric       AnyErrors = true;
56630b57cec5SDimitry Andric       continue;
56640b57cec5SDimitry Andric     }
56650b57cec5SDimitry Andric 
56660b57cec5SDimitry Andric     MemInitResult NewInit;
56670b57cec5SDimitry Andric     if (Init->isDelegatingInitializer() || Init->isBaseInitializer()) {
56680b57cec5SDimitry Andric       TypeSourceInfo *TInfo = SubstType(Init->getTypeSourceInfo(),
56690b57cec5SDimitry Andric                                         TemplateArgs,
56700b57cec5SDimitry Andric                                         Init->getSourceLocation(),
56710b57cec5SDimitry Andric                                         New->getDeclName());
56720b57cec5SDimitry Andric       if (!TInfo) {
56730b57cec5SDimitry Andric         AnyErrors = true;
56740b57cec5SDimitry Andric         New->setInvalidDecl();
56750b57cec5SDimitry Andric         continue;
56760b57cec5SDimitry Andric       }
56770b57cec5SDimitry Andric 
56780b57cec5SDimitry Andric       if (Init->isBaseInitializer())
56790b57cec5SDimitry Andric         NewInit = BuildBaseInitializer(TInfo->getType(), TInfo, TempInit.get(),
56800b57cec5SDimitry Andric                                        New->getParent(), EllipsisLoc);
56810b57cec5SDimitry Andric       else
56820b57cec5SDimitry Andric         NewInit = BuildDelegatingInitializer(TInfo, TempInit.get(),
56830b57cec5SDimitry Andric                                   cast<CXXRecordDecl>(CurContext->getParent()));
56840b57cec5SDimitry Andric     } else if (Init->isMemberInitializer()) {
56850b57cec5SDimitry Andric       FieldDecl *Member = cast_or_null<FieldDecl>(FindInstantiatedDecl(
56860b57cec5SDimitry Andric                                                      Init->getMemberLocation(),
56870b57cec5SDimitry Andric                                                      Init->getMember(),
56880b57cec5SDimitry Andric                                                      TemplateArgs));
56890b57cec5SDimitry Andric       if (!Member) {
56900b57cec5SDimitry Andric         AnyErrors = true;
56910b57cec5SDimitry Andric         New->setInvalidDecl();
56920b57cec5SDimitry Andric         continue;
56930b57cec5SDimitry Andric       }
56940b57cec5SDimitry Andric 
56950b57cec5SDimitry Andric       NewInit = BuildMemberInitializer(Member, TempInit.get(),
56960b57cec5SDimitry Andric                                        Init->getSourceLocation());
56970b57cec5SDimitry Andric     } else if (Init->isIndirectMemberInitializer()) {
56980b57cec5SDimitry Andric       IndirectFieldDecl *IndirectMember =
56990b57cec5SDimitry Andric          cast_or_null<IndirectFieldDecl>(FindInstantiatedDecl(
57000b57cec5SDimitry Andric                                  Init->getMemberLocation(),
57010b57cec5SDimitry Andric                                  Init->getIndirectMember(), TemplateArgs));
57020b57cec5SDimitry Andric 
57030b57cec5SDimitry Andric       if (!IndirectMember) {
57040b57cec5SDimitry Andric         AnyErrors = true;
57050b57cec5SDimitry Andric         New->setInvalidDecl();
57060b57cec5SDimitry Andric         continue;
57070b57cec5SDimitry Andric       }
57080b57cec5SDimitry Andric 
57090b57cec5SDimitry Andric       NewInit = BuildMemberInitializer(IndirectMember, TempInit.get(),
57100b57cec5SDimitry Andric                                        Init->getSourceLocation());
57110b57cec5SDimitry Andric     }
57120b57cec5SDimitry Andric 
57130b57cec5SDimitry Andric     if (NewInit.isInvalid()) {
57140b57cec5SDimitry Andric       AnyErrors = true;
57150b57cec5SDimitry Andric       New->setInvalidDecl();
57160b57cec5SDimitry Andric     } else {
57170b57cec5SDimitry Andric       NewInits.push_back(NewInit.get());
57180b57cec5SDimitry Andric     }
57190b57cec5SDimitry Andric   }
57200b57cec5SDimitry Andric 
57210b57cec5SDimitry Andric   // Assign all the initializers to the new constructor.
57220b57cec5SDimitry Andric   ActOnMemInitializers(New,
57230b57cec5SDimitry Andric                        /*FIXME: ColonLoc */
57240b57cec5SDimitry Andric                        SourceLocation(),
57250b57cec5SDimitry Andric                        NewInits,
57260b57cec5SDimitry Andric                        AnyErrors);
57270b57cec5SDimitry Andric }
57280b57cec5SDimitry Andric 
57290b57cec5SDimitry Andric // TODO: this could be templated if the various decl types used the
57300b57cec5SDimitry Andric // same method name.
57310b57cec5SDimitry Andric static bool isInstantiationOf(ClassTemplateDecl *Pattern,
57320b57cec5SDimitry Andric                               ClassTemplateDecl *Instance) {
57330b57cec5SDimitry Andric   Pattern = Pattern->getCanonicalDecl();
57340b57cec5SDimitry Andric 
57350b57cec5SDimitry Andric   do {
57360b57cec5SDimitry Andric     Instance = Instance->getCanonicalDecl();
57370b57cec5SDimitry Andric     if (Pattern == Instance) return true;
57380b57cec5SDimitry Andric     Instance = Instance->getInstantiatedFromMemberTemplate();
57390b57cec5SDimitry Andric   } while (Instance);
57400b57cec5SDimitry Andric 
57410b57cec5SDimitry Andric   return false;
57420b57cec5SDimitry Andric }
57430b57cec5SDimitry Andric 
57440b57cec5SDimitry Andric static bool isInstantiationOf(FunctionTemplateDecl *Pattern,
57450b57cec5SDimitry Andric                               FunctionTemplateDecl *Instance) {
57460b57cec5SDimitry Andric   Pattern = Pattern->getCanonicalDecl();
57470b57cec5SDimitry Andric 
57480b57cec5SDimitry Andric   do {
57490b57cec5SDimitry Andric     Instance = Instance->getCanonicalDecl();
57500b57cec5SDimitry Andric     if (Pattern == Instance) return true;
57510b57cec5SDimitry Andric     Instance = Instance->getInstantiatedFromMemberTemplate();
57520b57cec5SDimitry Andric   } while (Instance);
57530b57cec5SDimitry Andric 
57540b57cec5SDimitry Andric   return false;
57550b57cec5SDimitry Andric }
57560b57cec5SDimitry Andric 
57570b57cec5SDimitry Andric static bool
57580b57cec5SDimitry Andric isInstantiationOf(ClassTemplatePartialSpecializationDecl *Pattern,
57590b57cec5SDimitry Andric                   ClassTemplatePartialSpecializationDecl *Instance) {
57600b57cec5SDimitry Andric   Pattern
57610b57cec5SDimitry Andric     = cast<ClassTemplatePartialSpecializationDecl>(Pattern->getCanonicalDecl());
57620b57cec5SDimitry Andric   do {
57630b57cec5SDimitry Andric     Instance = cast<ClassTemplatePartialSpecializationDecl>(
57640b57cec5SDimitry Andric                                                 Instance->getCanonicalDecl());
57650b57cec5SDimitry Andric     if (Pattern == Instance)
57660b57cec5SDimitry Andric       return true;
57670b57cec5SDimitry Andric     Instance = Instance->getInstantiatedFromMember();
57680b57cec5SDimitry Andric   } while (Instance);
57690b57cec5SDimitry Andric 
57700b57cec5SDimitry Andric   return false;
57710b57cec5SDimitry Andric }
57720b57cec5SDimitry Andric 
57730b57cec5SDimitry Andric static bool isInstantiationOf(CXXRecordDecl *Pattern,
57740b57cec5SDimitry Andric                               CXXRecordDecl *Instance) {
57750b57cec5SDimitry Andric   Pattern = Pattern->getCanonicalDecl();
57760b57cec5SDimitry Andric 
57770b57cec5SDimitry Andric   do {
57780b57cec5SDimitry Andric     Instance = Instance->getCanonicalDecl();
57790b57cec5SDimitry Andric     if (Pattern == Instance) return true;
57800b57cec5SDimitry Andric     Instance = Instance->getInstantiatedFromMemberClass();
57810b57cec5SDimitry Andric   } while (Instance);
57820b57cec5SDimitry Andric 
57830b57cec5SDimitry Andric   return false;
57840b57cec5SDimitry Andric }
57850b57cec5SDimitry Andric 
57860b57cec5SDimitry Andric static bool isInstantiationOf(FunctionDecl *Pattern,
57870b57cec5SDimitry Andric                               FunctionDecl *Instance) {
57880b57cec5SDimitry Andric   Pattern = Pattern->getCanonicalDecl();
57890b57cec5SDimitry Andric 
57900b57cec5SDimitry Andric   do {
57910b57cec5SDimitry Andric     Instance = Instance->getCanonicalDecl();
57920b57cec5SDimitry Andric     if (Pattern == Instance) return true;
57930b57cec5SDimitry Andric     Instance = Instance->getInstantiatedFromMemberFunction();
57940b57cec5SDimitry Andric   } while (Instance);
57950b57cec5SDimitry Andric 
57960b57cec5SDimitry Andric   return false;
57970b57cec5SDimitry Andric }
57980b57cec5SDimitry Andric 
57990b57cec5SDimitry Andric static bool isInstantiationOf(EnumDecl *Pattern,
58000b57cec5SDimitry Andric                               EnumDecl *Instance) {
58010b57cec5SDimitry Andric   Pattern = Pattern->getCanonicalDecl();
58020b57cec5SDimitry Andric 
58030b57cec5SDimitry Andric   do {
58040b57cec5SDimitry Andric     Instance = Instance->getCanonicalDecl();
58050b57cec5SDimitry Andric     if (Pattern == Instance) return true;
58060b57cec5SDimitry Andric     Instance = Instance->getInstantiatedFromMemberEnum();
58070b57cec5SDimitry Andric   } while (Instance);
58080b57cec5SDimitry Andric 
58090b57cec5SDimitry Andric   return false;
58100b57cec5SDimitry Andric }
58110b57cec5SDimitry Andric 
58120b57cec5SDimitry Andric static bool isInstantiationOf(UsingShadowDecl *Pattern,
58130b57cec5SDimitry Andric                               UsingShadowDecl *Instance,
58140b57cec5SDimitry Andric                               ASTContext &C) {
58150b57cec5SDimitry Andric   return declaresSameEntity(C.getInstantiatedFromUsingShadowDecl(Instance),
58160b57cec5SDimitry Andric                             Pattern);
58170b57cec5SDimitry Andric }
58180b57cec5SDimitry Andric 
58190b57cec5SDimitry Andric static bool isInstantiationOf(UsingDecl *Pattern, UsingDecl *Instance,
58200b57cec5SDimitry Andric                               ASTContext &C) {
58210b57cec5SDimitry Andric   return declaresSameEntity(C.getInstantiatedFromUsingDecl(Instance), Pattern);
58220b57cec5SDimitry Andric }
58230b57cec5SDimitry Andric 
58240b57cec5SDimitry Andric template<typename T>
58250b57cec5SDimitry Andric static bool isInstantiationOfUnresolvedUsingDecl(T *Pattern, Decl *Other,
58260b57cec5SDimitry Andric                                                  ASTContext &Ctx) {
58270b57cec5SDimitry Andric   // An unresolved using declaration can instantiate to an unresolved using
58280b57cec5SDimitry Andric   // declaration, or to a using declaration or a using declaration pack.
58290b57cec5SDimitry Andric   //
58300b57cec5SDimitry Andric   // Multiple declarations can claim to be instantiated from an unresolved
58310b57cec5SDimitry Andric   // using declaration if it's a pack expansion. We want the UsingPackDecl
58320b57cec5SDimitry Andric   // in that case, not the individual UsingDecls within the pack.
58330b57cec5SDimitry Andric   bool OtherIsPackExpansion;
58340b57cec5SDimitry Andric   NamedDecl *OtherFrom;
58350b57cec5SDimitry Andric   if (auto *OtherUUD = dyn_cast<T>(Other)) {
58360b57cec5SDimitry Andric     OtherIsPackExpansion = OtherUUD->isPackExpansion();
58370b57cec5SDimitry Andric     OtherFrom = Ctx.getInstantiatedFromUsingDecl(OtherUUD);
58380b57cec5SDimitry Andric   } else if (auto *OtherUPD = dyn_cast<UsingPackDecl>(Other)) {
58390b57cec5SDimitry Andric     OtherIsPackExpansion = true;
58400b57cec5SDimitry Andric     OtherFrom = OtherUPD->getInstantiatedFromUsingDecl();
58410b57cec5SDimitry Andric   } else if (auto *OtherUD = dyn_cast<UsingDecl>(Other)) {
58420b57cec5SDimitry Andric     OtherIsPackExpansion = false;
58430b57cec5SDimitry Andric     OtherFrom = Ctx.getInstantiatedFromUsingDecl(OtherUD);
58440b57cec5SDimitry Andric   } else {
58450b57cec5SDimitry Andric     return false;
58460b57cec5SDimitry Andric   }
58470b57cec5SDimitry Andric   return Pattern->isPackExpansion() == OtherIsPackExpansion &&
58480b57cec5SDimitry Andric          declaresSameEntity(OtherFrom, Pattern);
58490b57cec5SDimitry Andric }
58500b57cec5SDimitry Andric 
58510b57cec5SDimitry Andric static bool isInstantiationOfStaticDataMember(VarDecl *Pattern,
58520b57cec5SDimitry Andric                                               VarDecl *Instance) {
58530b57cec5SDimitry Andric   assert(Instance->isStaticDataMember());
58540b57cec5SDimitry Andric 
58550b57cec5SDimitry Andric   Pattern = Pattern->getCanonicalDecl();
58560b57cec5SDimitry Andric 
58570b57cec5SDimitry Andric   do {
58580b57cec5SDimitry Andric     Instance = Instance->getCanonicalDecl();
58590b57cec5SDimitry Andric     if (Pattern == Instance) return true;
58600b57cec5SDimitry Andric     Instance = Instance->getInstantiatedFromStaticDataMember();
58610b57cec5SDimitry Andric   } while (Instance);
58620b57cec5SDimitry Andric 
58630b57cec5SDimitry Andric   return false;
58640b57cec5SDimitry Andric }
58650b57cec5SDimitry Andric 
58660b57cec5SDimitry Andric // Other is the prospective instantiation
58670b57cec5SDimitry Andric // D is the prospective pattern
58680b57cec5SDimitry Andric static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) {
58690b57cec5SDimitry Andric   if (auto *UUD = dyn_cast<UnresolvedUsingTypenameDecl>(D))
58700b57cec5SDimitry Andric     return isInstantiationOfUnresolvedUsingDecl(UUD, Other, Ctx);
58710b57cec5SDimitry Andric 
58720b57cec5SDimitry Andric   if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(D))
58730b57cec5SDimitry Andric     return isInstantiationOfUnresolvedUsingDecl(UUD, Other, Ctx);
58740b57cec5SDimitry Andric 
58750b57cec5SDimitry Andric   if (D->getKind() != Other->getKind())
58760b57cec5SDimitry Andric     return false;
58770b57cec5SDimitry Andric 
58780b57cec5SDimitry Andric   if (auto *Record = dyn_cast<CXXRecordDecl>(Other))
58790b57cec5SDimitry Andric     return isInstantiationOf(cast<CXXRecordDecl>(D), Record);
58800b57cec5SDimitry Andric 
58810b57cec5SDimitry Andric   if (auto *Function = dyn_cast<FunctionDecl>(Other))
58820b57cec5SDimitry Andric     return isInstantiationOf(cast<FunctionDecl>(D), Function);
58830b57cec5SDimitry Andric 
58840b57cec5SDimitry Andric   if (auto *Enum = dyn_cast<EnumDecl>(Other))
58850b57cec5SDimitry Andric     return isInstantiationOf(cast<EnumDecl>(D), Enum);
58860b57cec5SDimitry Andric 
58870b57cec5SDimitry Andric   if (auto *Var = dyn_cast<VarDecl>(Other))
58880b57cec5SDimitry Andric     if (Var->isStaticDataMember())
58890b57cec5SDimitry Andric       return isInstantiationOfStaticDataMember(cast<VarDecl>(D), Var);
58900b57cec5SDimitry Andric 
58910b57cec5SDimitry Andric   if (auto *Temp = dyn_cast<ClassTemplateDecl>(Other))
58920b57cec5SDimitry Andric     return isInstantiationOf(cast<ClassTemplateDecl>(D), Temp);
58930b57cec5SDimitry Andric 
58940b57cec5SDimitry Andric   if (auto *Temp = dyn_cast<FunctionTemplateDecl>(Other))
58950b57cec5SDimitry Andric     return isInstantiationOf(cast<FunctionTemplateDecl>(D), Temp);
58960b57cec5SDimitry Andric 
58970b57cec5SDimitry Andric   if (auto *PartialSpec =
58980b57cec5SDimitry Andric           dyn_cast<ClassTemplatePartialSpecializationDecl>(Other))
58990b57cec5SDimitry Andric     return isInstantiationOf(cast<ClassTemplatePartialSpecializationDecl>(D),
59000b57cec5SDimitry Andric                              PartialSpec);
59010b57cec5SDimitry Andric 
59020b57cec5SDimitry Andric   if (auto *Field = dyn_cast<FieldDecl>(Other)) {
59030b57cec5SDimitry Andric     if (!Field->getDeclName()) {
59040b57cec5SDimitry Andric       // This is an unnamed field.
59050b57cec5SDimitry Andric       return declaresSameEntity(Ctx.getInstantiatedFromUnnamedFieldDecl(Field),
59060b57cec5SDimitry Andric                                 cast<FieldDecl>(D));
59070b57cec5SDimitry Andric     }
59080b57cec5SDimitry Andric   }
59090b57cec5SDimitry Andric 
59100b57cec5SDimitry Andric   if (auto *Using = dyn_cast<UsingDecl>(Other))
59110b57cec5SDimitry Andric     return isInstantiationOf(cast<UsingDecl>(D), Using, Ctx);
59120b57cec5SDimitry Andric 
59130b57cec5SDimitry Andric   if (auto *Shadow = dyn_cast<UsingShadowDecl>(Other))
59140b57cec5SDimitry Andric     return isInstantiationOf(cast<UsingShadowDecl>(D), Shadow, Ctx);
59150b57cec5SDimitry Andric 
59160b57cec5SDimitry Andric   return D->getDeclName() &&
59170b57cec5SDimitry Andric          D->getDeclName() == cast<NamedDecl>(Other)->getDeclName();
59180b57cec5SDimitry Andric }
59190b57cec5SDimitry Andric 
59200b57cec5SDimitry Andric template<typename ForwardIterator>
59210b57cec5SDimitry Andric static NamedDecl *findInstantiationOf(ASTContext &Ctx,
59220b57cec5SDimitry Andric                                       NamedDecl *D,
59230b57cec5SDimitry Andric                                       ForwardIterator first,
59240b57cec5SDimitry Andric                                       ForwardIterator last) {
59250b57cec5SDimitry Andric   for (; first != last; ++first)
59260b57cec5SDimitry Andric     if (isInstantiationOf(Ctx, D, *first))
59270b57cec5SDimitry Andric       return cast<NamedDecl>(*first);
59280b57cec5SDimitry Andric 
59290b57cec5SDimitry Andric   return nullptr;
59300b57cec5SDimitry Andric }
59310b57cec5SDimitry Andric 
59320b57cec5SDimitry Andric /// Finds the instantiation of the given declaration context
59330b57cec5SDimitry Andric /// within the current instantiation.
59340b57cec5SDimitry Andric ///
59350b57cec5SDimitry Andric /// \returns NULL if there was an error
59360b57cec5SDimitry Andric DeclContext *Sema::FindInstantiatedContext(SourceLocation Loc, DeclContext* DC,
59370b57cec5SDimitry Andric                           const MultiLevelTemplateArgumentList &TemplateArgs) {
59380b57cec5SDimitry Andric   if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) {
59390b57cec5SDimitry Andric     Decl* ID = FindInstantiatedDecl(Loc, D, TemplateArgs, true);
59400b57cec5SDimitry Andric     return cast_or_null<DeclContext>(ID);
59410b57cec5SDimitry Andric   } else return DC;
59420b57cec5SDimitry Andric }
59430b57cec5SDimitry Andric 
59445ffd83dbSDimitry Andric /// Determine whether the given context is dependent on template parameters at
59455ffd83dbSDimitry Andric /// level \p Level or below.
59465ffd83dbSDimitry Andric ///
59475ffd83dbSDimitry Andric /// Sometimes we only substitute an inner set of template arguments and leave
59485ffd83dbSDimitry Andric /// the outer templates alone. In such cases, contexts dependent only on the
59495ffd83dbSDimitry Andric /// outer levels are not effectively dependent.
59505ffd83dbSDimitry Andric static bool isDependentContextAtLevel(DeclContext *DC, unsigned Level) {
59515ffd83dbSDimitry Andric   if (!DC->isDependentContext())
59525ffd83dbSDimitry Andric     return false;
59535ffd83dbSDimitry Andric   if (!Level)
59545ffd83dbSDimitry Andric     return true;
59555ffd83dbSDimitry Andric   return cast<Decl>(DC)->getTemplateDepth() > Level;
59565ffd83dbSDimitry Andric }
59575ffd83dbSDimitry Andric 
59580b57cec5SDimitry Andric /// Find the instantiation of the given declaration within the
59590b57cec5SDimitry Andric /// current instantiation.
59600b57cec5SDimitry Andric ///
59610b57cec5SDimitry Andric /// This routine is intended to be used when \p D is a declaration
59620b57cec5SDimitry Andric /// referenced from within a template, that needs to mapped into the
59630b57cec5SDimitry Andric /// corresponding declaration within an instantiation. For example,
59640b57cec5SDimitry Andric /// given:
59650b57cec5SDimitry Andric ///
59660b57cec5SDimitry Andric /// \code
59670b57cec5SDimitry Andric /// template<typename T>
59680b57cec5SDimitry Andric /// struct X {
59690b57cec5SDimitry Andric ///   enum Kind {
59700b57cec5SDimitry Andric ///     KnownValue = sizeof(T)
59710b57cec5SDimitry Andric ///   };
59720b57cec5SDimitry Andric ///
59730b57cec5SDimitry Andric ///   bool getKind() const { return KnownValue; }
59740b57cec5SDimitry Andric /// };
59750b57cec5SDimitry Andric ///
59760b57cec5SDimitry Andric /// template struct X<int>;
59770b57cec5SDimitry Andric /// \endcode
59780b57cec5SDimitry Andric ///
5979a7dea167SDimitry Andric /// In the instantiation of X<int>::getKind(), we need to map the \p
5980a7dea167SDimitry Andric /// EnumConstantDecl for \p KnownValue (which refers to
5981a7dea167SDimitry Andric /// X<T>::<Kind>::KnownValue) to its instantiation (X<int>::<Kind>::KnownValue).
5982a7dea167SDimitry Andric /// \p FindInstantiatedDecl performs this mapping from within the instantiation
5983a7dea167SDimitry Andric /// of X<int>.
59840b57cec5SDimitry Andric NamedDecl *Sema::FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
59850b57cec5SDimitry Andric                           const MultiLevelTemplateArgumentList &TemplateArgs,
59860b57cec5SDimitry Andric                           bool FindingInstantiatedContext) {
59870b57cec5SDimitry Andric   DeclContext *ParentDC = D->getDeclContext();
59885ffd83dbSDimitry Andric   // Determine whether our parent context depends on any of the tempalte
59895ffd83dbSDimitry Andric   // arguments we're currently substituting.
59905ffd83dbSDimitry Andric   bool ParentDependsOnArgs = isDependentContextAtLevel(
59915ffd83dbSDimitry Andric       ParentDC, TemplateArgs.getNumRetainedOuterLevels());
59920b57cec5SDimitry Andric   // FIXME: Parmeters of pointer to functions (y below) that are themselves
59930b57cec5SDimitry Andric   // parameters (p below) can have their ParentDC set to the translation-unit
59940b57cec5SDimitry Andric   // - thus we can not consistently check if the ParentDC of such a parameter
59950b57cec5SDimitry Andric   // is Dependent or/and a FunctionOrMethod.
59960b57cec5SDimitry Andric   // For e.g. this code, during Template argument deduction tries to
59970b57cec5SDimitry Andric   // find an instantiated decl for (T y) when the ParentDC for y is
59980b57cec5SDimitry Andric   // the translation unit.
59990b57cec5SDimitry Andric   //   e.g. template <class T> void Foo(auto (*p)(T y) -> decltype(y())) {}
60000b57cec5SDimitry Andric   //   float baz(float(*)()) { return 0.0; }
60010b57cec5SDimitry Andric   //   Foo(baz);
60020b57cec5SDimitry Andric   // The better fix here is perhaps to ensure that a ParmVarDecl, by the time
60030b57cec5SDimitry Andric   // it gets here, always has a FunctionOrMethod as its ParentDC??
60040b57cec5SDimitry Andric   // For now:
60050b57cec5SDimitry Andric   //  - as long as we have a ParmVarDecl whose parent is non-dependent and
60060b57cec5SDimitry Andric   //    whose type is not instantiation dependent, do nothing to the decl
60070b57cec5SDimitry Andric   //  - otherwise find its instantiated decl.
60085ffd83dbSDimitry Andric   if (isa<ParmVarDecl>(D) && !ParentDependsOnArgs &&
60090b57cec5SDimitry Andric       !cast<ParmVarDecl>(D)->getType()->isInstantiationDependentType())
60100b57cec5SDimitry Andric     return D;
60110b57cec5SDimitry Andric   if (isa<ParmVarDecl>(D) || isa<NonTypeTemplateParmDecl>(D) ||
60120b57cec5SDimitry Andric       isa<TemplateTypeParmDecl>(D) || isa<TemplateTemplateParmDecl>(D) ||
60135ffd83dbSDimitry Andric       (ParentDependsOnArgs && (ParentDC->isFunctionOrMethod() ||
60140b57cec5SDimitry Andric                                isa<OMPDeclareReductionDecl>(ParentDC) ||
60155ffd83dbSDimitry Andric                                isa<OMPDeclareMapperDecl>(ParentDC))) ||
60160b57cec5SDimitry Andric       (isa<CXXRecordDecl>(D) && cast<CXXRecordDecl>(D)->isLambda())) {
60170b57cec5SDimitry Andric     // D is a local of some kind. Look into the map of local
60180b57cec5SDimitry Andric     // declarations to their instantiations.
60190b57cec5SDimitry Andric     if (CurrentInstantiationScope) {
60200b57cec5SDimitry Andric       if (auto Found = CurrentInstantiationScope->findInstantiationOf(D)) {
60210b57cec5SDimitry Andric         if (Decl *FD = Found->dyn_cast<Decl *>())
60220b57cec5SDimitry Andric           return cast<NamedDecl>(FD);
60230b57cec5SDimitry Andric 
60240b57cec5SDimitry Andric         int PackIdx = ArgumentPackSubstitutionIndex;
60250b57cec5SDimitry Andric         assert(PackIdx != -1 &&
60260b57cec5SDimitry Andric                "found declaration pack but not pack expanding");
60270b57cec5SDimitry Andric         typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
60280b57cec5SDimitry Andric         return cast<NamedDecl>((*Found->get<DeclArgumentPack *>())[PackIdx]);
60290b57cec5SDimitry Andric       }
60300b57cec5SDimitry Andric     }
60310b57cec5SDimitry Andric 
60320b57cec5SDimitry Andric     // If we're performing a partial substitution during template argument
60330b57cec5SDimitry Andric     // deduction, we may not have values for template parameters yet. They
60340b57cec5SDimitry Andric     // just map to themselves.
60350b57cec5SDimitry Andric     if (isa<NonTypeTemplateParmDecl>(D) || isa<TemplateTypeParmDecl>(D) ||
60360b57cec5SDimitry Andric         isa<TemplateTemplateParmDecl>(D))
60370b57cec5SDimitry Andric       return D;
60380b57cec5SDimitry Andric 
60390b57cec5SDimitry Andric     if (D->isInvalidDecl())
60400b57cec5SDimitry Andric       return nullptr;
60410b57cec5SDimitry Andric 
60420b57cec5SDimitry Andric     // Normally this function only searches for already instantiated declaration
60430b57cec5SDimitry Andric     // however we have to make an exclusion for local types used before
60440b57cec5SDimitry Andric     // definition as in the code:
60450b57cec5SDimitry Andric     //
60460b57cec5SDimitry Andric     //   template<typename T> void f1() {
60470b57cec5SDimitry Andric     //     void g1(struct x1);
60480b57cec5SDimitry Andric     //     struct x1 {};
60490b57cec5SDimitry Andric     //   }
60500b57cec5SDimitry Andric     //
60510b57cec5SDimitry Andric     // In this case instantiation of the type of 'g1' requires definition of
60520b57cec5SDimitry Andric     // 'x1', which is defined later. Error recovery may produce an enum used
60530b57cec5SDimitry Andric     // before definition. In these cases we need to instantiate relevant
60540b57cec5SDimitry Andric     // declarations here.
60550b57cec5SDimitry Andric     bool NeedInstantiate = false;
60560b57cec5SDimitry Andric     if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
60570b57cec5SDimitry Andric       NeedInstantiate = RD->isLocalClass();
60585ffd83dbSDimitry Andric     else if (isa<TypedefNameDecl>(D) &&
60595ffd83dbSDimitry Andric              isa<CXXDeductionGuideDecl>(D->getDeclContext()))
60605ffd83dbSDimitry Andric       NeedInstantiate = true;
60610b57cec5SDimitry Andric     else
60620b57cec5SDimitry Andric       NeedInstantiate = isa<EnumDecl>(D);
60630b57cec5SDimitry Andric     if (NeedInstantiate) {
60640b57cec5SDimitry Andric       Decl *Inst = SubstDecl(D, CurContext, TemplateArgs);
60650b57cec5SDimitry Andric       CurrentInstantiationScope->InstantiatedLocal(D, Inst);
60660b57cec5SDimitry Andric       return cast<TypeDecl>(Inst);
60670b57cec5SDimitry Andric     }
60680b57cec5SDimitry Andric 
60690b57cec5SDimitry Andric     // If we didn't find the decl, then we must have a label decl that hasn't
60700b57cec5SDimitry Andric     // been found yet.  Lazily instantiate it and return it now.
60710b57cec5SDimitry Andric     assert(isa<LabelDecl>(D));
60720b57cec5SDimitry Andric 
60730b57cec5SDimitry Andric     Decl *Inst = SubstDecl(D, CurContext, TemplateArgs);
60740b57cec5SDimitry Andric     assert(Inst && "Failed to instantiate label??");
60750b57cec5SDimitry Andric 
60760b57cec5SDimitry Andric     CurrentInstantiationScope->InstantiatedLocal(D, Inst);
60770b57cec5SDimitry Andric     return cast<LabelDecl>(Inst);
60780b57cec5SDimitry Andric   }
60790b57cec5SDimitry Andric 
60800b57cec5SDimitry Andric   if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
60810b57cec5SDimitry Andric     if (!Record->isDependentContext())
60820b57cec5SDimitry Andric       return D;
60830b57cec5SDimitry Andric 
60840b57cec5SDimitry Andric     // Determine whether this record is the "templated" declaration describing
60850b57cec5SDimitry Andric     // a class template or class template partial specialization.
60860b57cec5SDimitry Andric     ClassTemplateDecl *ClassTemplate = Record->getDescribedClassTemplate();
60870b57cec5SDimitry Andric     if (ClassTemplate)
60880b57cec5SDimitry Andric       ClassTemplate = ClassTemplate->getCanonicalDecl();
60890b57cec5SDimitry Andric     else if (ClassTemplatePartialSpecializationDecl *PartialSpec
60900b57cec5SDimitry Andric                = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record))
60910b57cec5SDimitry Andric       ClassTemplate = PartialSpec->getSpecializedTemplate()->getCanonicalDecl();
60920b57cec5SDimitry Andric 
60930b57cec5SDimitry Andric     // Walk the current context to find either the record or an instantiation of
60940b57cec5SDimitry Andric     // it.
60950b57cec5SDimitry Andric     DeclContext *DC = CurContext;
60960b57cec5SDimitry Andric     while (!DC->isFileContext()) {
60970b57cec5SDimitry Andric       // If we're performing substitution while we're inside the template
60980b57cec5SDimitry Andric       // definition, we'll find our own context. We're done.
60990b57cec5SDimitry Andric       if (DC->Equals(Record))
61000b57cec5SDimitry Andric         return Record;
61010b57cec5SDimitry Andric 
61020b57cec5SDimitry Andric       if (CXXRecordDecl *InstRecord = dyn_cast<CXXRecordDecl>(DC)) {
61030b57cec5SDimitry Andric         // Check whether we're in the process of instantiating a class template
61040b57cec5SDimitry Andric         // specialization of the template we're mapping.
61050b57cec5SDimitry Andric         if (ClassTemplateSpecializationDecl *InstSpec
61060b57cec5SDimitry Andric                       = dyn_cast<ClassTemplateSpecializationDecl>(InstRecord)){
61070b57cec5SDimitry Andric           ClassTemplateDecl *SpecTemplate = InstSpec->getSpecializedTemplate();
61080b57cec5SDimitry Andric           if (ClassTemplate && isInstantiationOf(ClassTemplate, SpecTemplate))
61090b57cec5SDimitry Andric             return InstRecord;
61100b57cec5SDimitry Andric         }
61110b57cec5SDimitry Andric 
61120b57cec5SDimitry Andric         // Check whether we're in the process of instantiating a member class.
61130b57cec5SDimitry Andric         if (isInstantiationOf(Record, InstRecord))
61140b57cec5SDimitry Andric           return InstRecord;
61150b57cec5SDimitry Andric       }
61160b57cec5SDimitry Andric 
61170b57cec5SDimitry Andric       // Move to the outer template scope.
61180b57cec5SDimitry Andric       if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC)) {
61190b57cec5SDimitry Andric         if (FD->getFriendObjectKind() && FD->getDeclContext()->isFileContext()){
61200b57cec5SDimitry Andric           DC = FD->getLexicalDeclContext();
61210b57cec5SDimitry Andric           continue;
61220b57cec5SDimitry Andric         }
61230b57cec5SDimitry Andric         // An implicit deduction guide acts as if it's within the class template
61240b57cec5SDimitry Andric         // specialization described by its name and first N template params.
61250b57cec5SDimitry Andric         auto *Guide = dyn_cast<CXXDeductionGuideDecl>(FD);
61260b57cec5SDimitry Andric         if (Guide && Guide->isImplicit()) {
61270b57cec5SDimitry Andric           TemplateDecl *TD = Guide->getDeducedTemplate();
61280b57cec5SDimitry Andric           // Convert the arguments to an "as-written" list.
61290b57cec5SDimitry Andric           TemplateArgumentListInfo Args(Loc, Loc);
61300b57cec5SDimitry Andric           for (TemplateArgument Arg : TemplateArgs.getInnermost().take_front(
61310b57cec5SDimitry Andric                                         TD->getTemplateParameters()->size())) {
61320b57cec5SDimitry Andric             ArrayRef<TemplateArgument> Unpacked(Arg);
61330b57cec5SDimitry Andric             if (Arg.getKind() == TemplateArgument::Pack)
61340b57cec5SDimitry Andric               Unpacked = Arg.pack_elements();
61350b57cec5SDimitry Andric             for (TemplateArgument UnpackedArg : Unpacked)
61360b57cec5SDimitry Andric               Args.addArgument(
61370b57cec5SDimitry Andric                   getTrivialTemplateArgumentLoc(UnpackedArg, QualType(), Loc));
61380b57cec5SDimitry Andric           }
61390b57cec5SDimitry Andric           QualType T = CheckTemplateIdType(TemplateName(TD), Loc, Args);
61400b57cec5SDimitry Andric           if (T.isNull())
61410b57cec5SDimitry Andric             return nullptr;
61420b57cec5SDimitry Andric           auto *SubstRecord = T->getAsCXXRecordDecl();
61430b57cec5SDimitry Andric           assert(SubstRecord && "class template id not a class type?");
61440b57cec5SDimitry Andric           // Check that this template-id names the primary template and not a
61450b57cec5SDimitry Andric           // partial or explicit specialization. (In the latter cases, it's
61460b57cec5SDimitry Andric           // meaningless to attempt to find an instantiation of D within the
61470b57cec5SDimitry Andric           // specialization.)
61480b57cec5SDimitry Andric           // FIXME: The standard doesn't say what should happen here.
61490b57cec5SDimitry Andric           if (FindingInstantiatedContext &&
61500b57cec5SDimitry Andric               usesPartialOrExplicitSpecialization(
61510b57cec5SDimitry Andric                   Loc, cast<ClassTemplateSpecializationDecl>(SubstRecord))) {
61520b57cec5SDimitry Andric             Diag(Loc, diag::err_specialization_not_primary_template)
61530b57cec5SDimitry Andric               << T << (SubstRecord->getTemplateSpecializationKind() ==
61540b57cec5SDimitry Andric                            TSK_ExplicitSpecialization);
61550b57cec5SDimitry Andric             return nullptr;
61560b57cec5SDimitry Andric           }
61570b57cec5SDimitry Andric           DC = SubstRecord;
61580b57cec5SDimitry Andric           continue;
61590b57cec5SDimitry Andric         }
61600b57cec5SDimitry Andric       }
61610b57cec5SDimitry Andric 
61620b57cec5SDimitry Andric       DC = DC->getParent();
61630b57cec5SDimitry Andric     }
61640b57cec5SDimitry Andric 
61650b57cec5SDimitry Andric     // Fall through to deal with other dependent record types (e.g.,
61660b57cec5SDimitry Andric     // anonymous unions in class templates).
61670b57cec5SDimitry Andric   }
61680b57cec5SDimitry Andric 
61695ffd83dbSDimitry Andric   if (!ParentDependsOnArgs)
61700b57cec5SDimitry Andric     return D;
61710b57cec5SDimitry Andric 
61720b57cec5SDimitry Andric   ParentDC = FindInstantiatedContext(Loc, ParentDC, TemplateArgs);
61730b57cec5SDimitry Andric   if (!ParentDC)
61740b57cec5SDimitry Andric     return nullptr;
61750b57cec5SDimitry Andric 
61760b57cec5SDimitry Andric   if (ParentDC != D->getDeclContext()) {
61770b57cec5SDimitry Andric     // We performed some kind of instantiation in the parent context,
61780b57cec5SDimitry Andric     // so now we need to look into the instantiated parent context to
61790b57cec5SDimitry Andric     // find the instantiation of the declaration D.
61800b57cec5SDimitry Andric 
61810b57cec5SDimitry Andric     // If our context used to be dependent, we may need to instantiate
61820b57cec5SDimitry Andric     // it before performing lookup into that context.
61830b57cec5SDimitry Andric     bool IsBeingInstantiated = false;
61840b57cec5SDimitry Andric     if (CXXRecordDecl *Spec = dyn_cast<CXXRecordDecl>(ParentDC)) {
61850b57cec5SDimitry Andric       if (!Spec->isDependentContext()) {
61860b57cec5SDimitry Andric         QualType T = Context.getTypeDeclType(Spec);
61870b57cec5SDimitry Andric         const RecordType *Tag = T->getAs<RecordType>();
61880b57cec5SDimitry Andric         assert(Tag && "type of non-dependent record is not a RecordType");
61890b57cec5SDimitry Andric         if (Tag->isBeingDefined())
61900b57cec5SDimitry Andric           IsBeingInstantiated = true;
61910b57cec5SDimitry Andric         if (!Tag->isBeingDefined() &&
61920b57cec5SDimitry Andric             RequireCompleteType(Loc, T, diag::err_incomplete_type))
61930b57cec5SDimitry Andric           return nullptr;
61940b57cec5SDimitry Andric 
61950b57cec5SDimitry Andric         ParentDC = Tag->getDecl();
61960b57cec5SDimitry Andric       }
61970b57cec5SDimitry Andric     }
61980b57cec5SDimitry Andric 
61990b57cec5SDimitry Andric     NamedDecl *Result = nullptr;
62000b57cec5SDimitry Andric     // FIXME: If the name is a dependent name, this lookup won't necessarily
62010b57cec5SDimitry Andric     // find it. Does that ever matter?
62020b57cec5SDimitry Andric     if (auto Name = D->getDeclName()) {
62030b57cec5SDimitry Andric       DeclarationNameInfo NameInfo(Name, D->getLocation());
6204a7dea167SDimitry Andric       DeclarationNameInfo NewNameInfo =
6205a7dea167SDimitry Andric           SubstDeclarationNameInfo(NameInfo, TemplateArgs);
6206a7dea167SDimitry Andric       Name = NewNameInfo.getName();
62070b57cec5SDimitry Andric       if (!Name)
62080b57cec5SDimitry Andric         return nullptr;
62090b57cec5SDimitry Andric       DeclContext::lookup_result Found = ParentDC->lookup(Name);
6210a7dea167SDimitry Andric 
62110b57cec5SDimitry Andric       Result = findInstantiationOf(Context, D, Found.begin(), Found.end());
62120b57cec5SDimitry Andric     } else {
62130b57cec5SDimitry Andric       // Since we don't have a name for the entity we're looking for,
62140b57cec5SDimitry Andric       // our only option is to walk through all of the declarations to
62150b57cec5SDimitry Andric       // find that name. This will occur in a few cases:
62160b57cec5SDimitry Andric       //
62170b57cec5SDimitry Andric       //   - anonymous struct/union within a template
62180b57cec5SDimitry Andric       //   - unnamed class/struct/union/enum within a template
62190b57cec5SDimitry Andric       //
62200b57cec5SDimitry Andric       // FIXME: Find a better way to find these instantiations!
62210b57cec5SDimitry Andric       Result = findInstantiationOf(Context, D,
62220b57cec5SDimitry Andric                                    ParentDC->decls_begin(),
62230b57cec5SDimitry Andric                                    ParentDC->decls_end());
62240b57cec5SDimitry Andric     }
62250b57cec5SDimitry Andric 
62260b57cec5SDimitry Andric     if (!Result) {
62270b57cec5SDimitry Andric       if (isa<UsingShadowDecl>(D)) {
62280b57cec5SDimitry Andric         // UsingShadowDecls can instantiate to nothing because of using hiding.
6229e8d8bef9SDimitry Andric       } else if (hasUncompilableErrorOccurred()) {
62305ffd83dbSDimitry Andric         // We've already complained about some ill-formed code, so most likely
62315ffd83dbSDimitry Andric         // this declaration failed to instantiate. There's no point in
62325ffd83dbSDimitry Andric         // complaining further, since this is normal in invalid code.
62335ffd83dbSDimitry Andric         // FIXME: Use more fine-grained 'invalid' tracking for this.
62340b57cec5SDimitry Andric       } else if (IsBeingInstantiated) {
62350b57cec5SDimitry Andric         // The class in which this member exists is currently being
62360b57cec5SDimitry Andric         // instantiated, and we haven't gotten around to instantiating this
62370b57cec5SDimitry Andric         // member yet. This can happen when the code uses forward declarations
62380b57cec5SDimitry Andric         // of member classes, and introduces ordering dependencies via
62390b57cec5SDimitry Andric         // template instantiation.
62400b57cec5SDimitry Andric         Diag(Loc, diag::err_member_not_yet_instantiated)
62410b57cec5SDimitry Andric           << D->getDeclName()
62420b57cec5SDimitry Andric           << Context.getTypeDeclType(cast<CXXRecordDecl>(ParentDC));
62430b57cec5SDimitry Andric         Diag(D->getLocation(), diag::note_non_instantiated_member_here);
62440b57cec5SDimitry Andric       } else if (EnumConstantDecl *ED = dyn_cast<EnumConstantDecl>(D)) {
62450b57cec5SDimitry Andric         // This enumeration constant was found when the template was defined,
62460b57cec5SDimitry Andric         // but can't be found in the instantiation. This can happen if an
62470b57cec5SDimitry Andric         // unscoped enumeration member is explicitly specialized.
62480b57cec5SDimitry Andric         EnumDecl *Enum = cast<EnumDecl>(ED->getLexicalDeclContext());
62490b57cec5SDimitry Andric         EnumDecl *Spec = cast<EnumDecl>(FindInstantiatedDecl(Loc, Enum,
62500b57cec5SDimitry Andric                                                              TemplateArgs));
62510b57cec5SDimitry Andric         assert(Spec->getTemplateSpecializationKind() ==
62520b57cec5SDimitry Andric                  TSK_ExplicitSpecialization);
62530b57cec5SDimitry Andric         Diag(Loc, diag::err_enumerator_does_not_exist)
62540b57cec5SDimitry Andric           << D->getDeclName()
62550b57cec5SDimitry Andric           << Context.getTypeDeclType(cast<TypeDecl>(Spec->getDeclContext()));
62560b57cec5SDimitry Andric         Diag(Spec->getLocation(), diag::note_enum_specialized_here)
62570b57cec5SDimitry Andric           << Context.getTypeDeclType(Spec);
62580b57cec5SDimitry Andric       } else {
62590b57cec5SDimitry Andric         // We should have found something, but didn't.
62600b57cec5SDimitry Andric         llvm_unreachable("Unable to find instantiation of declaration!");
62610b57cec5SDimitry Andric       }
62620b57cec5SDimitry Andric     }
62630b57cec5SDimitry Andric 
62640b57cec5SDimitry Andric     D = Result;
62650b57cec5SDimitry Andric   }
62660b57cec5SDimitry Andric 
62670b57cec5SDimitry Andric   return D;
62680b57cec5SDimitry Andric }
62690b57cec5SDimitry Andric 
62700b57cec5SDimitry Andric /// Performs template instantiation for all implicit template
62710b57cec5SDimitry Andric /// instantiations we have seen until this point.
62720b57cec5SDimitry Andric void Sema::PerformPendingInstantiations(bool LocalOnly) {
62735ffd83dbSDimitry Andric   std::deque<PendingImplicitInstantiation> delayedPCHInstantiations;
62740b57cec5SDimitry Andric   while (!PendingLocalImplicitInstantiations.empty() ||
62750b57cec5SDimitry Andric          (!LocalOnly && !PendingInstantiations.empty())) {
62760b57cec5SDimitry Andric     PendingImplicitInstantiation Inst;
62770b57cec5SDimitry Andric 
62780b57cec5SDimitry Andric     if (PendingLocalImplicitInstantiations.empty()) {
62790b57cec5SDimitry Andric       Inst = PendingInstantiations.front();
62800b57cec5SDimitry Andric       PendingInstantiations.pop_front();
62810b57cec5SDimitry Andric     } else {
62820b57cec5SDimitry Andric       Inst = PendingLocalImplicitInstantiations.front();
62830b57cec5SDimitry Andric       PendingLocalImplicitInstantiations.pop_front();
62840b57cec5SDimitry Andric     }
62850b57cec5SDimitry Andric 
62860b57cec5SDimitry Andric     // Instantiate function definitions
62870b57cec5SDimitry Andric     if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) {
62880b57cec5SDimitry Andric       bool DefinitionRequired = Function->getTemplateSpecializationKind() ==
62890b57cec5SDimitry Andric                                 TSK_ExplicitInstantiationDefinition;
62900b57cec5SDimitry Andric       if (Function->isMultiVersion()) {
62910b57cec5SDimitry Andric         getASTContext().forEachMultiversionedFunctionVersion(
62920b57cec5SDimitry Andric             Function, [this, Inst, DefinitionRequired](FunctionDecl *CurFD) {
62930b57cec5SDimitry Andric               InstantiateFunctionDefinition(/*FIXME:*/ Inst.second, CurFD, true,
62940b57cec5SDimitry Andric                                             DefinitionRequired, true);
62950b57cec5SDimitry Andric               if (CurFD->isDefined())
62960b57cec5SDimitry Andric                 CurFD->setInstantiationIsPending(false);
62970b57cec5SDimitry Andric             });
62980b57cec5SDimitry Andric       } else {
62990b57cec5SDimitry Andric         InstantiateFunctionDefinition(/*FIXME:*/ Inst.second, Function, true,
63000b57cec5SDimitry Andric                                       DefinitionRequired, true);
63010b57cec5SDimitry Andric         if (Function->isDefined())
63020b57cec5SDimitry Andric           Function->setInstantiationIsPending(false);
63030b57cec5SDimitry Andric       }
63045ffd83dbSDimitry Andric       // Definition of a PCH-ed template declaration may be available only in the TU.
63055ffd83dbSDimitry Andric       if (!LocalOnly && LangOpts.PCHInstantiateTemplates &&
63065ffd83dbSDimitry Andric           TUKind == TU_Prefix && Function->instantiationIsPending())
63075ffd83dbSDimitry Andric         delayedPCHInstantiations.push_back(Inst);
63080b57cec5SDimitry Andric       continue;
63090b57cec5SDimitry Andric     }
63100b57cec5SDimitry Andric 
63110b57cec5SDimitry Andric     // Instantiate variable definitions
63120b57cec5SDimitry Andric     VarDecl *Var = cast<VarDecl>(Inst.first);
63130b57cec5SDimitry Andric 
63140b57cec5SDimitry Andric     assert((Var->isStaticDataMember() ||
63150b57cec5SDimitry Andric             isa<VarTemplateSpecializationDecl>(Var)) &&
63160b57cec5SDimitry Andric            "Not a static data member, nor a variable template"
63170b57cec5SDimitry Andric            " specialization?");
63180b57cec5SDimitry Andric 
63190b57cec5SDimitry Andric     // Don't try to instantiate declarations if the most recent redeclaration
63200b57cec5SDimitry Andric     // is invalid.
63210b57cec5SDimitry Andric     if (Var->getMostRecentDecl()->isInvalidDecl())
63220b57cec5SDimitry Andric       continue;
63230b57cec5SDimitry Andric 
63240b57cec5SDimitry Andric     // Check if the most recent declaration has changed the specialization kind
63250b57cec5SDimitry Andric     // and removed the need for implicit instantiation.
63260b57cec5SDimitry Andric     switch (Var->getMostRecentDecl()
63270b57cec5SDimitry Andric                 ->getTemplateSpecializationKindForInstantiation()) {
63280b57cec5SDimitry Andric     case TSK_Undeclared:
63290b57cec5SDimitry Andric       llvm_unreachable("Cannot instantitiate an undeclared specialization.");
63300b57cec5SDimitry Andric     case TSK_ExplicitInstantiationDeclaration:
63310b57cec5SDimitry Andric     case TSK_ExplicitSpecialization:
63320b57cec5SDimitry Andric       continue;  // No longer need to instantiate this type.
63330b57cec5SDimitry Andric     case TSK_ExplicitInstantiationDefinition:
63340b57cec5SDimitry Andric       // We only need an instantiation if the pending instantiation *is* the
63350b57cec5SDimitry Andric       // explicit instantiation.
63360b57cec5SDimitry Andric       if (Var != Var->getMostRecentDecl())
63370b57cec5SDimitry Andric         continue;
63380b57cec5SDimitry Andric       break;
63390b57cec5SDimitry Andric     case TSK_ImplicitInstantiation:
63400b57cec5SDimitry Andric       break;
63410b57cec5SDimitry Andric     }
63420b57cec5SDimitry Andric 
63430b57cec5SDimitry Andric     PrettyDeclStackTraceEntry CrashInfo(Context, Var, SourceLocation(),
63440b57cec5SDimitry Andric                                         "instantiating variable definition");
63450b57cec5SDimitry Andric     bool DefinitionRequired = Var->getTemplateSpecializationKind() ==
63460b57cec5SDimitry Andric                               TSK_ExplicitInstantiationDefinition;
63470b57cec5SDimitry Andric 
63480b57cec5SDimitry Andric     // Instantiate static data member definitions or variable template
63490b57cec5SDimitry Andric     // specializations.
63500b57cec5SDimitry Andric     InstantiateVariableDefinition(/*FIXME:*/ Inst.second, Var, true,
63510b57cec5SDimitry Andric                                   DefinitionRequired, true);
63520b57cec5SDimitry Andric   }
63535ffd83dbSDimitry Andric 
63545ffd83dbSDimitry Andric   if (!LocalOnly && LangOpts.PCHInstantiateTemplates)
63555ffd83dbSDimitry Andric     PendingInstantiations.swap(delayedPCHInstantiations);
63560b57cec5SDimitry Andric }
63570b57cec5SDimitry Andric 
63580b57cec5SDimitry Andric void Sema::PerformDependentDiagnostics(const DeclContext *Pattern,
63590b57cec5SDimitry Andric                        const MultiLevelTemplateArgumentList &TemplateArgs) {
63600b57cec5SDimitry Andric   for (auto DD : Pattern->ddiags()) {
63610b57cec5SDimitry Andric     switch (DD->getKind()) {
63620b57cec5SDimitry Andric     case DependentDiagnostic::Access:
63630b57cec5SDimitry Andric       HandleDependentAccessCheck(*DD, TemplateArgs);
63640b57cec5SDimitry Andric       break;
63650b57cec5SDimitry Andric     }
63660b57cec5SDimitry Andric   }
63670b57cec5SDimitry Andric }
6368