xref: /freebsd/contrib/llvm-project/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp (revision ffc5ee0f57d56459df93f4107b9835ae78a546b5)
1 //===--- SemaTemplateInstantiateDecl.cpp - C++ Template Decl Instantiation ===/
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //===----------------------------------------------------------------------===/
7 //
8 //  This file implements C++ template instantiation for declarations.
9 //
10 //===----------------------------------------------------------------------===/
11 
12 #include "TreeTransform.h"
13 #include "clang/AST/ASTConsumer.h"
14 #include "clang/AST/ASTContext.h"
15 #include "clang/AST/ASTMutationListener.h"
16 #include "clang/AST/DeclTemplate.h"
17 #include "clang/AST/DeclVisitor.h"
18 #include "clang/AST/DependentDiagnostic.h"
19 #include "clang/AST/Expr.h"
20 #include "clang/AST/ExprCXX.h"
21 #include "clang/AST/PrettyDeclStackTrace.h"
22 #include "clang/AST/TypeLoc.h"
23 #include "clang/Basic/SourceManager.h"
24 #include "clang/Basic/TargetInfo.h"
25 #include "clang/Sema/EnterExpressionEvaluationContext.h"
26 #include "clang/Sema/Initialization.h"
27 #include "clang/Sema/Lookup.h"
28 #include "clang/Sema/ScopeInfo.h"
29 #include "clang/Sema/SemaAMDGPU.h"
30 #include "clang/Sema/SemaCUDA.h"
31 #include "clang/Sema/SemaInternal.h"
32 #include "clang/Sema/SemaObjC.h"
33 #include "clang/Sema/SemaOpenMP.h"
34 #include "clang/Sema/SemaSwift.h"
35 #include "clang/Sema/Template.h"
36 #include "clang/Sema/TemplateInstCallback.h"
37 #include "llvm/Support/TimeProfiler.h"
38 #include <optional>
39 
40 using namespace clang;
41 
isDeclWithinFunction(const Decl * D)42 static bool isDeclWithinFunction(const Decl *D) {
43   const DeclContext *DC = D->getDeclContext();
44   if (DC->isFunctionOrMethod())
45     return true;
46 
47   if (DC->isRecord())
48     return cast<CXXRecordDecl>(DC)->isLocalClass();
49 
50   return false;
51 }
52 
53 template<typename DeclT>
SubstQualifier(Sema & SemaRef,const DeclT * OldDecl,DeclT * NewDecl,const MultiLevelTemplateArgumentList & TemplateArgs)54 static bool SubstQualifier(Sema &SemaRef, const DeclT *OldDecl, DeclT *NewDecl,
55                            const MultiLevelTemplateArgumentList &TemplateArgs) {
56   if (!OldDecl->getQualifierLoc())
57     return false;
58 
59   assert((NewDecl->getFriendObjectKind() ||
60           !OldDecl->getLexicalDeclContext()->isDependentContext()) &&
61          "non-friend with qualified name defined in dependent context");
62   Sema::ContextRAII SavedContext(
63       SemaRef,
64       const_cast<DeclContext *>(NewDecl->getFriendObjectKind()
65                                     ? NewDecl->getLexicalDeclContext()
66                                     : OldDecl->getLexicalDeclContext()));
67 
68   NestedNameSpecifierLoc NewQualifierLoc
69       = SemaRef.SubstNestedNameSpecifierLoc(OldDecl->getQualifierLoc(),
70                                             TemplateArgs);
71 
72   if (!NewQualifierLoc)
73     return true;
74 
75   NewDecl->setQualifierInfo(NewQualifierLoc);
76   return false;
77 }
78 
SubstQualifier(const DeclaratorDecl * OldDecl,DeclaratorDecl * NewDecl)79 bool TemplateDeclInstantiator::SubstQualifier(const DeclaratorDecl *OldDecl,
80                                               DeclaratorDecl *NewDecl) {
81   return ::SubstQualifier(SemaRef, OldDecl, NewDecl, TemplateArgs);
82 }
83 
SubstQualifier(const TagDecl * OldDecl,TagDecl * NewDecl)84 bool TemplateDeclInstantiator::SubstQualifier(const TagDecl *OldDecl,
85                                               TagDecl *NewDecl) {
86   return ::SubstQualifier(SemaRef, OldDecl, NewDecl, TemplateArgs);
87 }
88 
89 // Include attribute instantiation code.
90 #include "clang/Sema/AttrTemplateInstantiate.inc"
91 
instantiateDependentAlignedAttr(Sema & S,const MultiLevelTemplateArgumentList & TemplateArgs,const AlignedAttr * Aligned,Decl * New,bool IsPackExpansion)92 static void instantiateDependentAlignedAttr(
93     Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
94     const AlignedAttr *Aligned, Decl *New, bool IsPackExpansion) {
95   if (Aligned->isAlignmentExpr()) {
96     // The alignment expression is a constant expression.
97     EnterExpressionEvaluationContext Unevaluated(
98         S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
99     ExprResult Result = S.SubstExpr(Aligned->getAlignmentExpr(), TemplateArgs);
100     if (!Result.isInvalid())
101       S.AddAlignedAttr(New, *Aligned, Result.getAs<Expr>(), IsPackExpansion);
102   } else {
103     if (TypeSourceInfo *Result =
104             S.SubstType(Aligned->getAlignmentType(), TemplateArgs,
105                         Aligned->getLocation(), DeclarationName())) {
106       if (!S.CheckAlignasTypeArgument(Aligned->getSpelling(), Result,
107                                       Aligned->getLocation(),
108                                       Result->getTypeLoc().getSourceRange()))
109         S.AddAlignedAttr(New, *Aligned, Result, IsPackExpansion);
110     }
111   }
112 }
113 
instantiateDependentAlignedAttr(Sema & S,const MultiLevelTemplateArgumentList & TemplateArgs,const AlignedAttr * Aligned,Decl * New)114 static void instantiateDependentAlignedAttr(
115     Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
116     const AlignedAttr *Aligned, Decl *New) {
117   if (!Aligned->isPackExpansion()) {
118     instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, false);
119     return;
120   }
121 
122   SmallVector<UnexpandedParameterPack, 2> Unexpanded;
123   if (Aligned->isAlignmentExpr())
124     S.collectUnexpandedParameterPacks(Aligned->getAlignmentExpr(),
125                                       Unexpanded);
126   else
127     S.collectUnexpandedParameterPacks(Aligned->getAlignmentType()->getTypeLoc(),
128                                       Unexpanded);
129   assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
130 
131   // Determine whether we can expand this attribute pack yet.
132   bool Expand = true, RetainExpansion = false;
133   std::optional<unsigned> NumExpansions;
134   // FIXME: Use the actual location of the ellipsis.
135   SourceLocation EllipsisLoc = Aligned->getLocation();
136   if (S.CheckParameterPacksForExpansion(EllipsisLoc, Aligned->getRange(),
137                                         Unexpanded, TemplateArgs, Expand,
138                                         RetainExpansion, NumExpansions))
139     return;
140 
141   if (!Expand) {
142     Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(S, -1);
143     instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, true);
144   } else {
145     for (unsigned I = 0; I != *NumExpansions; ++I) {
146       Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(S, I);
147       instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, false);
148     }
149   }
150 }
151 
instantiateDependentAssumeAlignedAttr(Sema & S,const MultiLevelTemplateArgumentList & TemplateArgs,const AssumeAlignedAttr * Aligned,Decl * New)152 static void instantiateDependentAssumeAlignedAttr(
153     Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
154     const AssumeAlignedAttr *Aligned, Decl *New) {
155   // The alignment expression is a constant expression.
156   EnterExpressionEvaluationContext Unevaluated(
157       S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
158 
159   Expr *E, *OE = nullptr;
160   ExprResult Result = S.SubstExpr(Aligned->getAlignment(), TemplateArgs);
161   if (Result.isInvalid())
162     return;
163   E = Result.getAs<Expr>();
164 
165   if (Aligned->getOffset()) {
166     Result = S.SubstExpr(Aligned->getOffset(), TemplateArgs);
167     if (Result.isInvalid())
168       return;
169     OE = Result.getAs<Expr>();
170   }
171 
172   S.AddAssumeAlignedAttr(New, *Aligned, E, OE);
173 }
174 
instantiateDependentAlignValueAttr(Sema & S,const MultiLevelTemplateArgumentList & TemplateArgs,const AlignValueAttr * Aligned,Decl * New)175 static void instantiateDependentAlignValueAttr(
176     Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
177     const AlignValueAttr *Aligned, Decl *New) {
178   // The alignment expression is a constant expression.
179   EnterExpressionEvaluationContext Unevaluated(
180       S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
181   ExprResult Result = S.SubstExpr(Aligned->getAlignment(), TemplateArgs);
182   if (!Result.isInvalid())
183     S.AddAlignValueAttr(New, *Aligned, Result.getAs<Expr>());
184 }
185 
instantiateDependentAllocAlignAttr(Sema & S,const MultiLevelTemplateArgumentList & TemplateArgs,const AllocAlignAttr * Align,Decl * New)186 static void instantiateDependentAllocAlignAttr(
187     Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
188     const AllocAlignAttr *Align, Decl *New) {
189   Expr *Param = IntegerLiteral::Create(
190       S.getASTContext(),
191       llvm::APInt(64, Align->getParamIndex().getSourceIndex()),
192       S.getASTContext().UnsignedLongLongTy, Align->getLocation());
193   S.AddAllocAlignAttr(New, *Align, Param);
194 }
195 
instantiateDependentAnnotationAttr(Sema & S,const MultiLevelTemplateArgumentList & TemplateArgs,const AnnotateAttr * Attr,Decl * New)196 static void instantiateDependentAnnotationAttr(
197     Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
198     const AnnotateAttr *Attr, Decl *New) {
199   EnterExpressionEvaluationContext Unevaluated(
200       S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
201 
202   // If the attribute has delayed arguments it will have to instantiate those
203   // and handle them as new arguments for the attribute.
204   bool HasDelayedArgs = Attr->delayedArgs_size();
205 
206   ArrayRef<Expr *> ArgsToInstantiate =
207       HasDelayedArgs
208           ? ArrayRef<Expr *>{Attr->delayedArgs_begin(), Attr->delayedArgs_end()}
209           : ArrayRef<Expr *>{Attr->args_begin(), Attr->args_end()};
210 
211   SmallVector<Expr *, 4> Args;
212   if (S.SubstExprs(ArgsToInstantiate,
213                    /*IsCall=*/false, TemplateArgs, Args))
214     return;
215 
216   StringRef Str = Attr->getAnnotation();
217   if (HasDelayedArgs) {
218     if (Args.size() < 1) {
219       S.Diag(Attr->getLoc(), diag::err_attribute_too_few_arguments)
220           << Attr << 1;
221       return;
222     }
223 
224     if (!S.checkStringLiteralArgumentAttr(*Attr, Args[0], Str))
225       return;
226 
227     llvm::SmallVector<Expr *, 4> ActualArgs;
228     ActualArgs.insert(ActualArgs.begin(), Args.begin() + 1, Args.end());
229     std::swap(Args, ActualArgs);
230   }
231   S.AddAnnotationAttr(New, *Attr, Str, Args);
232 }
233 
instantiateDependentFunctionAttrCondition(Sema & S,const MultiLevelTemplateArgumentList & TemplateArgs,const Attr * A,Expr * OldCond,const Decl * Tmpl,FunctionDecl * New)234 static Expr *instantiateDependentFunctionAttrCondition(
235     Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
236     const Attr *A, Expr *OldCond, const Decl *Tmpl, FunctionDecl *New) {
237   Expr *Cond = nullptr;
238   {
239     Sema::ContextRAII SwitchContext(S, New);
240     EnterExpressionEvaluationContext Unevaluated(
241         S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
242     ExprResult Result = S.SubstExpr(OldCond, TemplateArgs);
243     if (Result.isInvalid())
244       return nullptr;
245     Cond = Result.getAs<Expr>();
246   }
247   if (!Cond->isTypeDependent()) {
248     ExprResult Converted = S.PerformContextuallyConvertToBool(Cond);
249     if (Converted.isInvalid())
250       return nullptr;
251     Cond = Converted.get();
252   }
253 
254   SmallVector<PartialDiagnosticAt, 8> Diags;
255   if (OldCond->isValueDependent() && !Cond->isValueDependent() &&
256       !Expr::isPotentialConstantExprUnevaluated(Cond, New, Diags)) {
257     S.Diag(A->getLocation(), diag::err_attr_cond_never_constant_expr) << A;
258     for (const auto &P : Diags)
259       S.Diag(P.first, P.second);
260     return nullptr;
261   }
262   return Cond;
263 }
264 
instantiateDependentEnableIfAttr(Sema & S,const MultiLevelTemplateArgumentList & TemplateArgs,const EnableIfAttr * EIA,const Decl * Tmpl,FunctionDecl * New)265 static void instantiateDependentEnableIfAttr(
266     Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
267     const EnableIfAttr *EIA, const Decl *Tmpl, FunctionDecl *New) {
268   Expr *Cond = instantiateDependentFunctionAttrCondition(
269       S, TemplateArgs, EIA, EIA->getCond(), Tmpl, New);
270 
271   if (Cond)
272     New->addAttr(new (S.getASTContext()) EnableIfAttr(S.getASTContext(), *EIA,
273                                                       Cond, EIA->getMessage()));
274 }
275 
instantiateDependentDiagnoseIfAttr(Sema & S,const MultiLevelTemplateArgumentList & TemplateArgs,const DiagnoseIfAttr * DIA,const Decl * Tmpl,FunctionDecl * New)276 static void instantiateDependentDiagnoseIfAttr(
277     Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
278     const DiagnoseIfAttr *DIA, const Decl *Tmpl, FunctionDecl *New) {
279   Expr *Cond = instantiateDependentFunctionAttrCondition(
280       S, TemplateArgs, DIA, DIA->getCond(), Tmpl, New);
281 
282   if (Cond)
283     New->addAttr(new (S.getASTContext()) DiagnoseIfAttr(
284         S.getASTContext(), *DIA, Cond, DIA->getMessage(),
285         DIA->getDiagnosticType(), DIA->getArgDependent(), New));
286 }
287 
288 // Constructs and adds to New a new instance of CUDALaunchBoundsAttr using
289 // template A as the base and arguments from TemplateArgs.
instantiateDependentCUDALaunchBoundsAttr(Sema & S,const MultiLevelTemplateArgumentList & TemplateArgs,const CUDALaunchBoundsAttr & Attr,Decl * New)290 static void instantiateDependentCUDALaunchBoundsAttr(
291     Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
292     const CUDALaunchBoundsAttr &Attr, Decl *New) {
293   // The alignment expression is a constant expression.
294   EnterExpressionEvaluationContext Unevaluated(
295       S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
296 
297   ExprResult Result = S.SubstExpr(Attr.getMaxThreads(), TemplateArgs);
298   if (Result.isInvalid())
299     return;
300   Expr *MaxThreads = Result.getAs<Expr>();
301 
302   Expr *MinBlocks = nullptr;
303   if (Attr.getMinBlocks()) {
304     Result = S.SubstExpr(Attr.getMinBlocks(), TemplateArgs);
305     if (Result.isInvalid())
306       return;
307     MinBlocks = Result.getAs<Expr>();
308   }
309 
310   Expr *MaxBlocks = nullptr;
311   if (Attr.getMaxBlocks()) {
312     Result = S.SubstExpr(Attr.getMaxBlocks(), TemplateArgs);
313     if (Result.isInvalid())
314       return;
315     MaxBlocks = Result.getAs<Expr>();
316   }
317 
318   S.AddLaunchBoundsAttr(New, Attr, MaxThreads, MinBlocks, MaxBlocks);
319 }
320 
321 static void
instantiateDependentModeAttr(Sema & S,const MultiLevelTemplateArgumentList & TemplateArgs,const ModeAttr & Attr,Decl * New)322 instantiateDependentModeAttr(Sema &S,
323                              const MultiLevelTemplateArgumentList &TemplateArgs,
324                              const ModeAttr &Attr, Decl *New) {
325   S.AddModeAttr(New, Attr, Attr.getMode(),
326                 /*InInstantiation=*/true);
327 }
328 
329 /// Instantiation of 'declare simd' attribute and its arguments.
instantiateOMPDeclareSimdDeclAttr(Sema & S,const MultiLevelTemplateArgumentList & TemplateArgs,const OMPDeclareSimdDeclAttr & Attr,Decl * New)330 static void instantiateOMPDeclareSimdDeclAttr(
331     Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
332     const OMPDeclareSimdDeclAttr &Attr, Decl *New) {
333   // Allow 'this' in clauses with varlists.
334   if (auto *FTD = dyn_cast<FunctionTemplateDecl>(New))
335     New = FTD->getTemplatedDecl();
336   auto *FD = cast<FunctionDecl>(New);
337   auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(FD->getDeclContext());
338   SmallVector<Expr *, 4> Uniforms, Aligneds, Alignments, Linears, Steps;
339   SmallVector<unsigned, 4> LinModifiers;
340 
341   auto SubstExpr = [&](Expr *E) -> ExprResult {
342     if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
343       if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
344         Sema::ContextRAII SavedContext(S, FD);
345         LocalInstantiationScope Local(S);
346         if (FD->getNumParams() > PVD->getFunctionScopeIndex())
347           Local.InstantiatedLocal(
348               PVD, FD->getParamDecl(PVD->getFunctionScopeIndex()));
349         return S.SubstExpr(E, TemplateArgs);
350       }
351     Sema::CXXThisScopeRAII ThisScope(S, ThisContext, Qualifiers(),
352                                      FD->isCXXInstanceMember());
353     return S.SubstExpr(E, TemplateArgs);
354   };
355 
356   // Substitute a single OpenMP clause, which is a potentially-evaluated
357   // full-expression.
358   auto Subst = [&](Expr *E) -> ExprResult {
359     EnterExpressionEvaluationContext Evaluated(
360         S, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
361     ExprResult Res = SubstExpr(E);
362     if (Res.isInvalid())
363       return Res;
364     return S.ActOnFinishFullExpr(Res.get(), false);
365   };
366 
367   ExprResult Simdlen;
368   if (auto *E = Attr.getSimdlen())
369     Simdlen = Subst(E);
370 
371   if (Attr.uniforms_size() > 0) {
372     for(auto *E : Attr.uniforms()) {
373       ExprResult Inst = Subst(E);
374       if (Inst.isInvalid())
375         continue;
376       Uniforms.push_back(Inst.get());
377     }
378   }
379 
380   auto AI = Attr.alignments_begin();
381   for (auto *E : Attr.aligneds()) {
382     ExprResult Inst = Subst(E);
383     if (Inst.isInvalid())
384       continue;
385     Aligneds.push_back(Inst.get());
386     Inst = ExprEmpty();
387     if (*AI)
388       Inst = S.SubstExpr(*AI, TemplateArgs);
389     Alignments.push_back(Inst.get());
390     ++AI;
391   }
392 
393   auto SI = Attr.steps_begin();
394   for (auto *E : Attr.linears()) {
395     ExprResult Inst = Subst(E);
396     if (Inst.isInvalid())
397       continue;
398     Linears.push_back(Inst.get());
399     Inst = ExprEmpty();
400     if (*SI)
401       Inst = S.SubstExpr(*SI, TemplateArgs);
402     Steps.push_back(Inst.get());
403     ++SI;
404   }
405   LinModifiers.append(Attr.modifiers_begin(), Attr.modifiers_end());
406   (void)S.OpenMP().ActOnOpenMPDeclareSimdDirective(
407       S.ConvertDeclToDeclGroup(New), Attr.getBranchState(), Simdlen.get(),
408       Uniforms, Aligneds, Alignments, Linears, LinModifiers, Steps,
409       Attr.getRange());
410 }
411 
412 /// Instantiation of 'declare variant' attribute and its arguments.
instantiateOMPDeclareVariantAttr(Sema & S,const MultiLevelTemplateArgumentList & TemplateArgs,const OMPDeclareVariantAttr & Attr,Decl * New)413 static void instantiateOMPDeclareVariantAttr(
414     Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
415     const OMPDeclareVariantAttr &Attr, Decl *New) {
416   // Allow 'this' in clauses with varlists.
417   if (auto *FTD = dyn_cast<FunctionTemplateDecl>(New))
418     New = FTD->getTemplatedDecl();
419   auto *FD = cast<FunctionDecl>(New);
420   auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(FD->getDeclContext());
421 
422   auto &&SubstExpr = [FD, ThisContext, &S, &TemplateArgs](Expr *E) {
423     if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
424       if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
425         Sema::ContextRAII SavedContext(S, FD);
426         LocalInstantiationScope Local(S);
427         if (FD->getNumParams() > PVD->getFunctionScopeIndex())
428           Local.InstantiatedLocal(
429               PVD, FD->getParamDecl(PVD->getFunctionScopeIndex()));
430         return S.SubstExpr(E, TemplateArgs);
431       }
432     Sema::CXXThisScopeRAII ThisScope(S, ThisContext, Qualifiers(),
433                                      FD->isCXXInstanceMember());
434     return S.SubstExpr(E, TemplateArgs);
435   };
436 
437   // Substitute a single OpenMP clause, which is a potentially-evaluated
438   // full-expression.
439   auto &&Subst = [&SubstExpr, &S](Expr *E) {
440     EnterExpressionEvaluationContext Evaluated(
441         S, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
442     ExprResult Res = SubstExpr(E);
443     if (Res.isInvalid())
444       return Res;
445     return S.ActOnFinishFullExpr(Res.get(), false);
446   };
447 
448   ExprResult VariantFuncRef;
449   if (Expr *E = Attr.getVariantFuncRef()) {
450     // Do not mark function as is used to prevent its emission if this is the
451     // only place where it is used.
452     EnterExpressionEvaluationContext Unevaluated(
453         S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
454     VariantFuncRef = Subst(E);
455   }
456 
457   // Copy the template version of the OMPTraitInfo and run substitute on all
458   // score and condition expressiosn.
459   OMPTraitInfo &TI = S.getASTContext().getNewOMPTraitInfo();
460   TI = *Attr.getTraitInfos();
461 
462   // Try to substitute template parameters in score and condition expressions.
463   auto SubstScoreOrConditionExpr = [&S, Subst](Expr *&E, bool) {
464     if (E) {
465       EnterExpressionEvaluationContext Unevaluated(
466           S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
467       ExprResult ER = Subst(E);
468       if (ER.isUsable())
469         E = ER.get();
470       else
471         return true;
472     }
473     return false;
474   };
475   if (TI.anyScoreOrCondition(SubstScoreOrConditionExpr))
476     return;
477 
478   Expr *E = VariantFuncRef.get();
479 
480   // Check function/variant ref for `omp declare variant` but not for `omp
481   // begin declare variant` (which use implicit attributes).
482   std::optional<std::pair<FunctionDecl *, Expr *>> DeclVarData =
483       S.OpenMP().checkOpenMPDeclareVariantFunction(
484           S.ConvertDeclToDeclGroup(New), E, TI, Attr.appendArgs_size(),
485           Attr.getRange());
486 
487   if (!DeclVarData)
488     return;
489 
490   E = DeclVarData->second;
491   FD = DeclVarData->first;
492 
493   if (auto *VariantDRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts())) {
494     if (auto *VariantFD = dyn_cast<FunctionDecl>(VariantDRE->getDecl())) {
495       if (auto *VariantFTD = VariantFD->getDescribedFunctionTemplate()) {
496         if (!VariantFTD->isThisDeclarationADefinition())
497           return;
498         Sema::TentativeAnalysisScope Trap(S);
499         const TemplateArgumentList *TAL = TemplateArgumentList::CreateCopy(
500             S.Context, TemplateArgs.getInnermost());
501 
502         auto *SubstFD = S.InstantiateFunctionDeclaration(VariantFTD, TAL,
503                                                          New->getLocation());
504         if (!SubstFD)
505           return;
506         QualType NewType = S.Context.mergeFunctionTypes(
507             SubstFD->getType(), FD->getType(),
508             /* OfBlockPointer */ false,
509             /* Unqualified */ false, /* AllowCXX */ true);
510         if (NewType.isNull())
511           return;
512         S.InstantiateFunctionDefinition(
513             New->getLocation(), SubstFD, /* Recursive */ true,
514             /* DefinitionRequired */ false, /* AtEndOfTU */ false);
515         SubstFD->setInstantiationIsPending(!SubstFD->isDefined());
516         E = DeclRefExpr::Create(S.Context, NestedNameSpecifierLoc(),
517                                 SourceLocation(), SubstFD,
518                                 /* RefersToEnclosingVariableOrCapture */ false,
519                                 /* NameLoc */ SubstFD->getLocation(),
520                                 SubstFD->getType(), ExprValueKind::VK_PRValue);
521       }
522     }
523   }
524 
525   SmallVector<Expr *, 8> NothingExprs;
526   SmallVector<Expr *, 8> NeedDevicePtrExprs;
527   SmallVector<OMPInteropInfo, 4> AppendArgs;
528 
529   for (Expr *E : Attr.adjustArgsNothing()) {
530     ExprResult ER = Subst(E);
531     if (ER.isInvalid())
532       continue;
533     NothingExprs.push_back(ER.get());
534   }
535   for (Expr *E : Attr.adjustArgsNeedDevicePtr()) {
536     ExprResult ER = Subst(E);
537     if (ER.isInvalid())
538       continue;
539     NeedDevicePtrExprs.push_back(ER.get());
540   }
541   for (OMPInteropInfo &II : Attr.appendArgs()) {
542     // When prefer_type is implemented for append_args handle them here too.
543     AppendArgs.emplace_back(II.IsTarget, II.IsTargetSync);
544   }
545 
546   S.OpenMP().ActOnOpenMPDeclareVariantDirective(
547       FD, E, TI, NothingExprs, NeedDevicePtrExprs, AppendArgs, SourceLocation(),
548       SourceLocation(), Attr.getRange());
549 }
550 
instantiateDependentAMDGPUFlatWorkGroupSizeAttr(Sema & S,const MultiLevelTemplateArgumentList & TemplateArgs,const AMDGPUFlatWorkGroupSizeAttr & Attr,Decl * New)551 static void instantiateDependentAMDGPUFlatWorkGroupSizeAttr(
552     Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
553     const AMDGPUFlatWorkGroupSizeAttr &Attr, Decl *New) {
554   // Both min and max expression are constant expressions.
555   EnterExpressionEvaluationContext Unevaluated(
556       S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
557 
558   ExprResult Result = S.SubstExpr(Attr.getMin(), TemplateArgs);
559   if (Result.isInvalid())
560     return;
561   Expr *MinExpr = Result.getAs<Expr>();
562 
563   Result = S.SubstExpr(Attr.getMax(), TemplateArgs);
564   if (Result.isInvalid())
565     return;
566   Expr *MaxExpr = Result.getAs<Expr>();
567 
568   S.AMDGPU().addAMDGPUFlatWorkGroupSizeAttr(New, Attr, MinExpr, MaxExpr);
569 }
570 
instantiateExplicitSpecifier(const MultiLevelTemplateArgumentList & TemplateArgs,ExplicitSpecifier ES)571 ExplicitSpecifier Sema::instantiateExplicitSpecifier(
572     const MultiLevelTemplateArgumentList &TemplateArgs, ExplicitSpecifier ES) {
573   if (!ES.getExpr())
574     return ES;
575   Expr *OldCond = ES.getExpr();
576   Expr *Cond = nullptr;
577   {
578     EnterExpressionEvaluationContext Unevaluated(
579         *this, Sema::ExpressionEvaluationContext::ConstantEvaluated);
580     ExprResult SubstResult = SubstExpr(OldCond, TemplateArgs);
581     if (SubstResult.isInvalid()) {
582       return ExplicitSpecifier::Invalid();
583     }
584     Cond = SubstResult.get();
585   }
586   ExplicitSpecifier Result(Cond, ES.getKind());
587   if (!Cond->isTypeDependent())
588     tryResolveExplicitSpecifier(Result);
589   return Result;
590 }
591 
instantiateDependentAMDGPUWavesPerEUAttr(Sema & S,const MultiLevelTemplateArgumentList & TemplateArgs,const AMDGPUWavesPerEUAttr & Attr,Decl * New)592 static void instantiateDependentAMDGPUWavesPerEUAttr(
593     Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
594     const AMDGPUWavesPerEUAttr &Attr, Decl *New) {
595   // Both min and max expression are constant expressions.
596   EnterExpressionEvaluationContext Unevaluated(
597       S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
598 
599   ExprResult Result = S.SubstExpr(Attr.getMin(), TemplateArgs);
600   if (Result.isInvalid())
601     return;
602   Expr *MinExpr = Result.getAs<Expr>();
603 
604   Expr *MaxExpr = nullptr;
605   if (auto Max = Attr.getMax()) {
606     Result = S.SubstExpr(Max, TemplateArgs);
607     if (Result.isInvalid())
608       return;
609     MaxExpr = Result.getAs<Expr>();
610   }
611 
612   S.AMDGPU().addAMDGPUWavesPerEUAttr(New, Attr, MinExpr, MaxExpr);
613 }
614 
instantiateDependentAMDGPUMaxNumWorkGroupsAttr(Sema & S,const MultiLevelTemplateArgumentList & TemplateArgs,const AMDGPUMaxNumWorkGroupsAttr & Attr,Decl * New)615 static void instantiateDependentAMDGPUMaxNumWorkGroupsAttr(
616     Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
617     const AMDGPUMaxNumWorkGroupsAttr &Attr, Decl *New) {
618   EnterExpressionEvaluationContext Unevaluated(
619       S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
620 
621   ExprResult ResultX = S.SubstExpr(Attr.getMaxNumWorkGroupsX(), TemplateArgs);
622   if (!ResultX.isUsable())
623     return;
624   ExprResult ResultY = S.SubstExpr(Attr.getMaxNumWorkGroupsY(), TemplateArgs);
625   if (!ResultY.isUsable())
626     return;
627   ExprResult ResultZ = S.SubstExpr(Attr.getMaxNumWorkGroupsZ(), TemplateArgs);
628   if (!ResultZ.isUsable())
629     return;
630 
631   Expr *XExpr = ResultX.getAs<Expr>();
632   Expr *YExpr = ResultY.getAs<Expr>();
633   Expr *ZExpr = ResultZ.getAs<Expr>();
634 
635   S.AMDGPU().addAMDGPUMaxNumWorkGroupsAttr(New, Attr, XExpr, YExpr, ZExpr);
636 }
637 
638 // This doesn't take any template parameters, but we have a custom action that
639 // needs to happen when the kernel itself is instantiated. We need to run the
640 // ItaniumMangler to mark the names required to name this kernel.
instantiateDependentSYCLKernelAttr(Sema & S,const MultiLevelTemplateArgumentList & TemplateArgs,const SYCLKernelAttr & Attr,Decl * New)641 static void instantiateDependentSYCLKernelAttr(
642     Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
643     const SYCLKernelAttr &Attr, Decl *New) {
644   New->addAttr(Attr.clone(S.getASTContext()));
645 }
646 
647 /// Determine whether the attribute A might be relevant to the declaration D.
648 /// If not, we can skip instantiating it. The attribute may or may not have
649 /// been instantiated yet.
isRelevantAttr(Sema & S,const Decl * D,const Attr * A)650 static bool isRelevantAttr(Sema &S, const Decl *D, const Attr *A) {
651   // 'preferred_name' is only relevant to the matching specialization of the
652   // template.
653   if (const auto *PNA = dyn_cast<PreferredNameAttr>(A)) {
654     QualType T = PNA->getTypedefType();
655     const auto *RD = cast<CXXRecordDecl>(D);
656     if (!T->isDependentType() && !RD->isDependentContext() &&
657         !declaresSameEntity(T->getAsCXXRecordDecl(), RD))
658       return false;
659     for (const auto *ExistingPNA : D->specific_attrs<PreferredNameAttr>())
660       if (S.Context.hasSameType(ExistingPNA->getTypedefType(),
661                                 PNA->getTypedefType()))
662         return false;
663     return true;
664   }
665 
666   if (const auto *BA = dyn_cast<BuiltinAttr>(A)) {
667     const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
668     switch (BA->getID()) {
669     case Builtin::BIforward:
670       // Do not treat 'std::forward' as a builtin if it takes an rvalue reference
671       // type and returns an lvalue reference type. The library implementation
672       // will produce an error in this case; don't get in its way.
673       if (FD && FD->getNumParams() >= 1 &&
674           FD->getParamDecl(0)->getType()->isRValueReferenceType() &&
675           FD->getReturnType()->isLValueReferenceType()) {
676         return false;
677       }
678       [[fallthrough]];
679     case Builtin::BImove:
680     case Builtin::BImove_if_noexcept:
681       // HACK: Super-old versions of libc++ (3.1 and earlier) provide
682       // std::forward and std::move overloads that sometimes return by value
683       // instead of by reference when building in C++98 mode. Don't treat such
684       // cases as builtins.
685       if (FD && !FD->getReturnType()->isReferenceType())
686         return false;
687       break;
688     }
689   }
690 
691   return true;
692 }
693 
instantiateDependentHLSLParamModifierAttr(Sema & S,const MultiLevelTemplateArgumentList & TemplateArgs,const HLSLParamModifierAttr * Attr,Decl * New)694 static void instantiateDependentHLSLParamModifierAttr(
695     Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
696     const HLSLParamModifierAttr *Attr, Decl *New) {
697   ParmVarDecl *P = cast<ParmVarDecl>(New);
698   P->addAttr(Attr->clone(S.getASTContext()));
699   P->setType(S.getASTContext().getLValueReferenceType(P->getType()));
700 }
701 
InstantiateAttrsForDecl(const MultiLevelTemplateArgumentList & TemplateArgs,const Decl * Tmpl,Decl * New,LateInstantiatedAttrVec * LateAttrs,LocalInstantiationScope * OuterMostScope)702 void Sema::InstantiateAttrsForDecl(
703     const MultiLevelTemplateArgumentList &TemplateArgs, const Decl *Tmpl,
704     Decl *New, LateInstantiatedAttrVec *LateAttrs,
705     LocalInstantiationScope *OuterMostScope) {
706   if (NamedDecl *ND = dyn_cast<NamedDecl>(New)) {
707     // FIXME: This function is called multiple times for the same template
708     // specialization. We should only instantiate attributes that were added
709     // since the previous instantiation.
710     for (const auto *TmplAttr : Tmpl->attrs()) {
711       if (!isRelevantAttr(*this, New, TmplAttr))
712         continue;
713 
714       // FIXME: If any of the special case versions from InstantiateAttrs become
715       // applicable to template declaration, we'll need to add them here.
716       CXXThisScopeRAII ThisScope(
717           *this, dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext()),
718           Qualifiers(), ND->isCXXInstanceMember());
719 
720       Attr *NewAttr = sema::instantiateTemplateAttributeForDecl(
721           TmplAttr, Context, *this, TemplateArgs);
722       if (NewAttr && isRelevantAttr(*this, New, NewAttr))
723         New->addAttr(NewAttr);
724     }
725   }
726 }
727 
728 static Sema::RetainOwnershipKind
attrToRetainOwnershipKind(const Attr * A)729 attrToRetainOwnershipKind(const Attr *A) {
730   switch (A->getKind()) {
731   case clang::attr::CFConsumed:
732     return Sema::RetainOwnershipKind::CF;
733   case clang::attr::OSConsumed:
734     return Sema::RetainOwnershipKind::OS;
735   case clang::attr::NSConsumed:
736     return Sema::RetainOwnershipKind::NS;
737   default:
738     llvm_unreachable("Wrong argument supplied");
739   }
740 }
741 
InstantiateAttrs(const MultiLevelTemplateArgumentList & TemplateArgs,const Decl * Tmpl,Decl * New,LateInstantiatedAttrVec * LateAttrs,LocalInstantiationScope * OuterMostScope)742 void Sema::InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs,
743                             const Decl *Tmpl, Decl *New,
744                             LateInstantiatedAttrVec *LateAttrs,
745                             LocalInstantiationScope *OuterMostScope) {
746   for (const auto *TmplAttr : Tmpl->attrs()) {
747     if (!isRelevantAttr(*this, New, TmplAttr))
748       continue;
749 
750     // FIXME: This should be generalized to more than just the AlignedAttr.
751     const AlignedAttr *Aligned = dyn_cast<AlignedAttr>(TmplAttr);
752     if (Aligned && Aligned->isAlignmentDependent()) {
753       instantiateDependentAlignedAttr(*this, TemplateArgs, Aligned, New);
754       continue;
755     }
756 
757     if (const auto *AssumeAligned = dyn_cast<AssumeAlignedAttr>(TmplAttr)) {
758       instantiateDependentAssumeAlignedAttr(*this, TemplateArgs, AssumeAligned, New);
759       continue;
760     }
761 
762     if (const auto *AlignValue = dyn_cast<AlignValueAttr>(TmplAttr)) {
763       instantiateDependentAlignValueAttr(*this, TemplateArgs, AlignValue, New);
764       continue;
765     }
766 
767     if (const auto *AllocAlign = dyn_cast<AllocAlignAttr>(TmplAttr)) {
768       instantiateDependentAllocAlignAttr(*this, TemplateArgs, AllocAlign, New);
769       continue;
770     }
771 
772     if (const auto *Annotate = dyn_cast<AnnotateAttr>(TmplAttr)) {
773       instantiateDependentAnnotationAttr(*this, TemplateArgs, Annotate, New);
774       continue;
775     }
776 
777     if (const auto *EnableIf = dyn_cast<EnableIfAttr>(TmplAttr)) {
778       instantiateDependentEnableIfAttr(*this, TemplateArgs, EnableIf, Tmpl,
779                                        cast<FunctionDecl>(New));
780       continue;
781     }
782 
783     if (const auto *DiagnoseIf = dyn_cast<DiagnoseIfAttr>(TmplAttr)) {
784       instantiateDependentDiagnoseIfAttr(*this, TemplateArgs, DiagnoseIf, Tmpl,
785                                          cast<FunctionDecl>(New));
786       continue;
787     }
788 
789     if (const auto *CUDALaunchBounds =
790             dyn_cast<CUDALaunchBoundsAttr>(TmplAttr)) {
791       instantiateDependentCUDALaunchBoundsAttr(*this, TemplateArgs,
792                                                *CUDALaunchBounds, New);
793       continue;
794     }
795 
796     if (const auto *Mode = dyn_cast<ModeAttr>(TmplAttr)) {
797       instantiateDependentModeAttr(*this, TemplateArgs, *Mode, New);
798       continue;
799     }
800 
801     if (const auto *OMPAttr = dyn_cast<OMPDeclareSimdDeclAttr>(TmplAttr)) {
802       instantiateOMPDeclareSimdDeclAttr(*this, TemplateArgs, *OMPAttr, New);
803       continue;
804     }
805 
806     if (const auto *OMPAttr = dyn_cast<OMPDeclareVariantAttr>(TmplAttr)) {
807       instantiateOMPDeclareVariantAttr(*this, TemplateArgs, *OMPAttr, New);
808       continue;
809     }
810 
811     if (const auto *AMDGPUFlatWorkGroupSize =
812             dyn_cast<AMDGPUFlatWorkGroupSizeAttr>(TmplAttr)) {
813       instantiateDependentAMDGPUFlatWorkGroupSizeAttr(
814           *this, TemplateArgs, *AMDGPUFlatWorkGroupSize, New);
815     }
816 
817     if (const auto *AMDGPUFlatWorkGroupSize =
818             dyn_cast<AMDGPUWavesPerEUAttr>(TmplAttr)) {
819       instantiateDependentAMDGPUWavesPerEUAttr(*this, TemplateArgs,
820                                                *AMDGPUFlatWorkGroupSize, New);
821     }
822 
823     if (const auto *AMDGPUMaxNumWorkGroups =
824             dyn_cast<AMDGPUMaxNumWorkGroupsAttr>(TmplAttr)) {
825       instantiateDependentAMDGPUMaxNumWorkGroupsAttr(
826           *this, TemplateArgs, *AMDGPUMaxNumWorkGroups, New);
827     }
828 
829     if (const auto *ParamAttr = dyn_cast<HLSLParamModifierAttr>(TmplAttr)) {
830       instantiateDependentHLSLParamModifierAttr(*this, TemplateArgs, ParamAttr,
831                                                 New);
832       continue;
833     }
834 
835     // Existing DLL attribute on the instantiation takes precedence.
836     if (TmplAttr->getKind() == attr::DLLExport ||
837         TmplAttr->getKind() == attr::DLLImport) {
838       if (New->hasAttr<DLLExportAttr>() || New->hasAttr<DLLImportAttr>()) {
839         continue;
840       }
841     }
842 
843     if (const auto *ABIAttr = dyn_cast<ParameterABIAttr>(TmplAttr)) {
844       Swift().AddParameterABIAttr(New, *ABIAttr, ABIAttr->getABI());
845       continue;
846     }
847 
848     if (isa<NSConsumedAttr>(TmplAttr) || isa<OSConsumedAttr>(TmplAttr) ||
849         isa<CFConsumedAttr>(TmplAttr)) {
850       ObjC().AddXConsumedAttr(New, *TmplAttr,
851                               attrToRetainOwnershipKind(TmplAttr),
852                               /*template instantiation=*/true);
853       continue;
854     }
855 
856     if (auto *A = dyn_cast<PointerAttr>(TmplAttr)) {
857       if (!New->hasAttr<PointerAttr>())
858         New->addAttr(A->clone(Context));
859       continue;
860     }
861 
862     if (auto *A = dyn_cast<OwnerAttr>(TmplAttr)) {
863       if (!New->hasAttr<OwnerAttr>())
864         New->addAttr(A->clone(Context));
865       continue;
866     }
867 
868     if (auto *A = dyn_cast<SYCLKernelAttr>(TmplAttr)) {
869       instantiateDependentSYCLKernelAttr(*this, TemplateArgs, *A, New);
870       continue;
871     }
872 
873     assert(!TmplAttr->isPackExpansion());
874     if (TmplAttr->isLateParsed() && LateAttrs) {
875       // Late parsed attributes must be instantiated and attached after the
876       // enclosing class has been instantiated.  See Sema::InstantiateClass.
877       LocalInstantiationScope *Saved = nullptr;
878       if (CurrentInstantiationScope)
879         Saved = CurrentInstantiationScope->cloneScopes(OuterMostScope);
880       LateAttrs->push_back(LateInstantiatedAttribute(TmplAttr, Saved, New));
881     } else {
882       // Allow 'this' within late-parsed attributes.
883       auto *ND = cast<NamedDecl>(New);
884       auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext());
885       CXXThisScopeRAII ThisScope(*this, ThisContext, Qualifiers(),
886                                  ND->isCXXInstanceMember());
887 
888       Attr *NewAttr = sema::instantiateTemplateAttribute(TmplAttr, Context,
889                                                          *this, TemplateArgs);
890       if (NewAttr && isRelevantAttr(*this, New, TmplAttr))
891         New->addAttr(NewAttr);
892     }
893   }
894 }
895 
updateAttrsForLateParsedTemplate(const Decl * Pattern,Decl * Inst)896 void Sema::updateAttrsForLateParsedTemplate(const Decl *Pattern, Decl *Inst) {
897   for (const auto *Attr : Pattern->attrs()) {
898     if (auto *A = dyn_cast<StrictFPAttr>(Attr)) {
899       if (!Inst->hasAttr<StrictFPAttr>())
900         Inst->addAttr(A->clone(getASTContext()));
901       continue;
902     }
903   }
904 }
905 
InstantiateDefaultCtorDefaultArgs(CXXConstructorDecl * Ctor)906 void Sema::InstantiateDefaultCtorDefaultArgs(CXXConstructorDecl *Ctor) {
907   assert(Context.getTargetInfo().getCXXABI().isMicrosoft() &&
908          Ctor->isDefaultConstructor());
909   unsigned NumParams = Ctor->getNumParams();
910   if (NumParams == 0)
911     return;
912   DLLExportAttr *Attr = Ctor->getAttr<DLLExportAttr>();
913   if (!Attr)
914     return;
915   for (unsigned I = 0; I != NumParams; ++I) {
916     (void)CheckCXXDefaultArgExpr(Attr->getLocation(), Ctor,
917                                    Ctor->getParamDecl(I));
918     CleanupVarDeclMarking();
919   }
920 }
921 
922 /// Get the previous declaration of a declaration for the purposes of template
923 /// instantiation. If this finds a previous declaration, then the previous
924 /// declaration of the instantiation of D should be an instantiation of the
925 /// result of this function.
926 template<typename DeclT>
getPreviousDeclForInstantiation(DeclT * D)927 static DeclT *getPreviousDeclForInstantiation(DeclT *D) {
928   DeclT *Result = D->getPreviousDecl();
929 
930   // If the declaration is within a class, and the previous declaration was
931   // merged from a different definition of that class, then we don't have a
932   // previous declaration for the purpose of template instantiation.
933   if (Result && isa<CXXRecordDecl>(D->getDeclContext()) &&
934       D->getLexicalDeclContext() != Result->getLexicalDeclContext())
935     return nullptr;
936 
937   return Result;
938 }
939 
940 Decl *
VisitTranslationUnitDecl(TranslationUnitDecl * D)941 TemplateDeclInstantiator::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
942   llvm_unreachable("Translation units cannot be instantiated");
943 }
944 
VisitHLSLBufferDecl(HLSLBufferDecl * Decl)945 Decl *TemplateDeclInstantiator::VisitHLSLBufferDecl(HLSLBufferDecl *Decl) {
946   llvm_unreachable("HLSL buffer declarations cannot be instantiated");
947 }
948 
949 Decl *
VisitPragmaCommentDecl(PragmaCommentDecl * D)950 TemplateDeclInstantiator::VisitPragmaCommentDecl(PragmaCommentDecl *D) {
951   llvm_unreachable("pragma comment cannot be instantiated");
952 }
953 
VisitPragmaDetectMismatchDecl(PragmaDetectMismatchDecl * D)954 Decl *TemplateDeclInstantiator::VisitPragmaDetectMismatchDecl(
955     PragmaDetectMismatchDecl *D) {
956   llvm_unreachable("pragma comment cannot be instantiated");
957 }
958 
959 Decl *
VisitExternCContextDecl(ExternCContextDecl * D)960 TemplateDeclInstantiator::VisitExternCContextDecl(ExternCContextDecl *D) {
961   llvm_unreachable("extern \"C\" context cannot be instantiated");
962 }
963 
VisitMSGuidDecl(MSGuidDecl * D)964 Decl *TemplateDeclInstantiator::VisitMSGuidDecl(MSGuidDecl *D) {
965   llvm_unreachable("GUID declaration cannot be instantiated");
966 }
967 
VisitUnnamedGlobalConstantDecl(UnnamedGlobalConstantDecl * D)968 Decl *TemplateDeclInstantiator::VisitUnnamedGlobalConstantDecl(
969     UnnamedGlobalConstantDecl *D) {
970   llvm_unreachable("UnnamedGlobalConstantDecl cannot be instantiated");
971 }
972 
VisitTemplateParamObjectDecl(TemplateParamObjectDecl * D)973 Decl *TemplateDeclInstantiator::VisitTemplateParamObjectDecl(
974     TemplateParamObjectDecl *D) {
975   llvm_unreachable("template parameter objects cannot be instantiated");
976 }
977 
978 Decl *
VisitLabelDecl(LabelDecl * D)979 TemplateDeclInstantiator::VisitLabelDecl(LabelDecl *D) {
980   LabelDecl *Inst = LabelDecl::Create(SemaRef.Context, Owner, D->getLocation(),
981                                       D->getIdentifier());
982   Owner->addDecl(Inst);
983   return Inst;
984 }
985 
986 Decl *
VisitNamespaceDecl(NamespaceDecl * D)987 TemplateDeclInstantiator::VisitNamespaceDecl(NamespaceDecl *D) {
988   llvm_unreachable("Namespaces cannot be instantiated");
989 }
990 
991 Decl *
VisitNamespaceAliasDecl(NamespaceAliasDecl * D)992 TemplateDeclInstantiator::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
993   NamespaceAliasDecl *Inst
994     = NamespaceAliasDecl::Create(SemaRef.Context, Owner,
995                                  D->getNamespaceLoc(),
996                                  D->getAliasLoc(),
997                                  D->getIdentifier(),
998                                  D->getQualifierLoc(),
999                                  D->getTargetNameLoc(),
1000                                  D->getNamespace());
1001   Owner->addDecl(Inst);
1002   return Inst;
1003 }
1004 
InstantiateTypedefNameDecl(TypedefNameDecl * D,bool IsTypeAlias)1005 Decl *TemplateDeclInstantiator::InstantiateTypedefNameDecl(TypedefNameDecl *D,
1006                                                            bool IsTypeAlias) {
1007   bool Invalid = false;
1008   TypeSourceInfo *DI = D->getTypeSourceInfo();
1009   if (DI->getType()->isInstantiationDependentType() ||
1010       DI->getType()->isVariablyModifiedType()) {
1011     DI = SemaRef.SubstType(DI, TemplateArgs,
1012                            D->getLocation(), D->getDeclName());
1013     if (!DI) {
1014       Invalid = true;
1015       DI = SemaRef.Context.getTrivialTypeSourceInfo(SemaRef.Context.IntTy);
1016     }
1017   } else {
1018     SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
1019   }
1020 
1021   // HACK: 2012-10-23 g++ has a bug where it gets the value kind of ?: wrong.
1022   // libstdc++ relies upon this bug in its implementation of common_type.  If we
1023   // happen to be processing that implementation, fake up the g++ ?:
1024   // semantics. See LWG issue 2141 for more information on the bug.  The bugs
1025   // are fixed in g++ and libstdc++ 4.9.0 (2014-04-22).
1026   const DecltypeType *DT = DI->getType()->getAs<DecltypeType>();
1027   CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D->getDeclContext());
1028   if (DT && RD && isa<ConditionalOperator>(DT->getUnderlyingExpr()) &&
1029       DT->isReferenceType() &&
1030       RD->getEnclosingNamespaceContext() == SemaRef.getStdNamespace() &&
1031       RD->getIdentifier() && RD->getIdentifier()->isStr("common_type") &&
1032       D->getIdentifier() && D->getIdentifier()->isStr("type") &&
1033       SemaRef.getSourceManager().isInSystemHeader(D->getBeginLoc()))
1034     // Fold it to the (non-reference) type which g++ would have produced.
1035     DI = SemaRef.Context.getTrivialTypeSourceInfo(
1036       DI->getType().getNonReferenceType());
1037 
1038   // Create the new typedef
1039   TypedefNameDecl *Typedef;
1040   if (IsTypeAlias)
1041     Typedef = TypeAliasDecl::Create(SemaRef.Context, Owner, D->getBeginLoc(),
1042                                     D->getLocation(), D->getIdentifier(), DI);
1043   else
1044     Typedef = TypedefDecl::Create(SemaRef.Context, Owner, D->getBeginLoc(),
1045                                   D->getLocation(), D->getIdentifier(), DI);
1046   if (Invalid)
1047     Typedef->setInvalidDecl();
1048 
1049   // If the old typedef was the name for linkage purposes of an anonymous
1050   // tag decl, re-establish that relationship for the new typedef.
1051   if (const TagType *oldTagType = D->getUnderlyingType()->getAs<TagType>()) {
1052     TagDecl *oldTag = oldTagType->getDecl();
1053     if (oldTag->getTypedefNameForAnonDecl() == D && !Invalid) {
1054       TagDecl *newTag = DI->getType()->castAs<TagType>()->getDecl();
1055       assert(!newTag->hasNameForLinkage());
1056       newTag->setTypedefNameForAnonDecl(Typedef);
1057     }
1058   }
1059 
1060   if (TypedefNameDecl *Prev = getPreviousDeclForInstantiation(D)) {
1061     NamedDecl *InstPrev = SemaRef.FindInstantiatedDecl(D->getLocation(), Prev,
1062                                                        TemplateArgs);
1063     if (!InstPrev)
1064       return nullptr;
1065 
1066     TypedefNameDecl *InstPrevTypedef = cast<TypedefNameDecl>(InstPrev);
1067 
1068     // If the typedef types are not identical, reject them.
1069     SemaRef.isIncompatibleTypedef(InstPrevTypedef, Typedef);
1070 
1071     Typedef->setPreviousDecl(InstPrevTypedef);
1072   }
1073 
1074   SemaRef.InstantiateAttrs(TemplateArgs, D, Typedef);
1075 
1076   if (D->getUnderlyingType()->getAs<DependentNameType>())
1077     SemaRef.inferGslPointerAttribute(Typedef);
1078 
1079   Typedef->setAccess(D->getAccess());
1080   Typedef->setReferenced(D->isReferenced());
1081 
1082   return Typedef;
1083 }
1084 
VisitTypedefDecl(TypedefDecl * D)1085 Decl *TemplateDeclInstantiator::VisitTypedefDecl(TypedefDecl *D) {
1086   Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/false);
1087   if (Typedef)
1088     Owner->addDecl(Typedef);
1089   return Typedef;
1090 }
1091 
VisitTypeAliasDecl(TypeAliasDecl * D)1092 Decl *TemplateDeclInstantiator::VisitTypeAliasDecl(TypeAliasDecl *D) {
1093   Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/true);
1094   if (Typedef)
1095     Owner->addDecl(Typedef);
1096   return Typedef;
1097 }
1098 
InstantiateTypeAliasTemplateDecl(TypeAliasTemplateDecl * D)1099 Decl *TemplateDeclInstantiator::InstantiateTypeAliasTemplateDecl(
1100     TypeAliasTemplateDecl *D) {
1101   // Create a local instantiation scope for this type alias template, which
1102   // will contain the instantiations of the template parameters.
1103   LocalInstantiationScope Scope(SemaRef);
1104 
1105   TemplateParameterList *TempParams = D->getTemplateParameters();
1106   TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1107   if (!InstParams)
1108     return nullptr;
1109 
1110   TypeAliasDecl *Pattern = D->getTemplatedDecl();
1111   Sema::InstantiatingTemplate InstTemplate(
1112       SemaRef, D->getBeginLoc(), D,
1113       D->getTemplateDepth() >= TemplateArgs.getNumLevels()
1114           ? ArrayRef<TemplateArgument>()
1115           : (TemplateArgs.begin() + TemplateArgs.getNumLevels() - 1 -
1116              D->getTemplateDepth())
1117                 ->Args);
1118   if (InstTemplate.isInvalid())
1119     return nullptr;
1120 
1121   TypeAliasTemplateDecl *PrevAliasTemplate = nullptr;
1122   if (getPreviousDeclForInstantiation<TypedefNameDecl>(Pattern)) {
1123     DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
1124     if (!Found.empty()) {
1125       PrevAliasTemplate = dyn_cast<TypeAliasTemplateDecl>(Found.front());
1126     }
1127   }
1128 
1129   TypeAliasDecl *AliasInst = cast_or_null<TypeAliasDecl>(
1130     InstantiateTypedefNameDecl(Pattern, /*IsTypeAlias=*/true));
1131   if (!AliasInst)
1132     return nullptr;
1133 
1134   TypeAliasTemplateDecl *Inst
1135     = TypeAliasTemplateDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1136                                     D->getDeclName(), InstParams, AliasInst);
1137   AliasInst->setDescribedAliasTemplate(Inst);
1138   if (PrevAliasTemplate)
1139     Inst->setPreviousDecl(PrevAliasTemplate);
1140 
1141   Inst->setAccess(D->getAccess());
1142 
1143   if (!PrevAliasTemplate)
1144     Inst->setInstantiatedFromMemberTemplate(D);
1145 
1146   return Inst;
1147 }
1148 
1149 Decl *
VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl * D)1150 TemplateDeclInstantiator::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) {
1151   Decl *Inst = InstantiateTypeAliasTemplateDecl(D);
1152   if (Inst)
1153     Owner->addDecl(Inst);
1154 
1155   return Inst;
1156 }
1157 
VisitBindingDecl(BindingDecl * D)1158 Decl *TemplateDeclInstantiator::VisitBindingDecl(BindingDecl *D) {
1159   auto *NewBD = BindingDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1160                                     D->getIdentifier());
1161   NewBD->setReferenced(D->isReferenced());
1162   SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewBD);
1163   return NewBD;
1164 }
1165 
VisitDecompositionDecl(DecompositionDecl * D)1166 Decl *TemplateDeclInstantiator::VisitDecompositionDecl(DecompositionDecl *D) {
1167   // Transform the bindings first.
1168   SmallVector<BindingDecl*, 16> NewBindings;
1169   for (auto *OldBD : D->bindings())
1170     NewBindings.push_back(cast<BindingDecl>(VisitBindingDecl(OldBD)));
1171   ArrayRef<BindingDecl*> NewBindingArray = NewBindings;
1172 
1173   auto *NewDD = cast_or_null<DecompositionDecl>(
1174       VisitVarDecl(D, /*InstantiatingVarTemplate=*/false, &NewBindingArray));
1175 
1176   if (!NewDD || NewDD->isInvalidDecl())
1177     for (auto *NewBD : NewBindings)
1178       NewBD->setInvalidDecl();
1179 
1180   return NewDD;
1181 }
1182 
VisitVarDecl(VarDecl * D)1183 Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D) {
1184   return VisitVarDecl(D, /*InstantiatingVarTemplate=*/false);
1185 }
1186 
VisitVarDecl(VarDecl * D,bool InstantiatingVarTemplate,ArrayRef<BindingDecl * > * Bindings)1187 Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D,
1188                                              bool InstantiatingVarTemplate,
1189                                              ArrayRef<BindingDecl*> *Bindings) {
1190 
1191   // Do substitution on the type of the declaration
1192   TypeSourceInfo *DI = SemaRef.SubstType(
1193       D->getTypeSourceInfo(), TemplateArgs, D->getTypeSpecStartLoc(),
1194       D->getDeclName(), /*AllowDeducedTST*/true);
1195   if (!DI)
1196     return nullptr;
1197 
1198   if (DI->getType()->isFunctionType()) {
1199     SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function)
1200       << D->isStaticDataMember() << DI->getType();
1201     return nullptr;
1202   }
1203 
1204   DeclContext *DC = Owner;
1205   if (D->isLocalExternDecl())
1206     SemaRef.adjustContextForLocalExternDecl(DC);
1207 
1208   // Build the instantiated declaration.
1209   VarDecl *Var;
1210   if (Bindings)
1211     Var = DecompositionDecl::Create(SemaRef.Context, DC, D->getInnerLocStart(),
1212                                     D->getLocation(), DI->getType(), DI,
1213                                     D->getStorageClass(), *Bindings);
1214   else
1215     Var = VarDecl::Create(SemaRef.Context, DC, D->getInnerLocStart(),
1216                           D->getLocation(), D->getIdentifier(), DI->getType(),
1217                           DI, D->getStorageClass());
1218 
1219   // In ARC, infer 'retaining' for variables of retainable type.
1220   if (SemaRef.getLangOpts().ObjCAutoRefCount &&
1221       SemaRef.ObjC().inferObjCARCLifetime(Var))
1222     Var->setInvalidDecl();
1223 
1224   if (SemaRef.getLangOpts().OpenCL)
1225     SemaRef.deduceOpenCLAddressSpace(Var);
1226 
1227   // Substitute the nested name specifier, if any.
1228   if (SubstQualifier(D, Var))
1229     return nullptr;
1230 
1231   SemaRef.BuildVariableInstantiation(Var, D, TemplateArgs, LateAttrs, Owner,
1232                                      StartingScope, InstantiatingVarTemplate);
1233   if (D->isNRVOVariable() && !Var->isInvalidDecl()) {
1234     QualType RT;
1235     if (auto *F = dyn_cast<FunctionDecl>(DC))
1236       RT = F->getReturnType();
1237     else if (isa<BlockDecl>(DC))
1238       RT = cast<FunctionType>(SemaRef.getCurBlock()->FunctionType)
1239                ->getReturnType();
1240     else
1241       llvm_unreachable("Unknown context type");
1242 
1243     // This is the last chance we have of checking copy elision eligibility
1244     // for functions in dependent contexts. The sema actions for building
1245     // the return statement during template instantiation will have no effect
1246     // regarding copy elision, since NRVO propagation runs on the scope exit
1247     // actions, and these are not run on instantiation.
1248     // This might run through some VarDecls which were returned from non-taken
1249     // 'if constexpr' branches, and these will end up being constructed on the
1250     // return slot even if they will never be returned, as a sort of accidental
1251     // 'optimization'. Notably, functions with 'auto' return types won't have it
1252     // deduced by this point. Coupled with the limitation described
1253     // previously, this makes it very hard to support copy elision for these.
1254     Sema::NamedReturnInfo Info = SemaRef.getNamedReturnInfo(Var);
1255     bool NRVO = SemaRef.getCopyElisionCandidate(Info, RT) != nullptr;
1256     Var->setNRVOVariable(NRVO);
1257   }
1258 
1259   Var->setImplicit(D->isImplicit());
1260 
1261   if (Var->isStaticLocal())
1262     SemaRef.CheckStaticLocalForDllExport(Var);
1263 
1264   if (Var->getTLSKind())
1265     SemaRef.CheckThreadLocalForLargeAlignment(Var);
1266 
1267   return Var;
1268 }
1269 
VisitAccessSpecDecl(AccessSpecDecl * D)1270 Decl *TemplateDeclInstantiator::VisitAccessSpecDecl(AccessSpecDecl *D) {
1271   AccessSpecDecl* AD
1272     = AccessSpecDecl::Create(SemaRef.Context, D->getAccess(), Owner,
1273                              D->getAccessSpecifierLoc(), D->getColonLoc());
1274   Owner->addHiddenDecl(AD);
1275   return AD;
1276 }
1277 
VisitFieldDecl(FieldDecl * D)1278 Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) {
1279   bool Invalid = false;
1280   TypeSourceInfo *DI = D->getTypeSourceInfo();
1281   if (DI->getType()->isInstantiationDependentType() ||
1282       DI->getType()->isVariablyModifiedType())  {
1283     DI = SemaRef.SubstType(DI, TemplateArgs,
1284                            D->getLocation(), D->getDeclName());
1285     if (!DI) {
1286       DI = D->getTypeSourceInfo();
1287       Invalid = true;
1288     } else if (DI->getType()->isFunctionType()) {
1289       // C++ [temp.arg.type]p3:
1290       //   If a declaration acquires a function type through a type
1291       //   dependent on a template-parameter and this causes a
1292       //   declaration that does not use the syntactic form of a
1293       //   function declarator to have function type, the program is
1294       //   ill-formed.
1295       SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
1296         << DI->getType();
1297       Invalid = true;
1298     }
1299   } else {
1300     SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
1301   }
1302 
1303   Expr *BitWidth = D->getBitWidth();
1304   if (Invalid)
1305     BitWidth = nullptr;
1306   else if (BitWidth) {
1307     // The bit-width expression is a constant expression.
1308     EnterExpressionEvaluationContext Unevaluated(
1309         SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
1310 
1311     ExprResult InstantiatedBitWidth
1312       = SemaRef.SubstExpr(BitWidth, TemplateArgs);
1313     if (InstantiatedBitWidth.isInvalid()) {
1314       Invalid = true;
1315       BitWidth = nullptr;
1316     } else
1317       BitWidth = InstantiatedBitWidth.getAs<Expr>();
1318   }
1319 
1320   FieldDecl *Field = SemaRef.CheckFieldDecl(D->getDeclName(),
1321                                             DI->getType(), DI,
1322                                             cast<RecordDecl>(Owner),
1323                                             D->getLocation(),
1324                                             D->isMutable(),
1325                                             BitWidth,
1326                                             D->getInClassInitStyle(),
1327                                             D->getInnerLocStart(),
1328                                             D->getAccess(),
1329                                             nullptr);
1330   if (!Field) {
1331     cast<Decl>(Owner)->setInvalidDecl();
1332     return nullptr;
1333   }
1334 
1335   SemaRef.InstantiateAttrs(TemplateArgs, D, Field, LateAttrs, StartingScope);
1336 
1337   if (Field->hasAttrs())
1338     SemaRef.CheckAlignasUnderalignment(Field);
1339 
1340   if (Invalid)
1341     Field->setInvalidDecl();
1342 
1343   if (!Field->getDeclName()) {
1344     // Keep track of where this decl came from.
1345     SemaRef.Context.setInstantiatedFromUnnamedFieldDecl(Field, D);
1346   }
1347   if (CXXRecordDecl *Parent= dyn_cast<CXXRecordDecl>(Field->getDeclContext())) {
1348     if (Parent->isAnonymousStructOrUnion() &&
1349         Parent->getRedeclContext()->isFunctionOrMethod())
1350       SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Field);
1351   }
1352 
1353   Field->setImplicit(D->isImplicit());
1354   Field->setAccess(D->getAccess());
1355   Owner->addDecl(Field);
1356 
1357   return Field;
1358 }
1359 
VisitMSPropertyDecl(MSPropertyDecl * D)1360 Decl *TemplateDeclInstantiator::VisitMSPropertyDecl(MSPropertyDecl *D) {
1361   bool Invalid = false;
1362   TypeSourceInfo *DI = D->getTypeSourceInfo();
1363 
1364   if (DI->getType()->isVariablyModifiedType()) {
1365     SemaRef.Diag(D->getLocation(), diag::err_property_is_variably_modified)
1366       << D;
1367     Invalid = true;
1368   } else if (DI->getType()->isInstantiationDependentType())  {
1369     DI = SemaRef.SubstType(DI, TemplateArgs,
1370                            D->getLocation(), D->getDeclName());
1371     if (!DI) {
1372       DI = D->getTypeSourceInfo();
1373       Invalid = true;
1374     } else if (DI->getType()->isFunctionType()) {
1375       // C++ [temp.arg.type]p3:
1376       //   If a declaration acquires a function type through a type
1377       //   dependent on a template-parameter and this causes a
1378       //   declaration that does not use the syntactic form of a
1379       //   function declarator to have function type, the program is
1380       //   ill-formed.
1381       SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
1382       << DI->getType();
1383       Invalid = true;
1384     }
1385   } else {
1386     SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
1387   }
1388 
1389   MSPropertyDecl *Property = MSPropertyDecl::Create(
1390       SemaRef.Context, Owner, D->getLocation(), D->getDeclName(), DI->getType(),
1391       DI, D->getBeginLoc(), D->getGetterId(), D->getSetterId());
1392 
1393   SemaRef.InstantiateAttrs(TemplateArgs, D, Property, LateAttrs,
1394                            StartingScope);
1395 
1396   if (Invalid)
1397     Property->setInvalidDecl();
1398 
1399   Property->setAccess(D->getAccess());
1400   Owner->addDecl(Property);
1401 
1402   return Property;
1403 }
1404 
VisitIndirectFieldDecl(IndirectFieldDecl * D)1405 Decl *TemplateDeclInstantiator::VisitIndirectFieldDecl(IndirectFieldDecl *D) {
1406   NamedDecl **NamedChain =
1407     new (SemaRef.Context)NamedDecl*[D->getChainingSize()];
1408 
1409   int i = 0;
1410   for (auto *PI : D->chain()) {
1411     NamedDecl *Next = SemaRef.FindInstantiatedDecl(D->getLocation(), PI,
1412                                               TemplateArgs);
1413     if (!Next)
1414       return nullptr;
1415 
1416     NamedChain[i++] = Next;
1417   }
1418 
1419   QualType T = cast<FieldDecl>(NamedChain[i-1])->getType();
1420   IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
1421       SemaRef.Context, Owner, D->getLocation(), D->getIdentifier(), T,
1422       {NamedChain, D->getChainingSize()});
1423 
1424   for (const auto *Attr : D->attrs())
1425     IndirectField->addAttr(Attr->clone(SemaRef.Context));
1426 
1427   IndirectField->setImplicit(D->isImplicit());
1428   IndirectField->setAccess(D->getAccess());
1429   Owner->addDecl(IndirectField);
1430   return IndirectField;
1431 }
1432 
VisitFriendDecl(FriendDecl * D)1433 Decl *TemplateDeclInstantiator::VisitFriendDecl(FriendDecl *D) {
1434   // Handle friend type expressions by simply substituting template
1435   // parameters into the pattern type and checking the result.
1436   if (TypeSourceInfo *Ty = D->getFriendType()) {
1437     TypeSourceInfo *InstTy;
1438     // If this is an unsupported friend, don't bother substituting template
1439     // arguments into it. The actual type referred to won't be used by any
1440     // parts of Clang, and may not be valid for instantiating. Just use the
1441     // same info for the instantiated friend.
1442     if (D->isUnsupportedFriend()) {
1443       InstTy = Ty;
1444     } else {
1445       InstTy = SemaRef.SubstType(Ty, TemplateArgs,
1446                                  D->getLocation(), DeclarationName());
1447     }
1448     if (!InstTy)
1449       return nullptr;
1450 
1451     FriendDecl *FD = FriendDecl::Create(
1452         SemaRef.Context, Owner, D->getLocation(), InstTy, D->getFriendLoc());
1453     FD->setAccess(AS_public);
1454     FD->setUnsupportedFriend(D->isUnsupportedFriend());
1455     Owner->addDecl(FD);
1456     return FD;
1457   }
1458 
1459   NamedDecl *ND = D->getFriendDecl();
1460   assert(ND && "friend decl must be a decl or a type!");
1461 
1462   // All of the Visit implementations for the various potential friend
1463   // declarations have to be carefully written to work for friend
1464   // objects, with the most important detail being that the target
1465   // decl should almost certainly not be placed in Owner.
1466   Decl *NewND = Visit(ND);
1467   if (!NewND) return nullptr;
1468 
1469   FriendDecl *FD =
1470     FriendDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1471                        cast<NamedDecl>(NewND), D->getFriendLoc());
1472   FD->setAccess(AS_public);
1473   FD->setUnsupportedFriend(D->isUnsupportedFriend());
1474   Owner->addDecl(FD);
1475   return FD;
1476 }
1477 
VisitStaticAssertDecl(StaticAssertDecl * D)1478 Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) {
1479   Expr *AssertExpr = D->getAssertExpr();
1480 
1481   // The expression in a static assertion is a constant expression.
1482   EnterExpressionEvaluationContext Unevaluated(
1483       SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
1484 
1485   ExprResult InstantiatedAssertExpr
1486     = SemaRef.SubstExpr(AssertExpr, TemplateArgs);
1487   if (InstantiatedAssertExpr.isInvalid())
1488     return nullptr;
1489 
1490   ExprResult InstantiatedMessageExpr =
1491       SemaRef.SubstExpr(D->getMessage(), TemplateArgs);
1492   if (InstantiatedMessageExpr.isInvalid())
1493     return nullptr;
1494 
1495   return SemaRef.BuildStaticAssertDeclaration(
1496       D->getLocation(), InstantiatedAssertExpr.get(),
1497       InstantiatedMessageExpr.get(), D->getRParenLoc(), D->isFailed());
1498 }
1499 
VisitEnumDecl(EnumDecl * D)1500 Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) {
1501   EnumDecl *PrevDecl = nullptr;
1502   if (EnumDecl *PatternPrev = getPreviousDeclForInstantiation(D)) {
1503     NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
1504                                                    PatternPrev,
1505                                                    TemplateArgs);
1506     if (!Prev) return nullptr;
1507     PrevDecl = cast<EnumDecl>(Prev);
1508   }
1509 
1510   EnumDecl *Enum =
1511       EnumDecl::Create(SemaRef.Context, Owner, D->getBeginLoc(),
1512                        D->getLocation(), D->getIdentifier(), PrevDecl,
1513                        D->isScoped(), D->isScopedUsingClassTag(), D->isFixed());
1514   if (D->isFixed()) {
1515     if (TypeSourceInfo *TI = D->getIntegerTypeSourceInfo()) {
1516       // If we have type source information for the underlying type, it means it
1517       // has been explicitly set by the user. Perform substitution on it before
1518       // moving on.
1519       SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
1520       TypeSourceInfo *NewTI = SemaRef.SubstType(TI, TemplateArgs, UnderlyingLoc,
1521                                                 DeclarationName());
1522       if (!NewTI || SemaRef.CheckEnumUnderlyingType(NewTI))
1523         Enum->setIntegerType(SemaRef.Context.IntTy);
1524       else
1525         Enum->setIntegerTypeSourceInfo(NewTI);
1526     } else {
1527       assert(!D->getIntegerType()->isDependentType()
1528              && "Dependent type without type source info");
1529       Enum->setIntegerType(D->getIntegerType());
1530     }
1531   }
1532 
1533   SemaRef.InstantiateAttrs(TemplateArgs, D, Enum);
1534 
1535   Enum->setInstantiationOfMemberEnum(D, TSK_ImplicitInstantiation);
1536   Enum->setAccess(D->getAccess());
1537   // Forward the mangling number from the template to the instantiated decl.
1538   SemaRef.Context.setManglingNumber(Enum, SemaRef.Context.getManglingNumber(D));
1539   // See if the old tag was defined along with a declarator.
1540   // If it did, mark the new tag as being associated with that declarator.
1541   if (DeclaratorDecl *DD = SemaRef.Context.getDeclaratorForUnnamedTagDecl(D))
1542     SemaRef.Context.addDeclaratorForUnnamedTagDecl(Enum, DD);
1543   // See if the old tag was defined along with a typedef.
1544   // If it did, mark the new tag as being associated with that typedef.
1545   if (TypedefNameDecl *TND = SemaRef.Context.getTypedefNameForUnnamedTagDecl(D))
1546     SemaRef.Context.addTypedefNameForUnnamedTagDecl(Enum, TND);
1547   if (SubstQualifier(D, Enum)) return nullptr;
1548   Owner->addDecl(Enum);
1549 
1550   EnumDecl *Def = D->getDefinition();
1551   if (Def && Def != D) {
1552     // If this is an out-of-line definition of an enum member template, check
1553     // that the underlying types match in the instantiation of both
1554     // declarations.
1555     if (TypeSourceInfo *TI = Def->getIntegerTypeSourceInfo()) {
1556       SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
1557       QualType DefnUnderlying =
1558         SemaRef.SubstType(TI->getType(), TemplateArgs,
1559                           UnderlyingLoc, DeclarationName());
1560       SemaRef.CheckEnumRedeclaration(Def->getLocation(), Def->isScoped(),
1561                                      DefnUnderlying, /*IsFixed=*/true, Enum);
1562     }
1563   }
1564 
1565   // C++11 [temp.inst]p1: The implicit instantiation of a class template
1566   // specialization causes the implicit instantiation of the declarations, but
1567   // not the definitions of scoped member enumerations.
1568   //
1569   // DR1484 clarifies that enumeration definitions inside of a template
1570   // declaration aren't considered entities that can be separately instantiated
1571   // from the rest of the entity they are declared inside of.
1572   if (isDeclWithinFunction(D) ? D == Def : Def && !Enum->isScoped()) {
1573     SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Enum);
1574     InstantiateEnumDefinition(Enum, Def);
1575   }
1576 
1577   return Enum;
1578 }
1579 
InstantiateEnumDefinition(EnumDecl * Enum,EnumDecl * Pattern)1580 void TemplateDeclInstantiator::InstantiateEnumDefinition(
1581     EnumDecl *Enum, EnumDecl *Pattern) {
1582   Enum->startDefinition();
1583 
1584   // Update the location to refer to the definition.
1585   Enum->setLocation(Pattern->getLocation());
1586 
1587   SmallVector<Decl*, 4> Enumerators;
1588 
1589   EnumConstantDecl *LastEnumConst = nullptr;
1590   for (auto *EC : Pattern->enumerators()) {
1591     // The specified value for the enumerator.
1592     ExprResult Value((Expr *)nullptr);
1593     if (Expr *UninstValue = EC->getInitExpr()) {
1594       // The enumerator's value expression is a constant expression.
1595       EnterExpressionEvaluationContext Unevaluated(
1596           SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
1597 
1598       Value = SemaRef.SubstExpr(UninstValue, TemplateArgs);
1599     }
1600 
1601     // Drop the initial value and continue.
1602     bool isInvalid = false;
1603     if (Value.isInvalid()) {
1604       Value = nullptr;
1605       isInvalid = true;
1606     }
1607 
1608     EnumConstantDecl *EnumConst
1609       = SemaRef.CheckEnumConstant(Enum, LastEnumConst,
1610                                   EC->getLocation(), EC->getIdentifier(),
1611                                   Value.get());
1612 
1613     if (isInvalid) {
1614       if (EnumConst)
1615         EnumConst->setInvalidDecl();
1616       Enum->setInvalidDecl();
1617     }
1618 
1619     if (EnumConst) {
1620       SemaRef.InstantiateAttrs(TemplateArgs, EC, EnumConst);
1621 
1622       EnumConst->setAccess(Enum->getAccess());
1623       Enum->addDecl(EnumConst);
1624       Enumerators.push_back(EnumConst);
1625       LastEnumConst = EnumConst;
1626 
1627       if (Pattern->getDeclContext()->isFunctionOrMethod() &&
1628           !Enum->isScoped()) {
1629         // If the enumeration is within a function or method, record the enum
1630         // constant as a local.
1631         SemaRef.CurrentInstantiationScope->InstantiatedLocal(EC, EnumConst);
1632       }
1633     }
1634   }
1635 
1636   SemaRef.ActOnEnumBody(Enum->getLocation(), Enum->getBraceRange(), Enum,
1637                         Enumerators, nullptr, ParsedAttributesView());
1638 }
1639 
VisitEnumConstantDecl(EnumConstantDecl * D)1640 Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) {
1641   llvm_unreachable("EnumConstantDecls can only occur within EnumDecls.");
1642 }
1643 
1644 Decl *
VisitBuiltinTemplateDecl(BuiltinTemplateDecl * D)1645 TemplateDeclInstantiator::VisitBuiltinTemplateDecl(BuiltinTemplateDecl *D) {
1646   llvm_unreachable("BuiltinTemplateDecls cannot be instantiated.");
1647 }
1648 
VisitClassTemplateDecl(ClassTemplateDecl * D)1649 Decl *TemplateDeclInstantiator::VisitClassTemplateDecl(ClassTemplateDecl *D) {
1650   bool isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
1651 
1652   // Create a local instantiation scope for this class template, which
1653   // will contain the instantiations of the template parameters.
1654   LocalInstantiationScope Scope(SemaRef);
1655   TemplateParameterList *TempParams = D->getTemplateParameters();
1656   TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1657   if (!InstParams)
1658     return nullptr;
1659 
1660   CXXRecordDecl *Pattern = D->getTemplatedDecl();
1661 
1662   // Instantiate the qualifier.  We have to do this first in case
1663   // we're a friend declaration, because if we are then we need to put
1664   // the new declaration in the appropriate context.
1665   NestedNameSpecifierLoc QualifierLoc = Pattern->getQualifierLoc();
1666   if (QualifierLoc) {
1667     QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
1668                                                        TemplateArgs);
1669     if (!QualifierLoc)
1670       return nullptr;
1671   }
1672 
1673   CXXRecordDecl *PrevDecl = nullptr;
1674   ClassTemplateDecl *PrevClassTemplate = nullptr;
1675 
1676   if (!isFriend && getPreviousDeclForInstantiation(Pattern)) {
1677     DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
1678     if (!Found.empty()) {
1679       PrevClassTemplate = dyn_cast<ClassTemplateDecl>(Found.front());
1680       if (PrevClassTemplate)
1681         PrevDecl = PrevClassTemplate->getTemplatedDecl();
1682     }
1683   }
1684 
1685   // If this isn't a friend, then it's a member template, in which
1686   // case we just want to build the instantiation in the
1687   // specialization.  If it is a friend, we want to build it in
1688   // the appropriate context.
1689   DeclContext *DC = Owner;
1690   if (isFriend) {
1691     if (QualifierLoc) {
1692       CXXScopeSpec SS;
1693       SS.Adopt(QualifierLoc);
1694       DC = SemaRef.computeDeclContext(SS);
1695       if (!DC) return nullptr;
1696     } else {
1697       DC = SemaRef.FindInstantiatedContext(Pattern->getLocation(),
1698                                            Pattern->getDeclContext(),
1699                                            TemplateArgs);
1700     }
1701 
1702     // Look for a previous declaration of the template in the owning
1703     // context.
1704     LookupResult R(SemaRef, Pattern->getDeclName(), Pattern->getLocation(),
1705                    Sema::LookupOrdinaryName,
1706                    SemaRef.forRedeclarationInCurContext());
1707     SemaRef.LookupQualifiedName(R, DC);
1708 
1709     if (R.isSingleResult()) {
1710       PrevClassTemplate = R.getAsSingle<ClassTemplateDecl>();
1711       if (PrevClassTemplate)
1712         PrevDecl = PrevClassTemplate->getTemplatedDecl();
1713     }
1714 
1715     if (!PrevClassTemplate && QualifierLoc) {
1716       SemaRef.Diag(Pattern->getLocation(), diag::err_not_tag_in_scope)
1717           << llvm::to_underlying(D->getTemplatedDecl()->getTagKind())
1718           << Pattern->getDeclName() << DC << QualifierLoc.getSourceRange();
1719       return nullptr;
1720     }
1721   }
1722 
1723   CXXRecordDecl *RecordInst = CXXRecordDecl::Create(
1724       SemaRef.Context, Pattern->getTagKind(), DC, Pattern->getBeginLoc(),
1725       Pattern->getLocation(), Pattern->getIdentifier(), PrevDecl,
1726       /*DelayTypeCreation=*/true);
1727   if (QualifierLoc)
1728     RecordInst->setQualifierInfo(QualifierLoc);
1729 
1730   SemaRef.InstantiateAttrsForDecl(TemplateArgs, Pattern, RecordInst, LateAttrs,
1731                                                               StartingScope);
1732 
1733   ClassTemplateDecl *Inst
1734     = ClassTemplateDecl::Create(SemaRef.Context, DC, D->getLocation(),
1735                                 D->getIdentifier(), InstParams, RecordInst);
1736   RecordInst->setDescribedClassTemplate(Inst);
1737 
1738   if (isFriend) {
1739     assert(!Owner->isDependentContext());
1740     Inst->setLexicalDeclContext(Owner);
1741     RecordInst->setLexicalDeclContext(Owner);
1742     Inst->setObjectOfFriendDecl();
1743 
1744     if (PrevClassTemplate) {
1745       Inst->setCommonPtr(PrevClassTemplate->getCommonPtr());
1746       RecordInst->setTypeForDecl(
1747           PrevClassTemplate->getTemplatedDecl()->getTypeForDecl());
1748       const ClassTemplateDecl *MostRecentPrevCT =
1749           PrevClassTemplate->getMostRecentDecl();
1750       TemplateParameterList *PrevParams =
1751           MostRecentPrevCT->getTemplateParameters();
1752 
1753       // Make sure the parameter lists match.
1754       if (!SemaRef.TemplateParameterListsAreEqual(
1755               RecordInst, InstParams, MostRecentPrevCT->getTemplatedDecl(),
1756               PrevParams, true, Sema::TPL_TemplateMatch))
1757         return nullptr;
1758 
1759       // Do some additional validation, then merge default arguments
1760       // from the existing declarations.
1761       if (SemaRef.CheckTemplateParameterList(InstParams, PrevParams,
1762                                              Sema::TPC_ClassTemplate))
1763         return nullptr;
1764 
1765       Inst->setAccess(PrevClassTemplate->getAccess());
1766     } else {
1767       Inst->setAccess(D->getAccess());
1768     }
1769 
1770     Inst->setObjectOfFriendDecl();
1771     // TODO: do we want to track the instantiation progeny of this
1772     // friend target decl?
1773   } else {
1774     Inst->setAccess(D->getAccess());
1775     if (!PrevClassTemplate)
1776       Inst->setInstantiatedFromMemberTemplate(D);
1777   }
1778 
1779   Inst->setPreviousDecl(PrevClassTemplate);
1780 
1781   // Trigger creation of the type for the instantiation.
1782   SemaRef.Context.getInjectedClassNameType(
1783       RecordInst, Inst->getInjectedClassNameSpecialization());
1784 
1785   // Finish handling of friends.
1786   if (isFriend) {
1787     DC->makeDeclVisibleInContext(Inst);
1788     return Inst;
1789   }
1790 
1791   if (D->isOutOfLine()) {
1792     Inst->setLexicalDeclContext(D->getLexicalDeclContext());
1793     RecordInst->setLexicalDeclContext(D->getLexicalDeclContext());
1794   }
1795 
1796   Owner->addDecl(Inst);
1797 
1798   if (!PrevClassTemplate) {
1799     // Queue up any out-of-line partial specializations of this member
1800     // class template; the client will force their instantiation once
1801     // the enclosing class has been instantiated.
1802     SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
1803     D->getPartialSpecializations(PartialSpecs);
1804     for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
1805       if (PartialSpecs[I]->getFirstDecl()->isOutOfLine())
1806         OutOfLinePartialSpecs.push_back(std::make_pair(Inst, PartialSpecs[I]));
1807   }
1808 
1809   return Inst;
1810 }
1811 
1812 Decl *
VisitClassTemplatePartialSpecializationDecl(ClassTemplatePartialSpecializationDecl * D)1813 TemplateDeclInstantiator::VisitClassTemplatePartialSpecializationDecl(
1814                                    ClassTemplatePartialSpecializationDecl *D) {
1815   ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
1816 
1817   // Lookup the already-instantiated declaration in the instantiation
1818   // of the class template and return that.
1819   DeclContext::lookup_result Found
1820     = Owner->lookup(ClassTemplate->getDeclName());
1821   if (Found.empty())
1822     return nullptr;
1823 
1824   ClassTemplateDecl *InstClassTemplate
1825     = dyn_cast<ClassTemplateDecl>(Found.front());
1826   if (!InstClassTemplate)
1827     return nullptr;
1828 
1829   if (ClassTemplatePartialSpecializationDecl *Result
1830         = InstClassTemplate->findPartialSpecInstantiatedFromMember(D))
1831     return Result;
1832 
1833   return InstantiateClassTemplatePartialSpecialization(InstClassTemplate, D);
1834 }
1835 
VisitVarTemplateDecl(VarTemplateDecl * D)1836 Decl *TemplateDeclInstantiator::VisitVarTemplateDecl(VarTemplateDecl *D) {
1837   assert(D->getTemplatedDecl()->isStaticDataMember() &&
1838          "Only static data member templates are allowed.");
1839 
1840   // Create a local instantiation scope for this variable template, which
1841   // will contain the instantiations of the template parameters.
1842   LocalInstantiationScope Scope(SemaRef);
1843   TemplateParameterList *TempParams = D->getTemplateParameters();
1844   TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1845   if (!InstParams)
1846     return nullptr;
1847 
1848   VarDecl *Pattern = D->getTemplatedDecl();
1849   VarTemplateDecl *PrevVarTemplate = nullptr;
1850 
1851   if (getPreviousDeclForInstantiation(Pattern)) {
1852     DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
1853     if (!Found.empty())
1854       PrevVarTemplate = dyn_cast<VarTemplateDecl>(Found.front());
1855   }
1856 
1857   VarDecl *VarInst =
1858       cast_or_null<VarDecl>(VisitVarDecl(Pattern,
1859                                          /*InstantiatingVarTemplate=*/true));
1860   if (!VarInst) return nullptr;
1861 
1862   DeclContext *DC = Owner;
1863 
1864   VarTemplateDecl *Inst = VarTemplateDecl::Create(
1865       SemaRef.Context, DC, D->getLocation(), D->getIdentifier(), InstParams,
1866       VarInst);
1867   VarInst->setDescribedVarTemplate(Inst);
1868   Inst->setPreviousDecl(PrevVarTemplate);
1869 
1870   Inst->setAccess(D->getAccess());
1871   if (!PrevVarTemplate)
1872     Inst->setInstantiatedFromMemberTemplate(D);
1873 
1874   if (D->isOutOfLine()) {
1875     Inst->setLexicalDeclContext(D->getLexicalDeclContext());
1876     VarInst->setLexicalDeclContext(D->getLexicalDeclContext());
1877   }
1878 
1879   Owner->addDecl(Inst);
1880 
1881   if (!PrevVarTemplate) {
1882     // Queue up any out-of-line partial specializations of this member
1883     // variable template; the client will force their instantiation once
1884     // the enclosing class has been instantiated.
1885     SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs;
1886     D->getPartialSpecializations(PartialSpecs);
1887     for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
1888       if (PartialSpecs[I]->getFirstDecl()->isOutOfLine())
1889         OutOfLineVarPartialSpecs.push_back(
1890             std::make_pair(Inst, PartialSpecs[I]));
1891   }
1892 
1893   return Inst;
1894 }
1895 
VisitVarTemplatePartialSpecializationDecl(VarTemplatePartialSpecializationDecl * D)1896 Decl *TemplateDeclInstantiator::VisitVarTemplatePartialSpecializationDecl(
1897     VarTemplatePartialSpecializationDecl *D) {
1898   assert(D->isStaticDataMember() &&
1899          "Only static data member templates are allowed.");
1900 
1901   VarTemplateDecl *VarTemplate = D->getSpecializedTemplate();
1902 
1903   // Lookup the already-instantiated declaration and return that.
1904   DeclContext::lookup_result Found = Owner->lookup(VarTemplate->getDeclName());
1905   assert(!Found.empty() && "Instantiation found nothing?");
1906 
1907   VarTemplateDecl *InstVarTemplate = dyn_cast<VarTemplateDecl>(Found.front());
1908   assert(InstVarTemplate && "Instantiation did not find a variable template?");
1909 
1910   if (VarTemplatePartialSpecializationDecl *Result =
1911           InstVarTemplate->findPartialSpecInstantiatedFromMember(D))
1912     return Result;
1913 
1914   return InstantiateVarTemplatePartialSpecialization(InstVarTemplate, D);
1915 }
1916 
1917 Decl *
VisitFunctionTemplateDecl(FunctionTemplateDecl * D)1918 TemplateDeclInstantiator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
1919   // Create a local instantiation scope for this function template, which
1920   // will contain the instantiations of the template parameters and then get
1921   // merged with the local instantiation scope for the function template
1922   // itself.
1923   LocalInstantiationScope Scope(SemaRef);
1924   Sema::ConstraintEvalRAII<TemplateDeclInstantiator> RAII(*this);
1925 
1926   TemplateParameterList *TempParams = D->getTemplateParameters();
1927   TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1928   if (!InstParams)
1929     return nullptr;
1930 
1931   FunctionDecl *Instantiated = nullptr;
1932   if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(D->getTemplatedDecl()))
1933     Instantiated = cast_or_null<FunctionDecl>(VisitCXXMethodDecl(DMethod,
1934                                                                  InstParams));
1935   else
1936     Instantiated = cast_or_null<FunctionDecl>(VisitFunctionDecl(
1937                                                           D->getTemplatedDecl(),
1938                                                                 InstParams));
1939 
1940   if (!Instantiated)
1941     return nullptr;
1942 
1943   // Link the instantiated function template declaration to the function
1944   // template from which it was instantiated.
1945   FunctionTemplateDecl *InstTemplate
1946     = Instantiated->getDescribedFunctionTemplate();
1947   InstTemplate->setAccess(D->getAccess());
1948   assert(InstTemplate &&
1949          "VisitFunctionDecl/CXXMethodDecl didn't create a template!");
1950 
1951   bool isFriend = (InstTemplate->getFriendObjectKind() != Decl::FOK_None);
1952 
1953   // Link the instantiation back to the pattern *unless* this is a
1954   // non-definition friend declaration.
1955   if (!InstTemplate->getInstantiatedFromMemberTemplate() &&
1956       !(isFriend && !D->getTemplatedDecl()->isThisDeclarationADefinition()))
1957     InstTemplate->setInstantiatedFromMemberTemplate(D);
1958 
1959   // Make declarations visible in the appropriate context.
1960   if (!isFriend) {
1961     Owner->addDecl(InstTemplate);
1962   } else if (InstTemplate->getDeclContext()->isRecord() &&
1963              !getPreviousDeclForInstantiation(D)) {
1964     SemaRef.CheckFriendAccess(InstTemplate);
1965   }
1966 
1967   return InstTemplate;
1968 }
1969 
VisitCXXRecordDecl(CXXRecordDecl * D)1970 Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) {
1971   CXXRecordDecl *PrevDecl = nullptr;
1972   if (CXXRecordDecl *PatternPrev = getPreviousDeclForInstantiation(D)) {
1973     NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
1974                                                    PatternPrev,
1975                                                    TemplateArgs);
1976     if (!Prev) return nullptr;
1977     PrevDecl = cast<CXXRecordDecl>(Prev);
1978   }
1979 
1980   CXXRecordDecl *Record = nullptr;
1981   bool IsInjectedClassName = D->isInjectedClassName();
1982   if (D->isLambda())
1983     Record = CXXRecordDecl::CreateLambda(
1984         SemaRef.Context, Owner, D->getLambdaTypeInfo(), D->getLocation(),
1985         D->getLambdaDependencyKind(), D->isGenericLambda(),
1986         D->getLambdaCaptureDefault());
1987   else
1988     Record = CXXRecordDecl::Create(SemaRef.Context, D->getTagKind(), Owner,
1989                                    D->getBeginLoc(), D->getLocation(),
1990                                    D->getIdentifier(), PrevDecl,
1991                                    /*DelayTypeCreation=*/IsInjectedClassName);
1992   // Link the type of the injected-class-name to that of the outer class.
1993   if (IsInjectedClassName)
1994     (void)SemaRef.Context.getTypeDeclType(Record, cast<CXXRecordDecl>(Owner));
1995 
1996   // Substitute the nested name specifier, if any.
1997   if (SubstQualifier(D, Record))
1998     return nullptr;
1999 
2000   SemaRef.InstantiateAttrsForDecl(TemplateArgs, D, Record, LateAttrs,
2001                                                               StartingScope);
2002 
2003   Record->setImplicit(D->isImplicit());
2004   // FIXME: Check against AS_none is an ugly hack to work around the issue that
2005   // the tag decls introduced by friend class declarations don't have an access
2006   // specifier. Remove once this area of the code gets sorted out.
2007   if (D->getAccess() != AS_none)
2008     Record->setAccess(D->getAccess());
2009   if (!IsInjectedClassName)
2010     Record->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
2011 
2012   // If the original function was part of a friend declaration,
2013   // inherit its namespace state.
2014   if (D->getFriendObjectKind())
2015     Record->setObjectOfFriendDecl();
2016 
2017   // Make sure that anonymous structs and unions are recorded.
2018   if (D->isAnonymousStructOrUnion())
2019     Record->setAnonymousStructOrUnion(true);
2020 
2021   if (D->isLocalClass())
2022     SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Record);
2023 
2024   // Forward the mangling number from the template to the instantiated decl.
2025   SemaRef.Context.setManglingNumber(Record,
2026                                     SemaRef.Context.getManglingNumber(D));
2027 
2028   // See if the old tag was defined along with a declarator.
2029   // If it did, mark the new tag as being associated with that declarator.
2030   if (DeclaratorDecl *DD = SemaRef.Context.getDeclaratorForUnnamedTagDecl(D))
2031     SemaRef.Context.addDeclaratorForUnnamedTagDecl(Record, DD);
2032 
2033   // See if the old tag was defined along with a typedef.
2034   // If it did, mark the new tag as being associated with that typedef.
2035   if (TypedefNameDecl *TND = SemaRef.Context.getTypedefNameForUnnamedTagDecl(D))
2036     SemaRef.Context.addTypedefNameForUnnamedTagDecl(Record, TND);
2037 
2038   Owner->addDecl(Record);
2039 
2040   // DR1484 clarifies that the members of a local class are instantiated as part
2041   // of the instantiation of their enclosing entity.
2042   if (D->isCompleteDefinition() && D->isLocalClass()) {
2043     Sema::LocalEagerInstantiationScope LocalInstantiations(SemaRef);
2044 
2045     SemaRef.InstantiateClass(D->getLocation(), Record, D, TemplateArgs,
2046                              TSK_ImplicitInstantiation,
2047                              /*Complain=*/true);
2048 
2049     // For nested local classes, we will instantiate the members when we
2050     // reach the end of the outermost (non-nested) local class.
2051     if (!D->isCXXClassMember())
2052       SemaRef.InstantiateClassMembers(D->getLocation(), Record, TemplateArgs,
2053                                       TSK_ImplicitInstantiation);
2054 
2055     // This class may have local implicit instantiations that need to be
2056     // performed within this scope.
2057     LocalInstantiations.perform();
2058   }
2059 
2060   SemaRef.DiagnoseUnusedNestedTypedefs(Record);
2061 
2062   if (IsInjectedClassName)
2063     assert(Record->isInjectedClassName() && "Broken injected-class-name");
2064 
2065   return Record;
2066 }
2067 
2068 /// Adjust the given function type for an instantiation of the
2069 /// given declaration, to cope with modifications to the function's type that
2070 /// aren't reflected in the type-source information.
2071 ///
2072 /// \param D The declaration we're instantiating.
2073 /// \param TInfo The already-instantiated type.
adjustFunctionTypeForInstantiation(ASTContext & Context,FunctionDecl * D,TypeSourceInfo * TInfo)2074 static QualType adjustFunctionTypeForInstantiation(ASTContext &Context,
2075                                                    FunctionDecl *D,
2076                                                    TypeSourceInfo *TInfo) {
2077   const FunctionProtoType *OrigFunc
2078     = D->getType()->castAs<FunctionProtoType>();
2079   const FunctionProtoType *NewFunc
2080     = TInfo->getType()->castAs<FunctionProtoType>();
2081   if (OrigFunc->getExtInfo() == NewFunc->getExtInfo())
2082     return TInfo->getType();
2083 
2084   FunctionProtoType::ExtProtoInfo NewEPI = NewFunc->getExtProtoInfo();
2085   NewEPI.ExtInfo = OrigFunc->getExtInfo();
2086   return Context.getFunctionType(NewFunc->getReturnType(),
2087                                  NewFunc->getParamTypes(), NewEPI);
2088 }
2089 
2090 /// Normal class members are of more specific types and therefore
2091 /// don't make it here.  This function serves three purposes:
2092 ///   1) instantiating function templates
2093 ///   2) substituting friend and local function declarations
2094 ///   3) substituting deduction guide declarations for nested class templates
VisitFunctionDecl(FunctionDecl * D,TemplateParameterList * TemplateParams,RewriteKind FunctionRewriteKind)2095 Decl *TemplateDeclInstantiator::VisitFunctionDecl(
2096     FunctionDecl *D, TemplateParameterList *TemplateParams,
2097     RewriteKind FunctionRewriteKind) {
2098   // Check whether there is already a function template specialization for
2099   // this declaration.
2100   FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
2101   if (FunctionTemplate && !TemplateParams) {
2102     ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
2103 
2104     void *InsertPos = nullptr;
2105     FunctionDecl *SpecFunc
2106       = FunctionTemplate->findSpecialization(Innermost, InsertPos);
2107 
2108     // If we already have a function template specialization, return it.
2109     if (SpecFunc)
2110       return SpecFunc;
2111   }
2112 
2113   bool isFriend;
2114   if (FunctionTemplate)
2115     isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
2116   else
2117     isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
2118 
2119   bool MergeWithParentScope = (TemplateParams != nullptr) ||
2120     Owner->isFunctionOrMethod() ||
2121     !(isa<Decl>(Owner) &&
2122       cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
2123   LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
2124 
2125   ExplicitSpecifier InstantiatedExplicitSpecifier;
2126   if (auto *DGuide = dyn_cast<CXXDeductionGuideDecl>(D)) {
2127     InstantiatedExplicitSpecifier = SemaRef.instantiateExplicitSpecifier(
2128         TemplateArgs, DGuide->getExplicitSpecifier());
2129     if (InstantiatedExplicitSpecifier.isInvalid())
2130       return nullptr;
2131   }
2132 
2133   SmallVector<ParmVarDecl *, 4> Params;
2134   TypeSourceInfo *TInfo = SubstFunctionType(D, Params);
2135   if (!TInfo)
2136     return nullptr;
2137   QualType T = adjustFunctionTypeForInstantiation(SemaRef.Context, D, TInfo);
2138 
2139   if (TemplateParams && TemplateParams->size()) {
2140     auto *LastParam =
2141         dyn_cast<TemplateTypeParmDecl>(TemplateParams->asArray().back());
2142     if (LastParam && LastParam->isImplicit() &&
2143         LastParam->hasTypeConstraint()) {
2144       // In abbreviated templates, the type-constraints of invented template
2145       // type parameters are instantiated with the function type, invalidating
2146       // the TemplateParameterList which relied on the template type parameter
2147       // not having a type constraint. Recreate the TemplateParameterList with
2148       // the updated parameter list.
2149       TemplateParams = TemplateParameterList::Create(
2150           SemaRef.Context, TemplateParams->getTemplateLoc(),
2151           TemplateParams->getLAngleLoc(), TemplateParams->asArray(),
2152           TemplateParams->getRAngleLoc(), TemplateParams->getRequiresClause());
2153     }
2154   }
2155 
2156   NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
2157   if (QualifierLoc) {
2158     QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
2159                                                        TemplateArgs);
2160     if (!QualifierLoc)
2161       return nullptr;
2162   }
2163 
2164   Expr *TrailingRequiresClause = D->getTrailingRequiresClause();
2165 
2166   // If we're instantiating a local function declaration, put the result
2167   // in the enclosing namespace; otherwise we need to find the instantiated
2168   // context.
2169   DeclContext *DC;
2170   if (D->isLocalExternDecl()) {
2171     DC = Owner;
2172     SemaRef.adjustContextForLocalExternDecl(DC);
2173   } else if (isFriend && QualifierLoc) {
2174     CXXScopeSpec SS;
2175     SS.Adopt(QualifierLoc);
2176     DC = SemaRef.computeDeclContext(SS);
2177     if (!DC) return nullptr;
2178   } else {
2179     DC = SemaRef.FindInstantiatedContext(D->getLocation(), D->getDeclContext(),
2180                                          TemplateArgs);
2181   }
2182 
2183   DeclarationNameInfo NameInfo
2184     = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
2185 
2186   if (FunctionRewriteKind != RewriteKind::None)
2187     adjustForRewrite(FunctionRewriteKind, D, T, TInfo, NameInfo);
2188 
2189   FunctionDecl *Function;
2190   if (auto *DGuide = dyn_cast<CXXDeductionGuideDecl>(D)) {
2191     Function = CXXDeductionGuideDecl::Create(
2192         SemaRef.Context, DC, D->getInnerLocStart(),
2193         InstantiatedExplicitSpecifier, NameInfo, T, TInfo,
2194         D->getSourceRange().getEnd(), DGuide->getCorrespondingConstructor(),
2195         DGuide->getDeductionCandidateKind());
2196     Function->setAccess(D->getAccess());
2197   } else {
2198     Function = FunctionDecl::Create(
2199         SemaRef.Context, DC, D->getInnerLocStart(), NameInfo, T, TInfo,
2200         D->getCanonicalDecl()->getStorageClass(), D->UsesFPIntrin(),
2201         D->isInlineSpecified(), D->hasWrittenPrototype(), D->getConstexprKind(),
2202         TrailingRequiresClause);
2203     Function->setFriendConstraintRefersToEnclosingTemplate(
2204         D->FriendConstraintRefersToEnclosingTemplate());
2205     Function->setRangeEnd(D->getSourceRange().getEnd());
2206   }
2207 
2208   if (D->isInlined())
2209     Function->setImplicitlyInline();
2210 
2211   if (QualifierLoc)
2212     Function->setQualifierInfo(QualifierLoc);
2213 
2214   if (D->isLocalExternDecl())
2215     Function->setLocalExternDecl();
2216 
2217   DeclContext *LexicalDC = Owner;
2218   if (!isFriend && D->isOutOfLine() && !D->isLocalExternDecl()) {
2219     assert(D->getDeclContext()->isFileContext());
2220     LexicalDC = D->getDeclContext();
2221   }
2222   else if (D->isLocalExternDecl()) {
2223     LexicalDC = SemaRef.CurContext;
2224   }
2225 
2226   Function->setLexicalDeclContext(LexicalDC);
2227 
2228   // Attach the parameters
2229   for (unsigned P = 0; P < Params.size(); ++P)
2230     if (Params[P])
2231       Params[P]->setOwningFunction(Function);
2232   Function->setParams(Params);
2233 
2234   if (TrailingRequiresClause)
2235     Function->setTrailingRequiresClause(TrailingRequiresClause);
2236 
2237   if (TemplateParams) {
2238     // Our resulting instantiation is actually a function template, since we
2239     // are substituting only the outer template parameters. For example, given
2240     //
2241     //   template<typename T>
2242     //   struct X {
2243     //     template<typename U> friend void f(T, U);
2244     //   };
2245     //
2246     //   X<int> x;
2247     //
2248     // We are instantiating the friend function template "f" within X<int>,
2249     // which means substituting int for T, but leaving "f" as a friend function
2250     // template.
2251     // Build the function template itself.
2252     FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, DC,
2253                                                     Function->getLocation(),
2254                                                     Function->getDeclName(),
2255                                                     TemplateParams, Function);
2256     Function->setDescribedFunctionTemplate(FunctionTemplate);
2257 
2258     FunctionTemplate->setLexicalDeclContext(LexicalDC);
2259 
2260     if (isFriend && D->isThisDeclarationADefinition()) {
2261       FunctionTemplate->setInstantiatedFromMemberTemplate(
2262                                            D->getDescribedFunctionTemplate());
2263     }
2264   } else if (FunctionTemplate &&
2265              SemaRef.CodeSynthesisContexts.back().Kind !=
2266                  Sema::CodeSynthesisContext::BuildingDeductionGuides) {
2267     // Record this function template specialization.
2268     ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
2269     Function->setFunctionTemplateSpecialization(FunctionTemplate,
2270                             TemplateArgumentList::CreateCopy(SemaRef.Context,
2271                                                              Innermost),
2272                                                 /*InsertPos=*/nullptr);
2273   } else if (FunctionRewriteKind == RewriteKind::None) {
2274     if (isFriend && D->isThisDeclarationADefinition()) {
2275       // Do not connect the friend to the template unless it's actually a
2276       // definition. We don't want non-template functions to be marked as being
2277       // template instantiations.
2278       Function->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
2279     } else if (!isFriend) {
2280       // If this is not a function template, and this is not a friend (that is,
2281       // this is a locally declared function), save the instantiation
2282       // relationship for the purposes of constraint instantiation.
2283       Function->setInstantiatedFromDecl(D);
2284     }
2285   }
2286 
2287   if (isFriend) {
2288     Function->setObjectOfFriendDecl();
2289     if (FunctionTemplateDecl *FT = Function->getDescribedFunctionTemplate())
2290       FT->setObjectOfFriendDecl();
2291   }
2292 
2293   if (InitFunctionInstantiation(Function, D))
2294     Function->setInvalidDecl();
2295 
2296   bool IsExplicitSpecialization = false;
2297 
2298   LookupResult Previous(
2299       SemaRef, Function->getDeclName(), SourceLocation(),
2300       D->isLocalExternDecl() ? Sema::LookupRedeclarationWithLinkage
2301                              : Sema::LookupOrdinaryName,
2302       D->isLocalExternDecl() ? RedeclarationKind::ForExternalRedeclaration
2303                              : SemaRef.forRedeclarationInCurContext());
2304 
2305   if (DependentFunctionTemplateSpecializationInfo *DFTSI =
2306           D->getDependentSpecializationInfo()) {
2307     assert(isFriend && "dependent specialization info on "
2308                        "non-member non-friend function?");
2309 
2310     // Instantiate the explicit template arguments.
2311     TemplateArgumentListInfo ExplicitArgs;
2312     if (const auto *ArgsWritten = DFTSI->TemplateArgumentsAsWritten) {
2313       ExplicitArgs.setLAngleLoc(ArgsWritten->getLAngleLoc());
2314       ExplicitArgs.setRAngleLoc(ArgsWritten->getRAngleLoc());
2315       if (SemaRef.SubstTemplateArguments(ArgsWritten->arguments(), TemplateArgs,
2316                                          ExplicitArgs))
2317         return nullptr;
2318     }
2319 
2320     // Map the candidates for the primary template to their instantiations.
2321     for (FunctionTemplateDecl *FTD : DFTSI->getCandidates()) {
2322       if (NamedDecl *ND =
2323               SemaRef.FindInstantiatedDecl(D->getLocation(), FTD, TemplateArgs))
2324         Previous.addDecl(ND);
2325       else
2326         return nullptr;
2327     }
2328 
2329     if (SemaRef.CheckFunctionTemplateSpecialization(
2330             Function,
2331             DFTSI->TemplateArgumentsAsWritten ? &ExplicitArgs : nullptr,
2332             Previous))
2333       Function->setInvalidDecl();
2334 
2335     IsExplicitSpecialization = true;
2336   } else if (const ASTTemplateArgumentListInfo *ArgsWritten =
2337                  D->getTemplateSpecializationArgsAsWritten()) {
2338     // The name of this function was written as a template-id.
2339     SemaRef.LookupQualifiedName(Previous, DC);
2340 
2341     // Instantiate the explicit template arguments.
2342     TemplateArgumentListInfo ExplicitArgs(ArgsWritten->getLAngleLoc(),
2343                                           ArgsWritten->getRAngleLoc());
2344     if (SemaRef.SubstTemplateArguments(ArgsWritten->arguments(), TemplateArgs,
2345                                        ExplicitArgs))
2346       return nullptr;
2347 
2348     if (SemaRef.CheckFunctionTemplateSpecialization(Function,
2349                                                     &ExplicitArgs,
2350                                                     Previous))
2351       Function->setInvalidDecl();
2352 
2353     IsExplicitSpecialization = true;
2354   } else if (TemplateParams || !FunctionTemplate) {
2355     // Look only into the namespace where the friend would be declared to
2356     // find a previous declaration. This is the innermost enclosing namespace,
2357     // as described in ActOnFriendFunctionDecl.
2358     SemaRef.LookupQualifiedName(Previous, DC->getRedeclContext());
2359 
2360     // In C++, the previous declaration we find might be a tag type
2361     // (class or enum). In this case, the new declaration will hide the
2362     // tag type. Note that this does not apply if we're declaring a
2363     // typedef (C++ [dcl.typedef]p4).
2364     if (Previous.isSingleTagDecl())
2365       Previous.clear();
2366 
2367     // Filter out previous declarations that don't match the scope. The only
2368     // effect this has is to remove declarations found in inline namespaces
2369     // for friend declarations with unqualified names.
2370     if (isFriend && !QualifierLoc) {
2371       SemaRef.FilterLookupForScope(Previous, DC, /*Scope=*/ nullptr,
2372                                    /*ConsiderLinkage=*/ true,
2373                                    QualifierLoc.hasQualifier());
2374     }
2375   }
2376 
2377   // Per [temp.inst], default arguments in function declarations at local scope
2378   // are instantiated along with the enclosing declaration. For example:
2379   //
2380   //   template<typename T>
2381   //   void ft() {
2382   //     void f(int = []{ return T::value; }());
2383   //   }
2384   //   template void ft<int>(); // error: type 'int' cannot be used prior
2385   //                                      to '::' because it has no members
2386   //
2387   // The error is issued during instantiation of ft<int>() because substitution
2388   // into the default argument fails; the default argument is instantiated even
2389   // though it is never used.
2390   if (Function->isLocalExternDecl()) {
2391     for (ParmVarDecl *PVD : Function->parameters()) {
2392       if (!PVD->hasDefaultArg())
2393         continue;
2394       if (SemaRef.SubstDefaultArgument(D->getInnerLocStart(), PVD, TemplateArgs)) {
2395         // If substitution fails, the default argument is set to a
2396         // RecoveryExpr that wraps the uninstantiated default argument so
2397         // that downstream diagnostics are omitted.
2398         Expr *UninstExpr = PVD->getUninstantiatedDefaultArg();
2399         ExprResult ErrorResult = SemaRef.CreateRecoveryExpr(
2400             UninstExpr->getBeginLoc(), UninstExpr->getEndLoc(),
2401             { UninstExpr }, UninstExpr->getType());
2402         if (ErrorResult.isUsable())
2403           PVD->setDefaultArg(ErrorResult.get());
2404       }
2405     }
2406   }
2407 
2408   SemaRef.CheckFunctionDeclaration(/*Scope*/ nullptr, Function, Previous,
2409                                    IsExplicitSpecialization,
2410                                    Function->isThisDeclarationADefinition());
2411 
2412   // Check the template parameter list against the previous declaration. The
2413   // goal here is to pick up default arguments added since the friend was
2414   // declared; we know the template parameter lists match, since otherwise
2415   // we would not have picked this template as the previous declaration.
2416   if (isFriend && TemplateParams && FunctionTemplate->getPreviousDecl()) {
2417     SemaRef.CheckTemplateParameterList(
2418         TemplateParams,
2419         FunctionTemplate->getPreviousDecl()->getTemplateParameters(),
2420         Function->isThisDeclarationADefinition()
2421             ? Sema::TPC_FriendFunctionTemplateDefinition
2422             : Sema::TPC_FriendFunctionTemplate);
2423   }
2424 
2425   // If we're introducing a friend definition after the first use, trigger
2426   // instantiation.
2427   // FIXME: If this is a friend function template definition, we should check
2428   // to see if any specializations have been used.
2429   if (isFriend && D->isThisDeclarationADefinition() && Function->isUsed(false)) {
2430     if (MemberSpecializationInfo *MSInfo =
2431             Function->getMemberSpecializationInfo()) {
2432       if (MSInfo->getPointOfInstantiation().isInvalid()) {
2433         SourceLocation Loc = D->getLocation(); // FIXME
2434         MSInfo->setPointOfInstantiation(Loc);
2435         SemaRef.PendingLocalImplicitInstantiations.push_back(
2436             std::make_pair(Function, Loc));
2437       }
2438     }
2439   }
2440 
2441   if (D->isExplicitlyDefaulted()) {
2442     if (SubstDefaultedFunction(Function, D))
2443       return nullptr;
2444   }
2445   if (D->isDeleted())
2446     SemaRef.SetDeclDeleted(Function, D->getLocation(), D->getDeletedMessage());
2447 
2448   NamedDecl *PrincipalDecl =
2449       (TemplateParams ? cast<NamedDecl>(FunctionTemplate) : Function);
2450 
2451   // If this declaration lives in a different context from its lexical context,
2452   // add it to the corresponding lookup table.
2453   if (isFriend ||
2454       (Function->isLocalExternDecl() && !Function->getPreviousDecl()))
2455     DC->makeDeclVisibleInContext(PrincipalDecl);
2456 
2457   if (Function->isOverloadedOperator() && !DC->isRecord() &&
2458       PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
2459     PrincipalDecl->setNonMemberOperator();
2460 
2461   return Function;
2462 }
2463 
VisitCXXMethodDecl(CXXMethodDecl * D,TemplateParameterList * TemplateParams,RewriteKind FunctionRewriteKind)2464 Decl *TemplateDeclInstantiator::VisitCXXMethodDecl(
2465     CXXMethodDecl *D, TemplateParameterList *TemplateParams,
2466     RewriteKind FunctionRewriteKind) {
2467   FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
2468   if (FunctionTemplate && !TemplateParams) {
2469     // We are creating a function template specialization from a function
2470     // template. Check whether there is already a function template
2471     // specialization for this particular set of template arguments.
2472     ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
2473 
2474     void *InsertPos = nullptr;
2475     FunctionDecl *SpecFunc
2476       = FunctionTemplate->findSpecialization(Innermost, InsertPos);
2477 
2478     // If we already have a function template specialization, return it.
2479     if (SpecFunc)
2480       return SpecFunc;
2481   }
2482 
2483   bool isFriend;
2484   if (FunctionTemplate)
2485     isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
2486   else
2487     isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
2488 
2489   bool MergeWithParentScope = (TemplateParams != nullptr) ||
2490     !(isa<Decl>(Owner) &&
2491       cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
2492   LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
2493 
2494   Sema::LambdaScopeForCallOperatorInstantiationRAII LambdaScope(
2495       SemaRef, const_cast<CXXMethodDecl *>(D), TemplateArgs, Scope);
2496 
2497   // Instantiate enclosing template arguments for friends.
2498   SmallVector<TemplateParameterList *, 4> TempParamLists;
2499   unsigned NumTempParamLists = 0;
2500   if (isFriend && (NumTempParamLists = D->getNumTemplateParameterLists())) {
2501     TempParamLists.resize(NumTempParamLists);
2502     for (unsigned I = 0; I != NumTempParamLists; ++I) {
2503       TemplateParameterList *TempParams = D->getTemplateParameterList(I);
2504       TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
2505       if (!InstParams)
2506         return nullptr;
2507       TempParamLists[I] = InstParams;
2508     }
2509   }
2510 
2511   auto InstantiatedExplicitSpecifier = ExplicitSpecifier::getFromDecl(D);
2512   // deduction guides need this
2513   const bool CouldInstantiate =
2514       InstantiatedExplicitSpecifier.getExpr() == nullptr ||
2515       !InstantiatedExplicitSpecifier.getExpr()->isValueDependent();
2516 
2517   // Delay the instantiation of the explicit-specifier until after the
2518   // constraints are checked during template argument deduction.
2519   if (CouldInstantiate ||
2520       SemaRef.CodeSynthesisContexts.back().Kind !=
2521           Sema::CodeSynthesisContext::DeducedTemplateArgumentSubstitution) {
2522     InstantiatedExplicitSpecifier = SemaRef.instantiateExplicitSpecifier(
2523         TemplateArgs, InstantiatedExplicitSpecifier);
2524 
2525     if (InstantiatedExplicitSpecifier.isInvalid())
2526       return nullptr;
2527   } else {
2528     InstantiatedExplicitSpecifier.setKind(ExplicitSpecKind::Unresolved);
2529   }
2530 
2531   // Implicit destructors/constructors created for local classes in
2532   // DeclareImplicit* (see SemaDeclCXX.cpp) might not have an associated TSI.
2533   // Unfortunately there isn't enough context in those functions to
2534   // conditionally populate the TSI without breaking non-template related use
2535   // cases. Populate TSIs prior to calling SubstFunctionType to make sure we get
2536   // a proper transformation.
2537   if (cast<CXXRecordDecl>(D->getParent())->isLambda() &&
2538       !D->getTypeSourceInfo() &&
2539       isa<CXXConstructorDecl, CXXDestructorDecl>(D)) {
2540     TypeSourceInfo *TSI =
2541         SemaRef.Context.getTrivialTypeSourceInfo(D->getType());
2542     D->setTypeSourceInfo(TSI);
2543   }
2544 
2545   SmallVector<ParmVarDecl *, 4> Params;
2546   TypeSourceInfo *TInfo = SubstFunctionType(D, Params);
2547   if (!TInfo)
2548     return nullptr;
2549   QualType T = adjustFunctionTypeForInstantiation(SemaRef.Context, D, TInfo);
2550 
2551   if (TemplateParams && TemplateParams->size()) {
2552     auto *LastParam =
2553         dyn_cast<TemplateTypeParmDecl>(TemplateParams->asArray().back());
2554     if (LastParam && LastParam->isImplicit() &&
2555         LastParam->hasTypeConstraint()) {
2556       // In abbreviated templates, the type-constraints of invented template
2557       // type parameters are instantiated with the function type, invalidating
2558       // the TemplateParameterList which relied on the template type parameter
2559       // not having a type constraint. Recreate the TemplateParameterList with
2560       // the updated parameter list.
2561       TemplateParams = TemplateParameterList::Create(
2562           SemaRef.Context, TemplateParams->getTemplateLoc(),
2563           TemplateParams->getLAngleLoc(), TemplateParams->asArray(),
2564           TemplateParams->getRAngleLoc(), TemplateParams->getRequiresClause());
2565     }
2566   }
2567 
2568   NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
2569   if (QualifierLoc) {
2570     QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
2571                                                  TemplateArgs);
2572     if (!QualifierLoc)
2573       return nullptr;
2574   }
2575 
2576   DeclContext *DC = Owner;
2577   if (isFriend) {
2578     if (QualifierLoc) {
2579       CXXScopeSpec SS;
2580       SS.Adopt(QualifierLoc);
2581       DC = SemaRef.computeDeclContext(SS);
2582 
2583       if (DC && SemaRef.RequireCompleteDeclContext(SS, DC))
2584         return nullptr;
2585     } else {
2586       DC = SemaRef.FindInstantiatedContext(D->getLocation(),
2587                                            D->getDeclContext(),
2588                                            TemplateArgs);
2589     }
2590     if (!DC) return nullptr;
2591   }
2592 
2593   CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
2594   Expr *TrailingRequiresClause = D->getTrailingRequiresClause();
2595 
2596   DeclarationNameInfo NameInfo
2597     = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
2598 
2599   if (FunctionRewriteKind != RewriteKind::None)
2600     adjustForRewrite(FunctionRewriteKind, D, T, TInfo, NameInfo);
2601 
2602   // Build the instantiated method declaration.
2603   CXXMethodDecl *Method = nullptr;
2604 
2605   SourceLocation StartLoc = D->getInnerLocStart();
2606   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
2607     Method = CXXConstructorDecl::Create(
2608         SemaRef.Context, Record, StartLoc, NameInfo, T, TInfo,
2609         InstantiatedExplicitSpecifier, Constructor->UsesFPIntrin(),
2610         Constructor->isInlineSpecified(), false,
2611         Constructor->getConstexprKind(), InheritedConstructor(),
2612         TrailingRequiresClause);
2613     Method->setRangeEnd(Constructor->getEndLoc());
2614   } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
2615     Method = CXXDestructorDecl::Create(
2616         SemaRef.Context, Record, StartLoc, NameInfo, T, TInfo,
2617         Destructor->UsesFPIntrin(), Destructor->isInlineSpecified(), false,
2618         Destructor->getConstexprKind(), TrailingRequiresClause);
2619     Method->setIneligibleOrNotSelected(true);
2620     Method->setRangeEnd(Destructor->getEndLoc());
2621     Method->setDeclName(SemaRef.Context.DeclarationNames.getCXXDestructorName(
2622         SemaRef.Context.getCanonicalType(
2623             SemaRef.Context.getTypeDeclType(Record))));
2624   } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) {
2625     Method = CXXConversionDecl::Create(
2626         SemaRef.Context, Record, StartLoc, NameInfo, T, TInfo,
2627         Conversion->UsesFPIntrin(), Conversion->isInlineSpecified(),
2628         InstantiatedExplicitSpecifier, Conversion->getConstexprKind(),
2629         Conversion->getEndLoc(), TrailingRequiresClause);
2630   } else {
2631     StorageClass SC = D->isStatic() ? SC_Static : SC_None;
2632     Method = CXXMethodDecl::Create(
2633         SemaRef.Context, Record, StartLoc, NameInfo, T, TInfo, SC,
2634         D->UsesFPIntrin(), D->isInlineSpecified(), D->getConstexprKind(),
2635         D->getEndLoc(), TrailingRequiresClause);
2636   }
2637 
2638   if (D->isInlined())
2639     Method->setImplicitlyInline();
2640 
2641   if (QualifierLoc)
2642     Method->setQualifierInfo(QualifierLoc);
2643 
2644   if (TemplateParams) {
2645     // Our resulting instantiation is actually a function template, since we
2646     // are substituting only the outer template parameters. For example, given
2647     //
2648     //   template<typename T>
2649     //   struct X {
2650     //     template<typename U> void f(T, U);
2651     //   };
2652     //
2653     //   X<int> x;
2654     //
2655     // We are instantiating the member template "f" within X<int>, which means
2656     // substituting int for T, but leaving "f" as a member function template.
2657     // Build the function template itself.
2658     FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Record,
2659                                                     Method->getLocation(),
2660                                                     Method->getDeclName(),
2661                                                     TemplateParams, Method);
2662     if (isFriend) {
2663       FunctionTemplate->setLexicalDeclContext(Owner);
2664       FunctionTemplate->setObjectOfFriendDecl();
2665     } else if (D->isOutOfLine())
2666       FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
2667     Method->setDescribedFunctionTemplate(FunctionTemplate);
2668   } else if (FunctionTemplate) {
2669     // Record this function template specialization.
2670     ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
2671     Method->setFunctionTemplateSpecialization(FunctionTemplate,
2672                          TemplateArgumentList::CreateCopy(SemaRef.Context,
2673                                                           Innermost),
2674                                               /*InsertPos=*/nullptr);
2675   } else if (!isFriend && FunctionRewriteKind == RewriteKind::None) {
2676     // Record that this is an instantiation of a member function.
2677     Method->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
2678   }
2679 
2680   // If we are instantiating a member function defined
2681   // out-of-line, the instantiation will have the same lexical
2682   // context (which will be a namespace scope) as the template.
2683   if (isFriend) {
2684     if (NumTempParamLists)
2685       Method->setTemplateParameterListsInfo(
2686           SemaRef.Context,
2687           llvm::ArrayRef(TempParamLists.data(), NumTempParamLists));
2688 
2689     Method->setLexicalDeclContext(Owner);
2690     Method->setObjectOfFriendDecl();
2691   } else if (D->isOutOfLine())
2692     Method->setLexicalDeclContext(D->getLexicalDeclContext());
2693 
2694   // Attach the parameters
2695   for (unsigned P = 0; P < Params.size(); ++P)
2696     Params[P]->setOwningFunction(Method);
2697   Method->setParams(Params);
2698 
2699   if (InitMethodInstantiation(Method, D))
2700     Method->setInvalidDecl();
2701 
2702   LookupResult Previous(SemaRef, NameInfo, Sema::LookupOrdinaryName,
2703                         RedeclarationKind::ForExternalRedeclaration);
2704 
2705   bool IsExplicitSpecialization = false;
2706 
2707   // If the name of this function was written as a template-id, instantiate
2708   // the explicit template arguments.
2709   if (DependentFunctionTemplateSpecializationInfo *DFTSI =
2710           D->getDependentSpecializationInfo()) {
2711     // Instantiate the explicit template arguments.
2712     TemplateArgumentListInfo ExplicitArgs;
2713     if (const auto *ArgsWritten = DFTSI->TemplateArgumentsAsWritten) {
2714       ExplicitArgs.setLAngleLoc(ArgsWritten->getLAngleLoc());
2715       ExplicitArgs.setRAngleLoc(ArgsWritten->getRAngleLoc());
2716       if (SemaRef.SubstTemplateArguments(ArgsWritten->arguments(), TemplateArgs,
2717                                          ExplicitArgs))
2718         return nullptr;
2719     }
2720 
2721     // Map the candidates for the primary template to their instantiations.
2722     for (FunctionTemplateDecl *FTD : DFTSI->getCandidates()) {
2723       if (NamedDecl *ND =
2724               SemaRef.FindInstantiatedDecl(D->getLocation(), FTD, TemplateArgs))
2725         Previous.addDecl(ND);
2726       else
2727         return nullptr;
2728     }
2729 
2730     if (SemaRef.CheckFunctionTemplateSpecialization(
2731             Method, DFTSI->TemplateArgumentsAsWritten ? &ExplicitArgs : nullptr,
2732             Previous))
2733       Method->setInvalidDecl();
2734 
2735     IsExplicitSpecialization = true;
2736   } else if (const ASTTemplateArgumentListInfo *ArgsWritten =
2737                  D->getTemplateSpecializationArgsAsWritten()) {
2738     SemaRef.LookupQualifiedName(Previous, DC);
2739 
2740     TemplateArgumentListInfo ExplicitArgs(ArgsWritten->getLAngleLoc(),
2741                                           ArgsWritten->getRAngleLoc());
2742 
2743     if (SemaRef.SubstTemplateArguments(ArgsWritten->arguments(), TemplateArgs,
2744                                        ExplicitArgs))
2745       return nullptr;
2746 
2747     if (SemaRef.CheckFunctionTemplateSpecialization(Method,
2748                                                     &ExplicitArgs,
2749                                                     Previous))
2750       Method->setInvalidDecl();
2751 
2752     IsExplicitSpecialization = true;
2753   } else if (!FunctionTemplate || TemplateParams || isFriend) {
2754     SemaRef.LookupQualifiedName(Previous, Record);
2755 
2756     // In C++, the previous declaration we find might be a tag type
2757     // (class or enum). In this case, the new declaration will hide the
2758     // tag type. Note that this does not apply if we're declaring a
2759     // typedef (C++ [dcl.typedef]p4).
2760     if (Previous.isSingleTagDecl())
2761       Previous.clear();
2762   }
2763 
2764   // Per [temp.inst], default arguments in member functions of local classes
2765   // are instantiated along with the member function declaration. For example:
2766   //
2767   //   template<typename T>
2768   //   void ft() {
2769   //     struct lc {
2770   //       int operator()(int p = []{ return T::value; }());
2771   //     };
2772   //   }
2773   //   template void ft<int>(); // error: type 'int' cannot be used prior
2774   //                                      to '::'because it has no members
2775   //
2776   // The error is issued during instantiation of ft<int>()::lc::operator()
2777   // because substitution into the default argument fails; the default argument
2778   // is instantiated even though it is never used.
2779   if (D->isInLocalScopeForInstantiation()) {
2780     for (unsigned P = 0; P < Params.size(); ++P) {
2781       if (!Params[P]->hasDefaultArg())
2782         continue;
2783       if (SemaRef.SubstDefaultArgument(StartLoc, Params[P], TemplateArgs)) {
2784         // If substitution fails, the default argument is set to a
2785         // RecoveryExpr that wraps the uninstantiated default argument so
2786         // that downstream diagnostics are omitted.
2787         Expr *UninstExpr = Params[P]->getUninstantiatedDefaultArg();
2788         ExprResult ErrorResult = SemaRef.CreateRecoveryExpr(
2789             UninstExpr->getBeginLoc(), UninstExpr->getEndLoc(),
2790             { UninstExpr }, UninstExpr->getType());
2791         if (ErrorResult.isUsable())
2792           Params[P]->setDefaultArg(ErrorResult.get());
2793       }
2794     }
2795   }
2796 
2797   SemaRef.CheckFunctionDeclaration(nullptr, Method, Previous,
2798                                    IsExplicitSpecialization,
2799                                    Method->isThisDeclarationADefinition());
2800 
2801   if (D->isPureVirtual())
2802     SemaRef.CheckPureMethod(Method, SourceRange());
2803 
2804   // Propagate access.  For a non-friend declaration, the access is
2805   // whatever we're propagating from.  For a friend, it should be the
2806   // previous declaration we just found.
2807   if (isFriend && Method->getPreviousDecl())
2808     Method->setAccess(Method->getPreviousDecl()->getAccess());
2809   else
2810     Method->setAccess(D->getAccess());
2811   if (FunctionTemplate)
2812     FunctionTemplate->setAccess(Method->getAccess());
2813 
2814   SemaRef.CheckOverrideControl(Method);
2815 
2816   // If a function is defined as defaulted or deleted, mark it as such now.
2817   if (D->isExplicitlyDefaulted()) {
2818     if (SubstDefaultedFunction(Method, D))
2819       return nullptr;
2820   }
2821   if (D->isDeletedAsWritten())
2822     SemaRef.SetDeclDeleted(Method, Method->getLocation(),
2823                            D->getDeletedMessage());
2824 
2825   // If this is an explicit specialization, mark the implicitly-instantiated
2826   // template specialization as being an explicit specialization too.
2827   // FIXME: Is this necessary?
2828   if (IsExplicitSpecialization && !isFriend)
2829     SemaRef.CompleteMemberSpecialization(Method, Previous);
2830 
2831   // If the method is a special member function, we need to mark it as
2832   // ineligible so that Owner->addDecl() won't mark the class as non trivial.
2833   // At the end of the class instantiation, we calculate eligibility again and
2834   // then we adjust trivility if needed.
2835   // We need this check to happen only after the method parameters are set,
2836   // because being e.g. a copy constructor depends on the instantiated
2837   // arguments.
2838   if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Method)) {
2839     if (Constructor->isDefaultConstructor() ||
2840         Constructor->isCopyOrMoveConstructor())
2841       Method->setIneligibleOrNotSelected(true);
2842   } else if (Method->isCopyAssignmentOperator() ||
2843              Method->isMoveAssignmentOperator()) {
2844     Method->setIneligibleOrNotSelected(true);
2845   }
2846 
2847   // If there's a function template, let our caller handle it.
2848   if (FunctionTemplate) {
2849     // do nothing
2850 
2851   // Don't hide a (potentially) valid declaration with an invalid one.
2852   } else if (Method->isInvalidDecl() && !Previous.empty()) {
2853     // do nothing
2854 
2855   // Otherwise, check access to friends and make them visible.
2856   } else if (isFriend) {
2857     // We only need to re-check access for methods which we didn't
2858     // manage to match during parsing.
2859     if (!D->getPreviousDecl())
2860       SemaRef.CheckFriendAccess(Method);
2861 
2862     Record->makeDeclVisibleInContext(Method);
2863 
2864   // Otherwise, add the declaration.  We don't need to do this for
2865   // class-scope specializations because we'll have matched them with
2866   // the appropriate template.
2867   } else {
2868     Owner->addDecl(Method);
2869   }
2870 
2871   // PR17480: Honor the used attribute to instantiate member function
2872   // definitions
2873   if (Method->hasAttr<UsedAttr>()) {
2874     if (const auto *A = dyn_cast<CXXRecordDecl>(Owner)) {
2875       SourceLocation Loc;
2876       if (const MemberSpecializationInfo *MSInfo =
2877               A->getMemberSpecializationInfo())
2878         Loc = MSInfo->getPointOfInstantiation();
2879       else if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(A))
2880         Loc = Spec->getPointOfInstantiation();
2881       SemaRef.MarkFunctionReferenced(Loc, Method);
2882     }
2883   }
2884 
2885   return Method;
2886 }
2887 
VisitCXXConstructorDecl(CXXConstructorDecl * D)2888 Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
2889   return VisitCXXMethodDecl(D);
2890 }
2891 
VisitCXXDestructorDecl(CXXDestructorDecl * D)2892 Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
2893   return VisitCXXMethodDecl(D);
2894 }
2895 
VisitCXXConversionDecl(CXXConversionDecl * D)2896 Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
2897   return VisitCXXMethodDecl(D);
2898 }
2899 
VisitParmVarDecl(ParmVarDecl * D)2900 Decl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
2901   return SemaRef.SubstParmVarDecl(D, TemplateArgs, /*indexAdjustment*/ 0,
2902                                   std::nullopt,
2903                                   /*ExpectParameterPack=*/false);
2904 }
2905 
VisitTemplateTypeParmDecl(TemplateTypeParmDecl * D)2906 Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl(
2907                                                     TemplateTypeParmDecl *D) {
2908   assert(D->getTypeForDecl()->isTemplateTypeParmType());
2909 
2910   std::optional<unsigned> NumExpanded;
2911 
2912   if (const TypeConstraint *TC = D->getTypeConstraint()) {
2913     if (D->isPackExpansion() && !D->isExpandedParameterPack()) {
2914       assert(TC->getTemplateArgsAsWritten() &&
2915              "type parameter can only be an expansion when explicit arguments "
2916              "are specified");
2917       // The template type parameter pack's type is a pack expansion of types.
2918       // Determine whether we need to expand this parameter pack into separate
2919       // types.
2920       SmallVector<UnexpandedParameterPack, 2> Unexpanded;
2921       for (auto &ArgLoc : TC->getTemplateArgsAsWritten()->arguments())
2922         SemaRef.collectUnexpandedParameterPacks(ArgLoc, Unexpanded);
2923 
2924       // Determine whether the set of unexpanded parameter packs can and should
2925       // be expanded.
2926       bool Expand = true;
2927       bool RetainExpansion = false;
2928       if (SemaRef.CheckParameterPacksForExpansion(
2929               cast<CXXFoldExpr>(TC->getImmediatelyDeclaredConstraint())
2930                   ->getEllipsisLoc(),
2931               SourceRange(TC->getConceptNameLoc(),
2932                           TC->hasExplicitTemplateArgs() ?
2933                           TC->getTemplateArgsAsWritten()->getRAngleLoc() :
2934                           TC->getConceptNameInfo().getEndLoc()),
2935               Unexpanded, TemplateArgs, Expand, RetainExpansion, NumExpanded))
2936         return nullptr;
2937     }
2938   }
2939 
2940   TemplateTypeParmDecl *Inst = TemplateTypeParmDecl::Create(
2941       SemaRef.Context, Owner, D->getBeginLoc(), D->getLocation(),
2942       D->getDepth() - TemplateArgs.getNumSubstitutedLevels(), D->getIndex(),
2943       D->getIdentifier(), D->wasDeclaredWithTypename(), D->isParameterPack(),
2944       D->hasTypeConstraint(), NumExpanded);
2945 
2946   Inst->setAccess(AS_public);
2947   Inst->setImplicit(D->isImplicit());
2948   if (auto *TC = D->getTypeConstraint()) {
2949     if (!D->isImplicit()) {
2950       // Invented template parameter type constraints will be instantiated
2951       // with the corresponding auto-typed parameter as it might reference
2952       // other parameters.
2953       if (SemaRef.SubstTypeConstraint(Inst, TC, TemplateArgs,
2954                                       EvaluateConstraints))
2955         return nullptr;
2956     }
2957   }
2958   if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited()) {
2959     TemplateArgumentLoc Output;
2960     if (!SemaRef.SubstTemplateArgument(D->getDefaultArgument(), TemplateArgs,
2961                                        Output))
2962       Inst->setDefaultArgument(SemaRef.getASTContext(), Output);
2963   }
2964 
2965   // Introduce this template parameter's instantiation into the instantiation
2966   // scope.
2967   SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst);
2968 
2969   return Inst;
2970 }
2971 
VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl * D)2972 Decl *TemplateDeclInstantiator::VisitNonTypeTemplateParmDecl(
2973                                                  NonTypeTemplateParmDecl *D) {
2974   // Substitute into the type of the non-type template parameter.
2975   TypeLoc TL = D->getTypeSourceInfo()->getTypeLoc();
2976   SmallVector<TypeSourceInfo *, 4> ExpandedParameterPackTypesAsWritten;
2977   SmallVector<QualType, 4> ExpandedParameterPackTypes;
2978   bool IsExpandedParameterPack = false;
2979   TypeSourceInfo *DI;
2980   QualType T;
2981   bool Invalid = false;
2982 
2983   if (D->isExpandedParameterPack()) {
2984     // The non-type template parameter pack is an already-expanded pack
2985     // expansion of types. Substitute into each of the expanded types.
2986     ExpandedParameterPackTypes.reserve(D->getNumExpansionTypes());
2987     ExpandedParameterPackTypesAsWritten.reserve(D->getNumExpansionTypes());
2988     for (unsigned I = 0, N = D->getNumExpansionTypes(); I != N; ++I) {
2989       TypeSourceInfo *NewDI =
2990           SemaRef.SubstType(D->getExpansionTypeSourceInfo(I), TemplateArgs,
2991                             D->getLocation(), D->getDeclName());
2992       if (!NewDI)
2993         return nullptr;
2994 
2995       QualType NewT =
2996           SemaRef.CheckNonTypeTemplateParameterType(NewDI, D->getLocation());
2997       if (NewT.isNull())
2998         return nullptr;
2999 
3000       ExpandedParameterPackTypesAsWritten.push_back(NewDI);
3001       ExpandedParameterPackTypes.push_back(NewT);
3002     }
3003 
3004     IsExpandedParameterPack = true;
3005     DI = D->getTypeSourceInfo();
3006     T = DI->getType();
3007   } else if (D->isPackExpansion()) {
3008     // The non-type template parameter pack's type is a pack expansion of types.
3009     // Determine whether we need to expand this parameter pack into separate
3010     // types.
3011     PackExpansionTypeLoc Expansion = TL.castAs<PackExpansionTypeLoc>();
3012     TypeLoc Pattern = Expansion.getPatternLoc();
3013     SmallVector<UnexpandedParameterPack, 2> Unexpanded;
3014     SemaRef.collectUnexpandedParameterPacks(Pattern, Unexpanded);
3015 
3016     // Determine whether the set of unexpanded parameter packs can and should
3017     // be expanded.
3018     bool Expand = true;
3019     bool RetainExpansion = false;
3020     std::optional<unsigned> OrigNumExpansions =
3021         Expansion.getTypePtr()->getNumExpansions();
3022     std::optional<unsigned> NumExpansions = OrigNumExpansions;
3023     if (SemaRef.CheckParameterPacksForExpansion(Expansion.getEllipsisLoc(),
3024                                                 Pattern.getSourceRange(),
3025                                                 Unexpanded,
3026                                                 TemplateArgs,
3027                                                 Expand, RetainExpansion,
3028                                                 NumExpansions))
3029       return nullptr;
3030 
3031     if (Expand) {
3032       for (unsigned I = 0; I != *NumExpansions; ++I) {
3033         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
3034         TypeSourceInfo *NewDI = SemaRef.SubstType(Pattern, TemplateArgs,
3035                                                   D->getLocation(),
3036                                                   D->getDeclName());
3037         if (!NewDI)
3038           return nullptr;
3039 
3040         QualType NewT =
3041             SemaRef.CheckNonTypeTemplateParameterType(NewDI, D->getLocation());
3042         if (NewT.isNull())
3043           return nullptr;
3044 
3045         ExpandedParameterPackTypesAsWritten.push_back(NewDI);
3046         ExpandedParameterPackTypes.push_back(NewT);
3047       }
3048 
3049       // Note that we have an expanded parameter pack. The "type" of this
3050       // expanded parameter pack is the original expansion type, but callers
3051       // will end up using the expanded parameter pack types for type-checking.
3052       IsExpandedParameterPack = true;
3053       DI = D->getTypeSourceInfo();
3054       T = DI->getType();
3055     } else {
3056       // We cannot fully expand the pack expansion now, so substitute into the
3057       // pattern and create a new pack expansion type.
3058       Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
3059       TypeSourceInfo *NewPattern = SemaRef.SubstType(Pattern, TemplateArgs,
3060                                                      D->getLocation(),
3061                                                      D->getDeclName());
3062       if (!NewPattern)
3063         return nullptr;
3064 
3065       SemaRef.CheckNonTypeTemplateParameterType(NewPattern, D->getLocation());
3066       DI = SemaRef.CheckPackExpansion(NewPattern, Expansion.getEllipsisLoc(),
3067                                       NumExpansions);
3068       if (!DI)
3069         return nullptr;
3070 
3071       T = DI->getType();
3072     }
3073   } else {
3074     // Simple case: substitution into a parameter that is not a parameter pack.
3075     DI = SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs,
3076                            D->getLocation(), D->getDeclName());
3077     if (!DI)
3078       return nullptr;
3079 
3080     // Check that this type is acceptable for a non-type template parameter.
3081     T = SemaRef.CheckNonTypeTemplateParameterType(DI, D->getLocation());
3082     if (T.isNull()) {
3083       T = SemaRef.Context.IntTy;
3084       Invalid = true;
3085     }
3086   }
3087 
3088   NonTypeTemplateParmDecl *Param;
3089   if (IsExpandedParameterPack)
3090     Param = NonTypeTemplateParmDecl::Create(
3091         SemaRef.Context, Owner, D->getInnerLocStart(), D->getLocation(),
3092         D->getDepth() - TemplateArgs.getNumSubstitutedLevels(),
3093         D->getPosition(), D->getIdentifier(), T, DI, ExpandedParameterPackTypes,
3094         ExpandedParameterPackTypesAsWritten);
3095   else
3096     Param = NonTypeTemplateParmDecl::Create(
3097         SemaRef.Context, Owner, D->getInnerLocStart(), D->getLocation(),
3098         D->getDepth() - TemplateArgs.getNumSubstitutedLevels(),
3099         D->getPosition(), D->getIdentifier(), T, D->isParameterPack(), DI);
3100 
3101   if (AutoTypeLoc AutoLoc = DI->getTypeLoc().getContainedAutoTypeLoc())
3102     if (AutoLoc.isConstrained()) {
3103       SourceLocation EllipsisLoc;
3104       if (IsExpandedParameterPack)
3105         EllipsisLoc =
3106             DI->getTypeLoc().getAs<PackExpansionTypeLoc>().getEllipsisLoc();
3107       else if (auto *Constraint = dyn_cast_if_present<CXXFoldExpr>(
3108                    D->getPlaceholderTypeConstraint()))
3109         EllipsisLoc = Constraint->getEllipsisLoc();
3110       // Note: We attach the uninstantiated constriant here, so that it can be
3111       // instantiated relative to the top level, like all our other
3112       // constraints.
3113       if (SemaRef.AttachTypeConstraint(AutoLoc, /*NewConstrainedParm=*/Param,
3114                                        /*OrigConstrainedParm=*/D, EllipsisLoc))
3115         Invalid = true;
3116     }
3117 
3118   Param->setAccess(AS_public);
3119   Param->setImplicit(D->isImplicit());
3120   if (Invalid)
3121     Param->setInvalidDecl();
3122 
3123   if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited()) {
3124     EnterExpressionEvaluationContext ConstantEvaluated(
3125         SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
3126     TemplateArgumentLoc Result;
3127     if (!SemaRef.SubstTemplateArgument(D->getDefaultArgument(), TemplateArgs,
3128                                        Result))
3129       Param->setDefaultArgument(SemaRef.Context, Result);
3130   }
3131 
3132   // Introduce this template parameter's instantiation into the instantiation
3133   // scope.
3134   SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
3135   return Param;
3136 }
3137 
collectUnexpandedParameterPacks(Sema & S,TemplateParameterList * Params,SmallVectorImpl<UnexpandedParameterPack> & Unexpanded)3138 static void collectUnexpandedParameterPacks(
3139     Sema &S,
3140     TemplateParameterList *Params,
3141     SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
3142   for (const auto &P : *Params) {
3143     if (P->isTemplateParameterPack())
3144       continue;
3145     if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P))
3146       S.collectUnexpandedParameterPacks(NTTP->getTypeSourceInfo()->getTypeLoc(),
3147                                         Unexpanded);
3148     if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(P))
3149       collectUnexpandedParameterPacks(S, TTP->getTemplateParameters(),
3150                                       Unexpanded);
3151   }
3152 }
3153 
3154 Decl *
VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl * D)3155 TemplateDeclInstantiator::VisitTemplateTemplateParmDecl(
3156                                                   TemplateTemplateParmDecl *D) {
3157   // Instantiate the template parameter list of the template template parameter.
3158   TemplateParameterList *TempParams = D->getTemplateParameters();
3159   TemplateParameterList *InstParams;
3160   SmallVector<TemplateParameterList*, 8> ExpandedParams;
3161 
3162   bool IsExpandedParameterPack = false;
3163 
3164   if (D->isExpandedParameterPack()) {
3165     // The template template parameter pack is an already-expanded pack
3166     // expansion of template parameters. Substitute into each of the expanded
3167     // parameters.
3168     ExpandedParams.reserve(D->getNumExpansionTemplateParameters());
3169     for (unsigned I = 0, N = D->getNumExpansionTemplateParameters();
3170          I != N; ++I) {
3171       LocalInstantiationScope Scope(SemaRef);
3172       TemplateParameterList *Expansion =
3173         SubstTemplateParams(D->getExpansionTemplateParameters(I));
3174       if (!Expansion)
3175         return nullptr;
3176       ExpandedParams.push_back(Expansion);
3177     }
3178 
3179     IsExpandedParameterPack = true;
3180     InstParams = TempParams;
3181   } else if (D->isPackExpansion()) {
3182     // The template template parameter pack expands to a pack of template
3183     // template parameters. Determine whether we need to expand this parameter
3184     // pack into separate parameters.
3185     SmallVector<UnexpandedParameterPack, 2> Unexpanded;
3186     collectUnexpandedParameterPacks(SemaRef, D->getTemplateParameters(),
3187                                     Unexpanded);
3188 
3189     // Determine whether the set of unexpanded parameter packs can and should
3190     // be expanded.
3191     bool Expand = true;
3192     bool RetainExpansion = false;
3193     std::optional<unsigned> NumExpansions;
3194     if (SemaRef.CheckParameterPacksForExpansion(D->getLocation(),
3195                                                 TempParams->getSourceRange(),
3196                                                 Unexpanded,
3197                                                 TemplateArgs,
3198                                                 Expand, RetainExpansion,
3199                                                 NumExpansions))
3200       return nullptr;
3201 
3202     if (Expand) {
3203       for (unsigned I = 0; I != *NumExpansions; ++I) {
3204         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
3205         LocalInstantiationScope Scope(SemaRef);
3206         TemplateParameterList *Expansion = SubstTemplateParams(TempParams);
3207         if (!Expansion)
3208           return nullptr;
3209         ExpandedParams.push_back(Expansion);
3210       }
3211 
3212       // Note that we have an expanded parameter pack. The "type" of this
3213       // expanded parameter pack is the original expansion type, but callers
3214       // will end up using the expanded parameter pack types for type-checking.
3215       IsExpandedParameterPack = true;
3216       InstParams = TempParams;
3217     } else {
3218       // We cannot fully expand the pack expansion now, so just substitute
3219       // into the pattern.
3220       Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
3221 
3222       LocalInstantiationScope Scope(SemaRef);
3223       InstParams = SubstTemplateParams(TempParams);
3224       if (!InstParams)
3225         return nullptr;
3226     }
3227   } else {
3228     // Perform the actual substitution of template parameters within a new,
3229     // local instantiation scope.
3230     LocalInstantiationScope Scope(SemaRef);
3231     InstParams = SubstTemplateParams(TempParams);
3232     if (!InstParams)
3233       return nullptr;
3234   }
3235 
3236   // Build the template template parameter.
3237   TemplateTemplateParmDecl *Param;
3238   if (IsExpandedParameterPack)
3239     Param = TemplateTemplateParmDecl::Create(
3240         SemaRef.Context, Owner, D->getLocation(),
3241         D->getDepth() - TemplateArgs.getNumSubstitutedLevels(),
3242         D->getPosition(), D->getIdentifier(), D->wasDeclaredWithTypename(),
3243         InstParams, ExpandedParams);
3244   else
3245     Param = TemplateTemplateParmDecl::Create(
3246         SemaRef.Context, Owner, D->getLocation(),
3247         D->getDepth() - TemplateArgs.getNumSubstitutedLevels(),
3248         D->getPosition(), D->isParameterPack(), D->getIdentifier(),
3249         D->wasDeclaredWithTypename(), InstParams);
3250   if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited()) {
3251     NestedNameSpecifierLoc QualifierLoc =
3252         D->getDefaultArgument().getTemplateQualifierLoc();
3253     QualifierLoc =
3254         SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgs);
3255     TemplateName TName = SemaRef.SubstTemplateName(
3256         QualifierLoc, D->getDefaultArgument().getArgument().getAsTemplate(),
3257         D->getDefaultArgument().getTemplateNameLoc(), TemplateArgs);
3258     if (!TName.isNull())
3259       Param->setDefaultArgument(
3260           SemaRef.Context,
3261           TemplateArgumentLoc(SemaRef.Context, TemplateArgument(TName),
3262                               D->getDefaultArgument().getTemplateQualifierLoc(),
3263                               D->getDefaultArgument().getTemplateNameLoc()));
3264   }
3265   Param->setAccess(AS_public);
3266   Param->setImplicit(D->isImplicit());
3267 
3268   // Introduce this template parameter's instantiation into the instantiation
3269   // scope.
3270   SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
3271 
3272   return Param;
3273 }
3274 
VisitUsingDirectiveDecl(UsingDirectiveDecl * D)3275 Decl *TemplateDeclInstantiator::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
3276   // Using directives are never dependent (and never contain any types or
3277   // expressions), so they require no explicit instantiation work.
3278 
3279   UsingDirectiveDecl *Inst
3280     = UsingDirectiveDecl::Create(SemaRef.Context, Owner, D->getLocation(),
3281                                  D->getNamespaceKeyLocation(),
3282                                  D->getQualifierLoc(),
3283                                  D->getIdentLocation(),
3284                                  D->getNominatedNamespace(),
3285                                  D->getCommonAncestor());
3286 
3287   // Add the using directive to its declaration context
3288   // only if this is not a function or method.
3289   if (!Owner->isFunctionOrMethod())
3290     Owner->addDecl(Inst);
3291 
3292   return Inst;
3293 }
3294 
VisitBaseUsingDecls(BaseUsingDecl * D,BaseUsingDecl * Inst,LookupResult * Lookup)3295 Decl *TemplateDeclInstantiator::VisitBaseUsingDecls(BaseUsingDecl *D,
3296                                                     BaseUsingDecl *Inst,
3297                                                     LookupResult *Lookup) {
3298 
3299   bool isFunctionScope = Owner->isFunctionOrMethod();
3300 
3301   for (auto *Shadow : D->shadows()) {
3302     // FIXME: UsingShadowDecl doesn't preserve its immediate target, so
3303     // reconstruct it in the case where it matters. Hm, can we extract it from
3304     // the DeclSpec when parsing and save it in the UsingDecl itself?
3305     NamedDecl *OldTarget = Shadow->getTargetDecl();
3306     if (auto *CUSD = dyn_cast<ConstructorUsingShadowDecl>(Shadow))
3307       if (auto *BaseShadow = CUSD->getNominatedBaseClassShadowDecl())
3308         OldTarget = BaseShadow;
3309 
3310     NamedDecl *InstTarget = nullptr;
3311     if (auto *EmptyD =
3312             dyn_cast<UnresolvedUsingIfExistsDecl>(Shadow->getTargetDecl())) {
3313       InstTarget = UnresolvedUsingIfExistsDecl::Create(
3314           SemaRef.Context, Owner, EmptyD->getLocation(), EmptyD->getDeclName());
3315     } else {
3316       InstTarget = cast_or_null<NamedDecl>(SemaRef.FindInstantiatedDecl(
3317           Shadow->getLocation(), OldTarget, TemplateArgs));
3318     }
3319     if (!InstTarget)
3320       return nullptr;
3321 
3322     UsingShadowDecl *PrevDecl = nullptr;
3323     if (Lookup &&
3324         SemaRef.CheckUsingShadowDecl(Inst, InstTarget, *Lookup, PrevDecl))
3325       continue;
3326 
3327     if (UsingShadowDecl *OldPrev = getPreviousDeclForInstantiation(Shadow))
3328       PrevDecl = cast_or_null<UsingShadowDecl>(SemaRef.FindInstantiatedDecl(
3329           Shadow->getLocation(), OldPrev, TemplateArgs));
3330 
3331     UsingShadowDecl *InstShadow = SemaRef.BuildUsingShadowDecl(
3332         /*Scope*/ nullptr, Inst, InstTarget, PrevDecl);
3333     SemaRef.Context.setInstantiatedFromUsingShadowDecl(InstShadow, Shadow);
3334 
3335     if (isFunctionScope)
3336       SemaRef.CurrentInstantiationScope->InstantiatedLocal(Shadow, InstShadow);
3337   }
3338 
3339   return Inst;
3340 }
3341 
VisitUsingDecl(UsingDecl * D)3342 Decl *TemplateDeclInstantiator::VisitUsingDecl(UsingDecl *D) {
3343 
3344   // The nested name specifier may be dependent, for example
3345   //     template <typename T> struct t {
3346   //       struct s1 { T f1(); };
3347   //       struct s2 : s1 { using s1::f1; };
3348   //     };
3349   //     template struct t<int>;
3350   // Here, in using s1::f1, s1 refers to t<T>::s1;
3351   // we need to substitute for t<int>::s1.
3352   NestedNameSpecifierLoc QualifierLoc
3353     = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
3354                                           TemplateArgs);
3355   if (!QualifierLoc)
3356     return nullptr;
3357 
3358   // For an inheriting constructor declaration, the name of the using
3359   // declaration is the name of a constructor in this class, not in the
3360   // base class.
3361   DeclarationNameInfo NameInfo = D->getNameInfo();
3362   if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName)
3363     if (auto *RD = dyn_cast<CXXRecordDecl>(SemaRef.CurContext))
3364       NameInfo.setName(SemaRef.Context.DeclarationNames.getCXXConstructorName(
3365           SemaRef.Context.getCanonicalType(SemaRef.Context.getRecordType(RD))));
3366 
3367   // We only need to do redeclaration lookups if we're in a class scope (in
3368   // fact, it's not really even possible in non-class scopes).
3369   bool CheckRedeclaration = Owner->isRecord();
3370   LookupResult Prev(SemaRef, NameInfo, Sema::LookupUsingDeclName,
3371                     RedeclarationKind::ForVisibleRedeclaration);
3372 
3373   UsingDecl *NewUD = UsingDecl::Create(SemaRef.Context, Owner,
3374                                        D->getUsingLoc(),
3375                                        QualifierLoc,
3376                                        NameInfo,
3377                                        D->hasTypename());
3378 
3379   CXXScopeSpec SS;
3380   SS.Adopt(QualifierLoc);
3381   if (CheckRedeclaration) {
3382     Prev.setHideTags(false);
3383     SemaRef.LookupQualifiedName(Prev, Owner);
3384 
3385     // Check for invalid redeclarations.
3386     if (SemaRef.CheckUsingDeclRedeclaration(D->getUsingLoc(),
3387                                             D->hasTypename(), SS,
3388                                             D->getLocation(), Prev))
3389       NewUD->setInvalidDecl();
3390   }
3391 
3392   if (!NewUD->isInvalidDecl() &&
3393       SemaRef.CheckUsingDeclQualifier(D->getUsingLoc(), D->hasTypename(), SS,
3394                                       NameInfo, D->getLocation(), nullptr, D))
3395     NewUD->setInvalidDecl();
3396 
3397   SemaRef.Context.setInstantiatedFromUsingDecl(NewUD, D);
3398   NewUD->setAccess(D->getAccess());
3399   Owner->addDecl(NewUD);
3400 
3401   // Don't process the shadow decls for an invalid decl.
3402   if (NewUD->isInvalidDecl())
3403     return NewUD;
3404 
3405   // If the using scope was dependent, or we had dependent bases, we need to
3406   // recheck the inheritance
3407   if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName)
3408     SemaRef.CheckInheritingConstructorUsingDecl(NewUD);
3409 
3410   return VisitBaseUsingDecls(D, NewUD, CheckRedeclaration ? &Prev : nullptr);
3411 }
3412 
VisitUsingEnumDecl(UsingEnumDecl * D)3413 Decl *TemplateDeclInstantiator::VisitUsingEnumDecl(UsingEnumDecl *D) {
3414   // Cannot be a dependent type, but still could be an instantiation
3415   EnumDecl *EnumD = cast_or_null<EnumDecl>(SemaRef.FindInstantiatedDecl(
3416       D->getLocation(), D->getEnumDecl(), TemplateArgs));
3417 
3418   if (SemaRef.RequireCompleteEnumDecl(EnumD, EnumD->getLocation()))
3419     return nullptr;
3420 
3421   TypeSourceInfo *TSI = SemaRef.SubstType(D->getEnumType(), TemplateArgs,
3422                                           D->getLocation(), D->getDeclName());
3423 
3424   if (!TSI)
3425     return nullptr;
3426 
3427   UsingEnumDecl *NewUD =
3428       UsingEnumDecl::Create(SemaRef.Context, Owner, D->getUsingLoc(),
3429                             D->getEnumLoc(), D->getLocation(), TSI);
3430 
3431   SemaRef.Context.setInstantiatedFromUsingEnumDecl(NewUD, D);
3432   NewUD->setAccess(D->getAccess());
3433   Owner->addDecl(NewUD);
3434 
3435   // Don't process the shadow decls for an invalid decl.
3436   if (NewUD->isInvalidDecl())
3437     return NewUD;
3438 
3439   // We don't have to recheck for duplication of the UsingEnumDecl itself, as it
3440   // cannot be dependent, and will therefore have been checked during template
3441   // definition.
3442 
3443   return VisitBaseUsingDecls(D, NewUD, nullptr);
3444 }
3445 
VisitUsingShadowDecl(UsingShadowDecl * D)3446 Decl *TemplateDeclInstantiator::VisitUsingShadowDecl(UsingShadowDecl *D) {
3447   // Ignore these;  we handle them in bulk when processing the UsingDecl.
3448   return nullptr;
3449 }
3450 
VisitConstructorUsingShadowDecl(ConstructorUsingShadowDecl * D)3451 Decl *TemplateDeclInstantiator::VisitConstructorUsingShadowDecl(
3452     ConstructorUsingShadowDecl *D) {
3453   // Ignore these;  we handle them in bulk when processing the UsingDecl.
3454   return nullptr;
3455 }
3456 
3457 template <typename T>
instantiateUnresolvedUsingDecl(T * D,bool InstantiatingPackElement)3458 Decl *TemplateDeclInstantiator::instantiateUnresolvedUsingDecl(
3459     T *D, bool InstantiatingPackElement) {
3460   // If this is a pack expansion, expand it now.
3461   if (D->isPackExpansion() && !InstantiatingPackElement) {
3462     SmallVector<UnexpandedParameterPack, 2> Unexpanded;
3463     SemaRef.collectUnexpandedParameterPacks(D->getQualifierLoc(), Unexpanded);
3464     SemaRef.collectUnexpandedParameterPacks(D->getNameInfo(), Unexpanded);
3465 
3466     // Determine whether the set of unexpanded parameter packs can and should
3467     // be expanded.
3468     bool Expand = true;
3469     bool RetainExpansion = false;
3470     std::optional<unsigned> NumExpansions;
3471     if (SemaRef.CheckParameterPacksForExpansion(
3472           D->getEllipsisLoc(), D->getSourceRange(), Unexpanded, TemplateArgs,
3473             Expand, RetainExpansion, NumExpansions))
3474       return nullptr;
3475 
3476     // This declaration cannot appear within a function template signature,
3477     // so we can't have a partial argument list for a parameter pack.
3478     assert(!RetainExpansion &&
3479            "should never need to retain an expansion for UsingPackDecl");
3480 
3481     if (!Expand) {
3482       // We cannot fully expand the pack expansion now, so substitute into the
3483       // pattern and create a new pack expansion.
3484       Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
3485       return instantiateUnresolvedUsingDecl(D, true);
3486     }
3487 
3488     // Within a function, we don't have any normal way to check for conflicts
3489     // between shadow declarations from different using declarations in the
3490     // same pack expansion, but this is always ill-formed because all expansions
3491     // must produce (conflicting) enumerators.
3492     //
3493     // Sadly we can't just reject this in the template definition because it
3494     // could be valid if the pack is empty or has exactly one expansion.
3495     if (D->getDeclContext()->isFunctionOrMethod() && *NumExpansions > 1) {
3496       SemaRef.Diag(D->getEllipsisLoc(),
3497                    diag::err_using_decl_redeclaration_expansion);
3498       return nullptr;
3499     }
3500 
3501     // Instantiate the slices of this pack and build a UsingPackDecl.
3502     SmallVector<NamedDecl*, 8> Expansions;
3503     for (unsigned I = 0; I != *NumExpansions; ++I) {
3504       Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
3505       Decl *Slice = instantiateUnresolvedUsingDecl(D, true);
3506       if (!Slice)
3507         return nullptr;
3508       // Note that we can still get unresolved using declarations here, if we
3509       // had arguments for all packs but the pattern also contained other
3510       // template arguments (this only happens during partial substitution, eg
3511       // into the body of a generic lambda in a function template).
3512       Expansions.push_back(cast<NamedDecl>(Slice));
3513     }
3514 
3515     auto *NewD = SemaRef.BuildUsingPackDecl(D, Expansions);
3516     if (isDeclWithinFunction(D))
3517       SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewD);
3518     return NewD;
3519   }
3520 
3521   UnresolvedUsingTypenameDecl *TD = dyn_cast<UnresolvedUsingTypenameDecl>(D);
3522   SourceLocation TypenameLoc = TD ? TD->getTypenameLoc() : SourceLocation();
3523 
3524   NestedNameSpecifierLoc QualifierLoc
3525     = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
3526                                           TemplateArgs);
3527   if (!QualifierLoc)
3528     return nullptr;
3529 
3530   CXXScopeSpec SS;
3531   SS.Adopt(QualifierLoc);
3532 
3533   DeclarationNameInfo NameInfo
3534     = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
3535 
3536   // Produce a pack expansion only if we're not instantiating a particular
3537   // slice of a pack expansion.
3538   bool InstantiatingSlice = D->getEllipsisLoc().isValid() &&
3539                             SemaRef.ArgumentPackSubstitutionIndex != -1;
3540   SourceLocation EllipsisLoc =
3541       InstantiatingSlice ? SourceLocation() : D->getEllipsisLoc();
3542 
3543   bool IsUsingIfExists = D->template hasAttr<UsingIfExistsAttr>();
3544   NamedDecl *UD = SemaRef.BuildUsingDeclaration(
3545       /*Scope*/ nullptr, D->getAccess(), D->getUsingLoc(),
3546       /*HasTypename*/ TD, TypenameLoc, SS, NameInfo, EllipsisLoc,
3547       ParsedAttributesView(),
3548       /*IsInstantiation*/ true, IsUsingIfExists);
3549   if (UD) {
3550     SemaRef.InstantiateAttrs(TemplateArgs, D, UD);
3551     SemaRef.Context.setInstantiatedFromUsingDecl(UD, D);
3552   }
3553 
3554   return UD;
3555 }
3556 
VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl * D)3557 Decl *TemplateDeclInstantiator::VisitUnresolvedUsingTypenameDecl(
3558     UnresolvedUsingTypenameDecl *D) {
3559   return instantiateUnresolvedUsingDecl(D);
3560 }
3561 
VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl * D)3562 Decl *TemplateDeclInstantiator::VisitUnresolvedUsingValueDecl(
3563     UnresolvedUsingValueDecl *D) {
3564   return instantiateUnresolvedUsingDecl(D);
3565 }
3566 
VisitUnresolvedUsingIfExistsDecl(UnresolvedUsingIfExistsDecl * D)3567 Decl *TemplateDeclInstantiator::VisitUnresolvedUsingIfExistsDecl(
3568     UnresolvedUsingIfExistsDecl *D) {
3569   llvm_unreachable("referring to unresolved decl out of UsingShadowDecl");
3570 }
3571 
VisitUsingPackDecl(UsingPackDecl * D)3572 Decl *TemplateDeclInstantiator::VisitUsingPackDecl(UsingPackDecl *D) {
3573   SmallVector<NamedDecl*, 8> Expansions;
3574   for (auto *UD : D->expansions()) {
3575     if (NamedDecl *NewUD =
3576             SemaRef.FindInstantiatedDecl(D->getLocation(), UD, TemplateArgs))
3577       Expansions.push_back(NewUD);
3578     else
3579       return nullptr;
3580   }
3581 
3582   auto *NewD = SemaRef.BuildUsingPackDecl(D, Expansions);
3583   if (isDeclWithinFunction(D))
3584     SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewD);
3585   return NewD;
3586 }
3587 
VisitOMPThreadPrivateDecl(OMPThreadPrivateDecl * D)3588 Decl *TemplateDeclInstantiator::VisitOMPThreadPrivateDecl(
3589                                      OMPThreadPrivateDecl *D) {
3590   SmallVector<Expr *, 5> Vars;
3591   for (auto *I : D->varlists()) {
3592     Expr *Var = SemaRef.SubstExpr(I, TemplateArgs).get();
3593     assert(isa<DeclRefExpr>(Var) && "threadprivate arg is not a DeclRefExpr");
3594     Vars.push_back(Var);
3595   }
3596 
3597   OMPThreadPrivateDecl *TD =
3598       SemaRef.OpenMP().CheckOMPThreadPrivateDecl(D->getLocation(), Vars);
3599 
3600   TD->setAccess(AS_public);
3601   Owner->addDecl(TD);
3602 
3603   return TD;
3604 }
3605 
VisitOMPAllocateDecl(OMPAllocateDecl * D)3606 Decl *TemplateDeclInstantiator::VisitOMPAllocateDecl(OMPAllocateDecl *D) {
3607   SmallVector<Expr *, 5> Vars;
3608   for (auto *I : D->varlists()) {
3609     Expr *Var = SemaRef.SubstExpr(I, TemplateArgs).get();
3610     assert(isa<DeclRefExpr>(Var) && "allocate arg is not a DeclRefExpr");
3611     Vars.push_back(Var);
3612   }
3613   SmallVector<OMPClause *, 4> Clauses;
3614   // Copy map clauses from the original mapper.
3615   for (OMPClause *C : D->clauselists()) {
3616     OMPClause *IC = nullptr;
3617     if (auto *AC = dyn_cast<OMPAllocatorClause>(C)) {
3618       ExprResult NewE = SemaRef.SubstExpr(AC->getAllocator(), TemplateArgs);
3619       if (!NewE.isUsable())
3620         continue;
3621       IC = SemaRef.OpenMP().ActOnOpenMPAllocatorClause(
3622           NewE.get(), AC->getBeginLoc(), AC->getLParenLoc(), AC->getEndLoc());
3623     } else if (auto *AC = dyn_cast<OMPAlignClause>(C)) {
3624       ExprResult NewE = SemaRef.SubstExpr(AC->getAlignment(), TemplateArgs);
3625       if (!NewE.isUsable())
3626         continue;
3627       IC = SemaRef.OpenMP().ActOnOpenMPAlignClause(
3628           NewE.get(), AC->getBeginLoc(), AC->getLParenLoc(), AC->getEndLoc());
3629       // If align clause value ends up being invalid, this can end up null.
3630       if (!IC)
3631         continue;
3632     }
3633     Clauses.push_back(IC);
3634   }
3635 
3636   Sema::DeclGroupPtrTy Res = SemaRef.OpenMP().ActOnOpenMPAllocateDirective(
3637       D->getLocation(), Vars, Clauses, Owner);
3638   if (Res.get().isNull())
3639     return nullptr;
3640   return Res.get().getSingleDecl();
3641 }
3642 
VisitOMPRequiresDecl(OMPRequiresDecl * D)3643 Decl *TemplateDeclInstantiator::VisitOMPRequiresDecl(OMPRequiresDecl *D) {
3644   llvm_unreachable(
3645       "Requires directive cannot be instantiated within a dependent context");
3646 }
3647 
VisitOMPDeclareReductionDecl(OMPDeclareReductionDecl * D)3648 Decl *TemplateDeclInstantiator::VisitOMPDeclareReductionDecl(
3649     OMPDeclareReductionDecl *D) {
3650   // Instantiate type and check if it is allowed.
3651   const bool RequiresInstantiation =
3652       D->getType()->isDependentType() ||
3653       D->getType()->isInstantiationDependentType() ||
3654       D->getType()->containsUnexpandedParameterPack();
3655   QualType SubstReductionType;
3656   if (RequiresInstantiation) {
3657     SubstReductionType = SemaRef.OpenMP().ActOnOpenMPDeclareReductionType(
3658         D->getLocation(),
3659         ParsedType::make(SemaRef.SubstType(
3660             D->getType(), TemplateArgs, D->getLocation(), DeclarationName())));
3661   } else {
3662     SubstReductionType = D->getType();
3663   }
3664   if (SubstReductionType.isNull())
3665     return nullptr;
3666   Expr *Combiner = D->getCombiner();
3667   Expr *Init = D->getInitializer();
3668   bool IsCorrect = true;
3669   // Create instantiated copy.
3670   std::pair<QualType, SourceLocation> ReductionTypes[] = {
3671       std::make_pair(SubstReductionType, D->getLocation())};
3672   auto *PrevDeclInScope = D->getPrevDeclInScope();
3673   if (PrevDeclInScope && !PrevDeclInScope->isInvalidDecl()) {
3674     PrevDeclInScope = cast<OMPDeclareReductionDecl>(
3675         SemaRef.CurrentInstantiationScope->findInstantiationOf(PrevDeclInScope)
3676             ->get<Decl *>());
3677   }
3678   auto DRD = SemaRef.OpenMP().ActOnOpenMPDeclareReductionDirectiveStart(
3679       /*S=*/nullptr, Owner, D->getDeclName(), ReductionTypes, D->getAccess(),
3680       PrevDeclInScope);
3681   auto *NewDRD = cast<OMPDeclareReductionDecl>(DRD.get().getSingleDecl());
3682   SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewDRD);
3683   Expr *SubstCombiner = nullptr;
3684   Expr *SubstInitializer = nullptr;
3685   // Combiners instantiation sequence.
3686   if (Combiner) {
3687     SemaRef.OpenMP().ActOnOpenMPDeclareReductionCombinerStart(
3688         /*S=*/nullptr, NewDRD);
3689     SemaRef.CurrentInstantiationScope->InstantiatedLocal(
3690         cast<DeclRefExpr>(D->getCombinerIn())->getDecl(),
3691         cast<DeclRefExpr>(NewDRD->getCombinerIn())->getDecl());
3692     SemaRef.CurrentInstantiationScope->InstantiatedLocal(
3693         cast<DeclRefExpr>(D->getCombinerOut())->getDecl(),
3694         cast<DeclRefExpr>(NewDRD->getCombinerOut())->getDecl());
3695     auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(Owner);
3696     Sema::CXXThisScopeRAII ThisScope(SemaRef, ThisContext, Qualifiers(),
3697                                      ThisContext);
3698     SubstCombiner = SemaRef.SubstExpr(Combiner, TemplateArgs).get();
3699     SemaRef.OpenMP().ActOnOpenMPDeclareReductionCombinerEnd(NewDRD,
3700                                                             SubstCombiner);
3701   }
3702   // Initializers instantiation sequence.
3703   if (Init) {
3704     VarDecl *OmpPrivParm =
3705         SemaRef.OpenMP().ActOnOpenMPDeclareReductionInitializerStart(
3706             /*S=*/nullptr, NewDRD);
3707     SemaRef.CurrentInstantiationScope->InstantiatedLocal(
3708         cast<DeclRefExpr>(D->getInitOrig())->getDecl(),
3709         cast<DeclRefExpr>(NewDRD->getInitOrig())->getDecl());
3710     SemaRef.CurrentInstantiationScope->InstantiatedLocal(
3711         cast<DeclRefExpr>(D->getInitPriv())->getDecl(),
3712         cast<DeclRefExpr>(NewDRD->getInitPriv())->getDecl());
3713     if (D->getInitializerKind() == OMPDeclareReductionInitKind::Call) {
3714       SubstInitializer = SemaRef.SubstExpr(Init, TemplateArgs).get();
3715     } else {
3716       auto *OldPrivParm =
3717           cast<VarDecl>(cast<DeclRefExpr>(D->getInitPriv())->getDecl());
3718       IsCorrect = IsCorrect && OldPrivParm->hasInit();
3719       if (IsCorrect)
3720         SemaRef.InstantiateVariableInitializer(OmpPrivParm, OldPrivParm,
3721                                                TemplateArgs);
3722     }
3723     SemaRef.OpenMP().ActOnOpenMPDeclareReductionInitializerEnd(
3724         NewDRD, SubstInitializer, OmpPrivParm);
3725   }
3726   IsCorrect = IsCorrect && SubstCombiner &&
3727               (!Init ||
3728                (D->getInitializerKind() == OMPDeclareReductionInitKind::Call &&
3729                 SubstInitializer) ||
3730                (D->getInitializerKind() != OMPDeclareReductionInitKind::Call &&
3731                 !SubstInitializer));
3732 
3733   (void)SemaRef.OpenMP().ActOnOpenMPDeclareReductionDirectiveEnd(
3734       /*S=*/nullptr, DRD, IsCorrect && !D->isInvalidDecl());
3735 
3736   return NewDRD;
3737 }
3738 
3739 Decl *
VisitOMPDeclareMapperDecl(OMPDeclareMapperDecl * D)3740 TemplateDeclInstantiator::VisitOMPDeclareMapperDecl(OMPDeclareMapperDecl *D) {
3741   // Instantiate type and check if it is allowed.
3742   const bool RequiresInstantiation =
3743       D->getType()->isDependentType() ||
3744       D->getType()->isInstantiationDependentType() ||
3745       D->getType()->containsUnexpandedParameterPack();
3746   QualType SubstMapperTy;
3747   DeclarationName VN = D->getVarName();
3748   if (RequiresInstantiation) {
3749     SubstMapperTy = SemaRef.OpenMP().ActOnOpenMPDeclareMapperType(
3750         D->getLocation(),
3751         ParsedType::make(SemaRef.SubstType(D->getType(), TemplateArgs,
3752                                            D->getLocation(), VN)));
3753   } else {
3754     SubstMapperTy = D->getType();
3755   }
3756   if (SubstMapperTy.isNull())
3757     return nullptr;
3758   // Create an instantiated copy of mapper.
3759   auto *PrevDeclInScope = D->getPrevDeclInScope();
3760   if (PrevDeclInScope && !PrevDeclInScope->isInvalidDecl()) {
3761     PrevDeclInScope = cast<OMPDeclareMapperDecl>(
3762         SemaRef.CurrentInstantiationScope->findInstantiationOf(PrevDeclInScope)
3763             ->get<Decl *>());
3764   }
3765   bool IsCorrect = true;
3766   SmallVector<OMPClause *, 6> Clauses;
3767   // Instantiate the mapper variable.
3768   DeclarationNameInfo DirName;
3769   SemaRef.OpenMP().StartOpenMPDSABlock(llvm::omp::OMPD_declare_mapper, DirName,
3770                                        /*S=*/nullptr,
3771                                        (*D->clauselist_begin())->getBeginLoc());
3772   ExprResult MapperVarRef =
3773       SemaRef.OpenMP().ActOnOpenMPDeclareMapperDirectiveVarDecl(
3774           /*S=*/nullptr, SubstMapperTy, D->getLocation(), VN);
3775   SemaRef.CurrentInstantiationScope->InstantiatedLocal(
3776       cast<DeclRefExpr>(D->getMapperVarRef())->getDecl(),
3777       cast<DeclRefExpr>(MapperVarRef.get())->getDecl());
3778   auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(Owner);
3779   Sema::CXXThisScopeRAII ThisScope(SemaRef, ThisContext, Qualifiers(),
3780                                    ThisContext);
3781   // Instantiate map clauses.
3782   for (OMPClause *C : D->clauselists()) {
3783     auto *OldC = cast<OMPMapClause>(C);
3784     SmallVector<Expr *, 4> NewVars;
3785     for (Expr *OE : OldC->varlists()) {
3786       Expr *NE = SemaRef.SubstExpr(OE, TemplateArgs).get();
3787       if (!NE) {
3788         IsCorrect = false;
3789         break;
3790       }
3791       NewVars.push_back(NE);
3792     }
3793     if (!IsCorrect)
3794       break;
3795     NestedNameSpecifierLoc NewQualifierLoc =
3796         SemaRef.SubstNestedNameSpecifierLoc(OldC->getMapperQualifierLoc(),
3797                                             TemplateArgs);
3798     CXXScopeSpec SS;
3799     SS.Adopt(NewQualifierLoc);
3800     DeclarationNameInfo NewNameInfo =
3801         SemaRef.SubstDeclarationNameInfo(OldC->getMapperIdInfo(), TemplateArgs);
3802     OMPVarListLocTy Locs(OldC->getBeginLoc(), OldC->getLParenLoc(),
3803                          OldC->getEndLoc());
3804     OMPClause *NewC = SemaRef.OpenMP().ActOnOpenMPMapClause(
3805         OldC->getIteratorModifier(), OldC->getMapTypeModifiers(),
3806         OldC->getMapTypeModifiersLoc(), SS, NewNameInfo, OldC->getMapType(),
3807         OldC->isImplicitMapType(), OldC->getMapLoc(), OldC->getColonLoc(),
3808         NewVars, Locs);
3809     Clauses.push_back(NewC);
3810   }
3811   SemaRef.OpenMP().EndOpenMPDSABlock(nullptr);
3812   if (!IsCorrect)
3813     return nullptr;
3814   Sema::DeclGroupPtrTy DG = SemaRef.OpenMP().ActOnOpenMPDeclareMapperDirective(
3815       /*S=*/nullptr, Owner, D->getDeclName(), SubstMapperTy, D->getLocation(),
3816       VN, D->getAccess(), MapperVarRef.get(), Clauses, PrevDeclInScope);
3817   Decl *NewDMD = DG.get().getSingleDecl();
3818   SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewDMD);
3819   return NewDMD;
3820 }
3821 
VisitOMPCapturedExprDecl(OMPCapturedExprDecl *)3822 Decl *TemplateDeclInstantiator::VisitOMPCapturedExprDecl(
3823     OMPCapturedExprDecl * /*D*/) {
3824   llvm_unreachable("Should not be met in templates");
3825 }
3826 
VisitFunctionDecl(FunctionDecl * D)3827 Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D) {
3828   return VisitFunctionDecl(D, nullptr);
3829 }
3830 
3831 Decl *
VisitCXXDeductionGuideDecl(CXXDeductionGuideDecl * D)3832 TemplateDeclInstantiator::VisitCXXDeductionGuideDecl(CXXDeductionGuideDecl *D) {
3833   Decl *Inst = VisitFunctionDecl(D, nullptr);
3834   if (Inst && !D->getDescribedFunctionTemplate())
3835     Owner->addDecl(Inst);
3836   return Inst;
3837 }
3838 
VisitCXXMethodDecl(CXXMethodDecl * D)3839 Decl *TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D) {
3840   return VisitCXXMethodDecl(D, nullptr);
3841 }
3842 
VisitRecordDecl(RecordDecl * D)3843 Decl *TemplateDeclInstantiator::VisitRecordDecl(RecordDecl *D) {
3844   llvm_unreachable("There are only CXXRecordDecls in C++");
3845 }
3846 
3847 Decl *
VisitClassTemplateSpecializationDecl(ClassTemplateSpecializationDecl * D)3848 TemplateDeclInstantiator::VisitClassTemplateSpecializationDecl(
3849     ClassTemplateSpecializationDecl *D) {
3850   // As a MS extension, we permit class-scope explicit specialization
3851   // of member class templates.
3852   ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
3853   assert(ClassTemplate->getDeclContext()->isRecord() &&
3854          D->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
3855          "can only instantiate an explicit specialization "
3856          "for a member class template");
3857 
3858   // Lookup the already-instantiated declaration in the instantiation
3859   // of the class template.
3860   ClassTemplateDecl *InstClassTemplate =
3861       cast_or_null<ClassTemplateDecl>(SemaRef.FindInstantiatedDecl(
3862           D->getLocation(), ClassTemplate, TemplateArgs));
3863   if (!InstClassTemplate)
3864     return nullptr;
3865 
3866   // Substitute into the template arguments of the class template explicit
3867   // specialization.
3868   TemplateArgumentListInfo InstTemplateArgs;
3869   if (const ASTTemplateArgumentListInfo *TemplateArgsInfo =
3870           D->getTemplateArgsAsWritten()) {
3871     InstTemplateArgs.setLAngleLoc(TemplateArgsInfo->getLAngleLoc());
3872     InstTemplateArgs.setRAngleLoc(TemplateArgsInfo->getRAngleLoc());
3873 
3874     if (SemaRef.SubstTemplateArguments(TemplateArgsInfo->arguments(),
3875                                        TemplateArgs, InstTemplateArgs))
3876       return nullptr;
3877   }
3878 
3879   // Check that the template argument list is well-formed for this
3880   // class template.
3881   SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
3882   if (SemaRef.CheckTemplateArgumentList(InstClassTemplate, D->getLocation(),
3883                                         InstTemplateArgs, false,
3884                                         SugaredConverted, CanonicalConverted,
3885                                         /*UpdateArgsWithConversions=*/true))
3886     return nullptr;
3887 
3888   // Figure out where to insert this class template explicit specialization
3889   // in the member template's set of class template explicit specializations.
3890   void *InsertPos = nullptr;
3891   ClassTemplateSpecializationDecl *PrevDecl =
3892       InstClassTemplate->findSpecialization(CanonicalConverted, InsertPos);
3893 
3894   // Check whether we've already seen a conflicting instantiation of this
3895   // declaration (for instance, if there was a prior implicit instantiation).
3896   bool Ignored;
3897   if (PrevDecl &&
3898       SemaRef.CheckSpecializationInstantiationRedecl(D->getLocation(),
3899                                                      D->getSpecializationKind(),
3900                                                      PrevDecl,
3901                                                      PrevDecl->getSpecializationKind(),
3902                                                      PrevDecl->getPointOfInstantiation(),
3903                                                      Ignored))
3904     return nullptr;
3905 
3906   // If PrevDecl was a definition and D is also a definition, diagnose.
3907   // This happens in cases like:
3908   //
3909   //   template<typename T, typename U>
3910   //   struct Outer {
3911   //     template<typename X> struct Inner;
3912   //     template<> struct Inner<T> {};
3913   //     template<> struct Inner<U> {};
3914   //   };
3915   //
3916   //   Outer<int, int> outer; // error: the explicit specializations of Inner
3917   //                          // have the same signature.
3918   if (PrevDecl && PrevDecl->getDefinition() &&
3919       D->isThisDeclarationADefinition()) {
3920     SemaRef.Diag(D->getLocation(), diag::err_redefinition) << PrevDecl;
3921     SemaRef.Diag(PrevDecl->getDefinition()->getLocation(),
3922                  diag::note_previous_definition);
3923     return nullptr;
3924   }
3925 
3926   // Create the class template partial specialization declaration.
3927   ClassTemplateSpecializationDecl *InstD =
3928       ClassTemplateSpecializationDecl::Create(
3929           SemaRef.Context, D->getTagKind(), Owner, D->getBeginLoc(),
3930           D->getLocation(), InstClassTemplate, CanonicalConverted, PrevDecl);
3931   InstD->setTemplateArgsAsWritten(InstTemplateArgs);
3932 
3933   // Add this partial specialization to the set of class template partial
3934   // specializations.
3935   if (!PrevDecl)
3936     InstClassTemplate->AddSpecialization(InstD, InsertPos);
3937 
3938   // Substitute the nested name specifier, if any.
3939   if (SubstQualifier(D, InstD))
3940     return nullptr;
3941 
3942   InstD->setAccess(D->getAccess());
3943   InstD->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
3944   InstD->setSpecializationKind(D->getSpecializationKind());
3945   InstD->setExternKeywordLoc(D->getExternKeywordLoc());
3946   InstD->setTemplateKeywordLoc(D->getTemplateKeywordLoc());
3947 
3948   Owner->addDecl(InstD);
3949 
3950   // Instantiate the members of the class-scope explicit specialization eagerly.
3951   // We don't have support for lazy instantiation of an explicit specialization
3952   // yet, and MSVC eagerly instantiates in this case.
3953   // FIXME: This is wrong in standard C++.
3954   if (D->isThisDeclarationADefinition() &&
3955       SemaRef.InstantiateClass(D->getLocation(), InstD, D, TemplateArgs,
3956                                TSK_ImplicitInstantiation,
3957                                /*Complain=*/true))
3958     return nullptr;
3959 
3960   return InstD;
3961 }
3962 
VisitVarTemplateSpecializationDecl(VarTemplateSpecializationDecl * D)3963 Decl *TemplateDeclInstantiator::VisitVarTemplateSpecializationDecl(
3964     VarTemplateSpecializationDecl *D) {
3965 
3966   TemplateArgumentListInfo VarTemplateArgsInfo;
3967   VarTemplateDecl *VarTemplate = D->getSpecializedTemplate();
3968   assert(VarTemplate &&
3969          "A template specialization without specialized template?");
3970 
3971   VarTemplateDecl *InstVarTemplate =
3972       cast_or_null<VarTemplateDecl>(SemaRef.FindInstantiatedDecl(
3973           D->getLocation(), VarTemplate, TemplateArgs));
3974   if (!InstVarTemplate)
3975     return nullptr;
3976 
3977   // Substitute the current template arguments.
3978   if (const ASTTemplateArgumentListInfo *TemplateArgsInfo =
3979           D->getTemplateArgsAsWritten()) {
3980     VarTemplateArgsInfo.setLAngleLoc(TemplateArgsInfo->getLAngleLoc());
3981     VarTemplateArgsInfo.setRAngleLoc(TemplateArgsInfo->getRAngleLoc());
3982 
3983     if (SemaRef.SubstTemplateArguments(TemplateArgsInfo->arguments(),
3984                                        TemplateArgs, VarTemplateArgsInfo))
3985       return nullptr;
3986   }
3987 
3988   // Check that the template argument list is well-formed for this template.
3989   SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
3990   if (SemaRef.CheckTemplateArgumentList(InstVarTemplate, D->getLocation(),
3991                                         VarTemplateArgsInfo, false,
3992                                         SugaredConverted, CanonicalConverted,
3993                                         /*UpdateArgsWithConversions=*/true))
3994     return nullptr;
3995 
3996   // Check whether we've already seen a declaration of this specialization.
3997   void *InsertPos = nullptr;
3998   VarTemplateSpecializationDecl *PrevDecl =
3999       InstVarTemplate->findSpecialization(CanonicalConverted, InsertPos);
4000 
4001   // Check whether we've already seen a conflicting instantiation of this
4002   // declaration (for instance, if there was a prior implicit instantiation).
4003   bool Ignored;
4004   if (PrevDecl && SemaRef.CheckSpecializationInstantiationRedecl(
4005                       D->getLocation(), D->getSpecializationKind(), PrevDecl,
4006                       PrevDecl->getSpecializationKind(),
4007                       PrevDecl->getPointOfInstantiation(), Ignored))
4008     return nullptr;
4009 
4010   return VisitVarTemplateSpecializationDecl(
4011       InstVarTemplate, D, VarTemplateArgsInfo, CanonicalConverted, PrevDecl);
4012 }
4013 
VisitVarTemplateSpecializationDecl(VarTemplateDecl * VarTemplate,VarDecl * D,const TemplateArgumentListInfo & TemplateArgsInfo,ArrayRef<TemplateArgument> Converted,VarTemplateSpecializationDecl * PrevDecl)4014 Decl *TemplateDeclInstantiator::VisitVarTemplateSpecializationDecl(
4015     VarTemplateDecl *VarTemplate, VarDecl *D,
4016     const TemplateArgumentListInfo &TemplateArgsInfo,
4017     ArrayRef<TemplateArgument> Converted,
4018     VarTemplateSpecializationDecl *PrevDecl) {
4019 
4020   // Do substitution on the type of the declaration
4021   TypeSourceInfo *DI =
4022       SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs,
4023                         D->getTypeSpecStartLoc(), D->getDeclName());
4024   if (!DI)
4025     return nullptr;
4026 
4027   if (DI->getType()->isFunctionType()) {
4028     SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function)
4029         << D->isStaticDataMember() << DI->getType();
4030     return nullptr;
4031   }
4032 
4033   // Build the instantiated declaration
4034   VarTemplateSpecializationDecl *Var = VarTemplateSpecializationDecl::Create(
4035       SemaRef.Context, Owner, D->getInnerLocStart(), D->getLocation(),
4036       VarTemplate, DI->getType(), DI, D->getStorageClass(), Converted);
4037   Var->setTemplateArgsAsWritten(TemplateArgsInfo);
4038   if (!PrevDecl) {
4039     void *InsertPos = nullptr;
4040     VarTemplate->findSpecialization(Converted, InsertPos);
4041     VarTemplate->AddSpecialization(Var, InsertPos);
4042   }
4043 
4044   if (SemaRef.getLangOpts().OpenCL)
4045     SemaRef.deduceOpenCLAddressSpace(Var);
4046 
4047   // Substitute the nested name specifier, if any.
4048   if (SubstQualifier(D, Var))
4049     return nullptr;
4050 
4051   SemaRef.BuildVariableInstantiation(Var, D, TemplateArgs, LateAttrs, Owner,
4052                                      StartingScope, false, PrevDecl);
4053 
4054   return Var;
4055 }
4056 
VisitObjCAtDefsFieldDecl(ObjCAtDefsFieldDecl * D)4057 Decl *TemplateDeclInstantiator::VisitObjCAtDefsFieldDecl(ObjCAtDefsFieldDecl *D) {
4058   llvm_unreachable("@defs is not supported in Objective-C++");
4059 }
4060 
VisitFriendTemplateDecl(FriendTemplateDecl * D)4061 Decl *TemplateDeclInstantiator::VisitFriendTemplateDecl(FriendTemplateDecl *D) {
4062   // FIXME: We need to be able to instantiate FriendTemplateDecls.
4063   unsigned DiagID = SemaRef.getDiagnostics().getCustomDiagID(
4064                                                DiagnosticsEngine::Error,
4065                                                "cannot instantiate %0 yet");
4066   SemaRef.Diag(D->getLocation(), DiagID)
4067     << D->getDeclKindName();
4068 
4069   return nullptr;
4070 }
4071 
VisitConceptDecl(ConceptDecl * D)4072 Decl *TemplateDeclInstantiator::VisitConceptDecl(ConceptDecl *D) {
4073   llvm_unreachable("Concept definitions cannot reside inside a template");
4074 }
4075 
VisitImplicitConceptSpecializationDecl(ImplicitConceptSpecializationDecl * D)4076 Decl *TemplateDeclInstantiator::VisitImplicitConceptSpecializationDecl(
4077     ImplicitConceptSpecializationDecl *D) {
4078   llvm_unreachable("Concept specializations cannot reside inside a template");
4079 }
4080 
4081 Decl *
VisitRequiresExprBodyDecl(RequiresExprBodyDecl * D)4082 TemplateDeclInstantiator::VisitRequiresExprBodyDecl(RequiresExprBodyDecl *D) {
4083   return RequiresExprBodyDecl::Create(SemaRef.Context, D->getDeclContext(),
4084                                       D->getBeginLoc());
4085 }
4086 
VisitDecl(Decl * D)4087 Decl *TemplateDeclInstantiator::VisitDecl(Decl *D) {
4088   llvm_unreachable("Unexpected decl");
4089 }
4090 
SubstDecl(Decl * D,DeclContext * Owner,const MultiLevelTemplateArgumentList & TemplateArgs)4091 Decl *Sema::SubstDecl(Decl *D, DeclContext *Owner,
4092                       const MultiLevelTemplateArgumentList &TemplateArgs) {
4093   TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
4094   if (D->isInvalidDecl())
4095     return nullptr;
4096 
4097   Decl *SubstD;
4098   runWithSufficientStackSpace(D->getLocation(), [&] {
4099     SubstD = Instantiator.Visit(D);
4100   });
4101   return SubstD;
4102 }
4103 
adjustForRewrite(RewriteKind RK,FunctionDecl * Orig,QualType & T,TypeSourceInfo * & TInfo,DeclarationNameInfo & NameInfo)4104 void TemplateDeclInstantiator::adjustForRewrite(RewriteKind RK,
4105                                                 FunctionDecl *Orig, QualType &T,
4106                                                 TypeSourceInfo *&TInfo,
4107                                                 DeclarationNameInfo &NameInfo) {
4108   assert(RK == RewriteKind::RewriteSpaceshipAsEqualEqual);
4109 
4110   // C++2a [class.compare.default]p3:
4111   //   the return type is replaced with bool
4112   auto *FPT = T->castAs<FunctionProtoType>();
4113   T = SemaRef.Context.getFunctionType(
4114       SemaRef.Context.BoolTy, FPT->getParamTypes(), FPT->getExtProtoInfo());
4115 
4116   // Update the return type in the source info too. The most straightforward
4117   // way is to create new TypeSourceInfo for the new type. Use the location of
4118   // the '= default' as the location of the new type.
4119   //
4120   // FIXME: Set the correct return type when we initially transform the type,
4121   // rather than delaying it to now.
4122   TypeSourceInfo *NewTInfo =
4123       SemaRef.Context.getTrivialTypeSourceInfo(T, Orig->getEndLoc());
4124   auto OldLoc = TInfo->getTypeLoc().getAsAdjusted<FunctionProtoTypeLoc>();
4125   assert(OldLoc && "type of function is not a function type?");
4126   auto NewLoc = NewTInfo->getTypeLoc().castAs<FunctionProtoTypeLoc>();
4127   for (unsigned I = 0, N = OldLoc.getNumParams(); I != N; ++I)
4128     NewLoc.setParam(I, OldLoc.getParam(I));
4129   TInfo = NewTInfo;
4130 
4131   //   and the declarator-id is replaced with operator==
4132   NameInfo.setName(
4133       SemaRef.Context.DeclarationNames.getCXXOperatorName(OO_EqualEqual));
4134 }
4135 
SubstSpaceshipAsEqualEqual(CXXRecordDecl * RD,FunctionDecl * Spaceship)4136 FunctionDecl *Sema::SubstSpaceshipAsEqualEqual(CXXRecordDecl *RD,
4137                                                FunctionDecl *Spaceship) {
4138   if (Spaceship->isInvalidDecl())
4139     return nullptr;
4140 
4141   // C++2a [class.compare.default]p3:
4142   //   an == operator function is declared implicitly [...] with the same
4143   //   access and function-definition and in the same class scope as the
4144   //   three-way comparison operator function
4145   MultiLevelTemplateArgumentList NoTemplateArgs;
4146   NoTemplateArgs.setKind(TemplateSubstitutionKind::Rewrite);
4147   NoTemplateArgs.addOuterRetainedLevels(RD->getTemplateDepth());
4148   TemplateDeclInstantiator Instantiator(*this, RD, NoTemplateArgs);
4149   Decl *R;
4150   if (auto *MD = dyn_cast<CXXMethodDecl>(Spaceship)) {
4151     R = Instantiator.VisitCXXMethodDecl(
4152         MD, /*TemplateParams=*/nullptr,
4153         TemplateDeclInstantiator::RewriteKind::RewriteSpaceshipAsEqualEqual);
4154   } else {
4155     assert(Spaceship->getFriendObjectKind() &&
4156            "defaulted spaceship is neither a member nor a friend");
4157 
4158     R = Instantiator.VisitFunctionDecl(
4159         Spaceship, /*TemplateParams=*/nullptr,
4160         TemplateDeclInstantiator::RewriteKind::RewriteSpaceshipAsEqualEqual);
4161     if (!R)
4162       return nullptr;
4163 
4164     FriendDecl *FD =
4165         FriendDecl::Create(Context, RD, Spaceship->getLocation(),
4166                            cast<NamedDecl>(R), Spaceship->getBeginLoc());
4167     FD->setAccess(AS_public);
4168     RD->addDecl(FD);
4169   }
4170   return cast_or_null<FunctionDecl>(R);
4171 }
4172 
4173 /// Instantiates a nested template parameter list in the current
4174 /// instantiation context.
4175 ///
4176 /// \param L The parameter list to instantiate
4177 ///
4178 /// \returns NULL if there was an error
4179 TemplateParameterList *
SubstTemplateParams(TemplateParameterList * L)4180 TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList *L) {
4181   // Get errors for all the parameters before bailing out.
4182   bool Invalid = false;
4183 
4184   unsigned N = L->size();
4185   typedef SmallVector<NamedDecl *, 8> ParamVector;
4186   ParamVector Params;
4187   Params.reserve(N);
4188   for (auto &P : *L) {
4189     NamedDecl *D = cast_or_null<NamedDecl>(Visit(P));
4190     Params.push_back(D);
4191     Invalid = Invalid || !D || D->isInvalidDecl();
4192   }
4193 
4194   // Clean up if we had an error.
4195   if (Invalid)
4196     return nullptr;
4197 
4198   Expr *InstRequiresClause = L->getRequiresClause();
4199 
4200   TemplateParameterList *InstL
4201     = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(),
4202                                     L->getLAngleLoc(), Params,
4203                                     L->getRAngleLoc(), InstRequiresClause);
4204   return InstL;
4205 }
4206 
4207 TemplateParameterList *
SubstTemplateParams(TemplateParameterList * Params,DeclContext * Owner,const MultiLevelTemplateArgumentList & TemplateArgs,bool EvaluateConstraints)4208 Sema::SubstTemplateParams(TemplateParameterList *Params, DeclContext *Owner,
4209                           const MultiLevelTemplateArgumentList &TemplateArgs,
4210                           bool EvaluateConstraints) {
4211   TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
4212   Instantiator.setEvaluateConstraints(EvaluateConstraints);
4213   return Instantiator.SubstTemplateParams(Params);
4214 }
4215 
4216 /// Instantiate the declaration of a class template partial
4217 /// specialization.
4218 ///
4219 /// \param ClassTemplate the (instantiated) class template that is partially
4220 // specialized by the instantiation of \p PartialSpec.
4221 ///
4222 /// \param PartialSpec the (uninstantiated) class template partial
4223 /// specialization that we are instantiating.
4224 ///
4225 /// \returns The instantiated partial specialization, if successful; otherwise,
4226 /// NULL to indicate an error.
4227 ClassTemplatePartialSpecializationDecl *
InstantiateClassTemplatePartialSpecialization(ClassTemplateDecl * ClassTemplate,ClassTemplatePartialSpecializationDecl * PartialSpec)4228 TemplateDeclInstantiator::InstantiateClassTemplatePartialSpecialization(
4229                                             ClassTemplateDecl *ClassTemplate,
4230                           ClassTemplatePartialSpecializationDecl *PartialSpec) {
4231   // Create a local instantiation scope for this class template partial
4232   // specialization, which will contain the instantiations of the template
4233   // parameters.
4234   LocalInstantiationScope Scope(SemaRef);
4235 
4236   // Substitute into the template parameters of the class template partial
4237   // specialization.
4238   TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
4239   TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
4240   if (!InstParams)
4241     return nullptr;
4242 
4243   // Substitute into the template arguments of the class template partial
4244   // specialization.
4245   const ASTTemplateArgumentListInfo *TemplArgInfo
4246     = PartialSpec->getTemplateArgsAsWritten();
4247   TemplateArgumentListInfo InstTemplateArgs(TemplArgInfo->LAngleLoc,
4248                                             TemplArgInfo->RAngleLoc);
4249   if (SemaRef.SubstTemplateArguments(TemplArgInfo->arguments(), TemplateArgs,
4250                                      InstTemplateArgs))
4251     return nullptr;
4252 
4253   // Check that the template argument list is well-formed for this
4254   // class template.
4255   SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
4256   if (SemaRef.CheckTemplateArgumentList(
4257           ClassTemplate, PartialSpec->getLocation(), InstTemplateArgs,
4258           /*PartialTemplateArgs=*/false, SugaredConverted, CanonicalConverted))
4259     return nullptr;
4260 
4261   // Check these arguments are valid for a template partial specialization.
4262   if (SemaRef.CheckTemplatePartialSpecializationArgs(
4263           PartialSpec->getLocation(), ClassTemplate, InstTemplateArgs.size(),
4264           CanonicalConverted))
4265     return nullptr;
4266 
4267   // Figure out where to insert this class template partial specialization
4268   // in the member template's set of class template partial specializations.
4269   void *InsertPos = nullptr;
4270   ClassTemplateSpecializationDecl *PrevDecl =
4271       ClassTemplate->findPartialSpecialization(CanonicalConverted, InstParams,
4272                                                InsertPos);
4273 
4274   // Build the canonical type that describes the converted template
4275   // arguments of the class template partial specialization.
4276   QualType CanonType = SemaRef.Context.getTemplateSpecializationType(
4277       TemplateName(ClassTemplate), CanonicalConverted);
4278 
4279   // Create the class template partial specialization declaration.
4280   ClassTemplatePartialSpecializationDecl *InstPartialSpec =
4281       ClassTemplatePartialSpecializationDecl::Create(
4282           SemaRef.Context, PartialSpec->getTagKind(), Owner,
4283           PartialSpec->getBeginLoc(), PartialSpec->getLocation(), InstParams,
4284           ClassTemplate, CanonicalConverted, CanonType,
4285           /*PrevDecl=*/nullptr);
4286 
4287   InstPartialSpec->setTemplateArgsAsWritten(InstTemplateArgs);
4288 
4289   // Substitute the nested name specifier, if any.
4290   if (SubstQualifier(PartialSpec, InstPartialSpec))
4291     return nullptr;
4292 
4293   InstPartialSpec->setInstantiatedFromMember(PartialSpec);
4294 
4295   if (PrevDecl) {
4296     // We've already seen a partial specialization with the same template
4297     // parameters and template arguments. This can happen, for example, when
4298     // substituting the outer template arguments ends up causing two
4299     // class template partial specializations of a member class template
4300     // to have identical forms, e.g.,
4301     //
4302     //   template<typename T, typename U>
4303     //   struct Outer {
4304     //     template<typename X, typename Y> struct Inner;
4305     //     template<typename Y> struct Inner<T, Y>;
4306     //     template<typename Y> struct Inner<U, Y>;
4307     //   };
4308     //
4309     //   Outer<int, int> outer; // error: the partial specializations of Inner
4310     //                          // have the same signature.
4311     SemaRef.Diag(InstPartialSpec->getLocation(),
4312                  diag::err_partial_spec_redeclared)
4313         << InstPartialSpec;
4314     SemaRef.Diag(PrevDecl->getLocation(), diag::note_prev_partial_spec_here)
4315       << SemaRef.Context.getTypeDeclType(PrevDecl);
4316     return nullptr;
4317   }
4318 
4319   // Check the completed partial specialization.
4320   SemaRef.CheckTemplatePartialSpecialization(InstPartialSpec);
4321 
4322   // Add this partial specialization to the set of class template partial
4323   // specializations.
4324   ClassTemplate->AddPartialSpecialization(InstPartialSpec,
4325                                           /*InsertPos=*/nullptr);
4326   return InstPartialSpec;
4327 }
4328 
4329 /// Instantiate the declaration of a variable template partial
4330 /// specialization.
4331 ///
4332 /// \param VarTemplate the (instantiated) variable template that is partially
4333 /// specialized by the instantiation of \p PartialSpec.
4334 ///
4335 /// \param PartialSpec the (uninstantiated) variable template partial
4336 /// specialization that we are instantiating.
4337 ///
4338 /// \returns The instantiated partial specialization, if successful; otherwise,
4339 /// NULL to indicate an error.
4340 VarTemplatePartialSpecializationDecl *
InstantiateVarTemplatePartialSpecialization(VarTemplateDecl * VarTemplate,VarTemplatePartialSpecializationDecl * PartialSpec)4341 TemplateDeclInstantiator::InstantiateVarTemplatePartialSpecialization(
4342     VarTemplateDecl *VarTemplate,
4343     VarTemplatePartialSpecializationDecl *PartialSpec) {
4344   // Create a local instantiation scope for this variable template partial
4345   // specialization, which will contain the instantiations of the template
4346   // parameters.
4347   LocalInstantiationScope Scope(SemaRef);
4348 
4349   // Substitute into the template parameters of the variable template partial
4350   // specialization.
4351   TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
4352   TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
4353   if (!InstParams)
4354     return nullptr;
4355 
4356   // Substitute into the template arguments of the variable template partial
4357   // specialization.
4358   const ASTTemplateArgumentListInfo *TemplArgInfo
4359     = PartialSpec->getTemplateArgsAsWritten();
4360   TemplateArgumentListInfo InstTemplateArgs(TemplArgInfo->LAngleLoc,
4361                                             TemplArgInfo->RAngleLoc);
4362   if (SemaRef.SubstTemplateArguments(TemplArgInfo->arguments(), TemplateArgs,
4363                                      InstTemplateArgs))
4364     return nullptr;
4365 
4366   // Check that the template argument list is well-formed for this
4367   // class template.
4368   SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
4369   if (SemaRef.CheckTemplateArgumentList(
4370           VarTemplate, PartialSpec->getLocation(), InstTemplateArgs,
4371           /*PartialTemplateArgs=*/false, SugaredConverted, CanonicalConverted))
4372     return nullptr;
4373 
4374   // Check these arguments are valid for a template partial specialization.
4375   if (SemaRef.CheckTemplatePartialSpecializationArgs(
4376           PartialSpec->getLocation(), VarTemplate, InstTemplateArgs.size(),
4377           CanonicalConverted))
4378     return nullptr;
4379 
4380   // Figure out where to insert this variable template partial specialization
4381   // in the member template's set of variable template partial specializations.
4382   void *InsertPos = nullptr;
4383   VarTemplateSpecializationDecl *PrevDecl =
4384       VarTemplate->findPartialSpecialization(CanonicalConverted, InstParams,
4385                                              InsertPos);
4386 
4387   // Do substitution on the type of the declaration
4388   TypeSourceInfo *DI = SemaRef.SubstType(
4389       PartialSpec->getTypeSourceInfo(), TemplateArgs,
4390       PartialSpec->getTypeSpecStartLoc(), PartialSpec->getDeclName());
4391   if (!DI)
4392     return nullptr;
4393 
4394   if (DI->getType()->isFunctionType()) {
4395     SemaRef.Diag(PartialSpec->getLocation(),
4396                  diag::err_variable_instantiates_to_function)
4397         << PartialSpec->isStaticDataMember() << DI->getType();
4398     return nullptr;
4399   }
4400 
4401   // Create the variable template partial specialization declaration.
4402   VarTemplatePartialSpecializationDecl *InstPartialSpec =
4403       VarTemplatePartialSpecializationDecl::Create(
4404           SemaRef.Context, Owner, PartialSpec->getInnerLocStart(),
4405           PartialSpec->getLocation(), InstParams, VarTemplate, DI->getType(),
4406           DI, PartialSpec->getStorageClass(), CanonicalConverted);
4407 
4408   InstPartialSpec->setTemplateArgsAsWritten(InstTemplateArgs);
4409 
4410   // Substitute the nested name specifier, if any.
4411   if (SubstQualifier(PartialSpec, InstPartialSpec))
4412     return nullptr;
4413 
4414   InstPartialSpec->setInstantiatedFromMember(PartialSpec);
4415 
4416   if (PrevDecl) {
4417     // We've already seen a partial specialization with the same template
4418     // parameters and template arguments. This can happen, for example, when
4419     // substituting the outer template arguments ends up causing two
4420     // variable template partial specializations of a member variable template
4421     // to have identical forms, e.g.,
4422     //
4423     //   template<typename T, typename U>
4424     //   struct Outer {
4425     //     template<typename X, typename Y> pair<X,Y> p;
4426     //     template<typename Y> pair<T, Y> p;
4427     //     template<typename Y> pair<U, Y> p;
4428     //   };
4429     //
4430     //   Outer<int, int> outer; // error: the partial specializations of Inner
4431     //                          // have the same signature.
4432     SemaRef.Diag(PartialSpec->getLocation(),
4433                  diag::err_var_partial_spec_redeclared)
4434         << InstPartialSpec;
4435     SemaRef.Diag(PrevDecl->getLocation(),
4436                  diag::note_var_prev_partial_spec_here);
4437     return nullptr;
4438   }
4439   // Check the completed partial specialization.
4440   SemaRef.CheckTemplatePartialSpecialization(InstPartialSpec);
4441 
4442   // Add this partial specialization to the set of variable template partial
4443   // specializations. The instantiation of the initializer is not necessary.
4444   VarTemplate->AddPartialSpecialization(InstPartialSpec, /*InsertPos=*/nullptr);
4445 
4446   SemaRef.BuildVariableInstantiation(InstPartialSpec, PartialSpec, TemplateArgs,
4447                                      LateAttrs, Owner, StartingScope);
4448 
4449   return InstPartialSpec;
4450 }
4451 
4452 TypeSourceInfo*
SubstFunctionType(FunctionDecl * D,SmallVectorImpl<ParmVarDecl * > & Params)4453 TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D,
4454                               SmallVectorImpl<ParmVarDecl *> &Params) {
4455   TypeSourceInfo *OldTInfo = D->getTypeSourceInfo();
4456   assert(OldTInfo && "substituting function without type source info");
4457   assert(Params.empty() && "parameter vector is non-empty at start");
4458 
4459   CXXRecordDecl *ThisContext = nullptr;
4460   Qualifiers ThisTypeQuals;
4461   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
4462     ThisContext = cast<CXXRecordDecl>(Owner);
4463     ThisTypeQuals = Method->getFunctionObjectParameterType().getQualifiers();
4464   }
4465 
4466   TypeSourceInfo *NewTInfo = SemaRef.SubstFunctionDeclType(
4467       OldTInfo, TemplateArgs, D->getTypeSpecStartLoc(), D->getDeclName(),
4468       ThisContext, ThisTypeQuals, EvaluateConstraints);
4469   if (!NewTInfo)
4470     return nullptr;
4471 
4472   TypeLoc OldTL = OldTInfo->getTypeLoc().IgnoreParens();
4473   if (FunctionProtoTypeLoc OldProtoLoc = OldTL.getAs<FunctionProtoTypeLoc>()) {
4474     if (NewTInfo != OldTInfo) {
4475       // Get parameters from the new type info.
4476       TypeLoc NewTL = NewTInfo->getTypeLoc().IgnoreParens();
4477       FunctionProtoTypeLoc NewProtoLoc = NewTL.castAs<FunctionProtoTypeLoc>();
4478       unsigned NewIdx = 0;
4479       for (unsigned OldIdx = 0, NumOldParams = OldProtoLoc.getNumParams();
4480            OldIdx != NumOldParams; ++OldIdx) {
4481         ParmVarDecl *OldParam = OldProtoLoc.getParam(OldIdx);
4482         if (!OldParam)
4483           return nullptr;
4484 
4485         LocalInstantiationScope *Scope = SemaRef.CurrentInstantiationScope;
4486 
4487         std::optional<unsigned> NumArgumentsInExpansion;
4488         if (OldParam->isParameterPack())
4489           NumArgumentsInExpansion =
4490               SemaRef.getNumArgumentsInExpansion(OldParam->getType(),
4491                                                  TemplateArgs);
4492         if (!NumArgumentsInExpansion) {
4493           // Simple case: normal parameter, or a parameter pack that's
4494           // instantiated to a (still-dependent) parameter pack.
4495           ParmVarDecl *NewParam = NewProtoLoc.getParam(NewIdx++);
4496           Params.push_back(NewParam);
4497           Scope->InstantiatedLocal(OldParam, NewParam);
4498         } else {
4499           // Parameter pack expansion: make the instantiation an argument pack.
4500           Scope->MakeInstantiatedLocalArgPack(OldParam);
4501           for (unsigned I = 0; I != *NumArgumentsInExpansion; ++I) {
4502             ParmVarDecl *NewParam = NewProtoLoc.getParam(NewIdx++);
4503             Params.push_back(NewParam);
4504             Scope->InstantiatedLocalPackArg(OldParam, NewParam);
4505           }
4506         }
4507       }
4508     } else {
4509       // The function type itself was not dependent and therefore no
4510       // substitution occurred. However, we still need to instantiate
4511       // the function parameters themselves.
4512       const FunctionProtoType *OldProto =
4513           cast<FunctionProtoType>(OldProtoLoc.getType());
4514       for (unsigned i = 0, i_end = OldProtoLoc.getNumParams(); i != i_end;
4515            ++i) {
4516         ParmVarDecl *OldParam = OldProtoLoc.getParam(i);
4517         if (!OldParam) {
4518           Params.push_back(SemaRef.BuildParmVarDeclForTypedef(
4519               D, D->getLocation(), OldProto->getParamType(i)));
4520           continue;
4521         }
4522 
4523         ParmVarDecl *Parm =
4524             cast_or_null<ParmVarDecl>(VisitParmVarDecl(OldParam));
4525         if (!Parm)
4526           return nullptr;
4527         Params.push_back(Parm);
4528       }
4529     }
4530   } else {
4531     // If the type of this function, after ignoring parentheses, is not
4532     // *directly* a function type, then we're instantiating a function that
4533     // was declared via a typedef or with attributes, e.g.,
4534     //
4535     //   typedef int functype(int, int);
4536     //   functype func;
4537     //   int __cdecl meth(int, int);
4538     //
4539     // In this case, we'll just go instantiate the ParmVarDecls that we
4540     // synthesized in the method declaration.
4541     SmallVector<QualType, 4> ParamTypes;
4542     Sema::ExtParameterInfoBuilder ExtParamInfos;
4543     if (SemaRef.SubstParmTypes(D->getLocation(), D->parameters(), nullptr,
4544                                TemplateArgs, ParamTypes, &Params,
4545                                ExtParamInfos))
4546       return nullptr;
4547   }
4548 
4549   return NewTInfo;
4550 }
4551 
addInstantiatedLocalVarsToScope(FunctionDecl * Function,const FunctionDecl * PatternDecl,LocalInstantiationScope & Scope)4552 void Sema::addInstantiatedLocalVarsToScope(FunctionDecl *Function,
4553                                            const FunctionDecl *PatternDecl,
4554                                            LocalInstantiationScope &Scope) {
4555   LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(getFunctionScopes().back());
4556 
4557   for (auto *decl : PatternDecl->decls()) {
4558     if (!isa<VarDecl>(decl) || isa<ParmVarDecl>(decl))
4559       continue;
4560 
4561     VarDecl *VD = cast<VarDecl>(decl);
4562     IdentifierInfo *II = VD->getIdentifier();
4563 
4564     auto it = llvm::find_if(Function->decls(), [&](Decl *inst) {
4565       VarDecl *InstVD = dyn_cast<VarDecl>(inst);
4566       return InstVD && InstVD->isLocalVarDecl() &&
4567              InstVD->getIdentifier() == II;
4568     });
4569 
4570     if (it == Function->decls().end())
4571       continue;
4572 
4573     Scope.InstantiatedLocal(VD, *it);
4574     LSI->addCapture(cast<VarDecl>(*it), /*isBlock=*/false, /*isByref=*/false,
4575                     /*isNested=*/false, VD->getLocation(), SourceLocation(),
4576                     VD->getType(), /*Invalid=*/false);
4577   }
4578 }
4579 
addInstantiatedParametersToScope(FunctionDecl * Function,const FunctionDecl * PatternDecl,LocalInstantiationScope & Scope,const MultiLevelTemplateArgumentList & TemplateArgs)4580 bool Sema::addInstantiatedParametersToScope(
4581     FunctionDecl *Function, const FunctionDecl *PatternDecl,
4582     LocalInstantiationScope &Scope,
4583     const MultiLevelTemplateArgumentList &TemplateArgs) {
4584   unsigned FParamIdx = 0;
4585   for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I) {
4586     const ParmVarDecl *PatternParam = PatternDecl->getParamDecl(I);
4587     if (!PatternParam->isParameterPack()) {
4588       // Simple case: not a parameter pack.
4589       assert(FParamIdx < Function->getNumParams());
4590       ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
4591       FunctionParam->setDeclName(PatternParam->getDeclName());
4592       // If the parameter's type is not dependent, update it to match the type
4593       // in the pattern. They can differ in top-level cv-qualifiers, and we want
4594       // the pattern's type here. If the type is dependent, they can't differ,
4595       // per core issue 1668. Substitute into the type from the pattern, in case
4596       // it's instantiation-dependent.
4597       // FIXME: Updating the type to work around this is at best fragile.
4598       if (!PatternDecl->getType()->isDependentType()) {
4599         QualType T = SubstType(PatternParam->getType(), TemplateArgs,
4600                                FunctionParam->getLocation(),
4601                                FunctionParam->getDeclName());
4602         if (T.isNull())
4603           return true;
4604         FunctionParam->setType(T);
4605       }
4606 
4607       Scope.InstantiatedLocal(PatternParam, FunctionParam);
4608       ++FParamIdx;
4609       continue;
4610     }
4611 
4612     // Expand the parameter pack.
4613     Scope.MakeInstantiatedLocalArgPack(PatternParam);
4614     std::optional<unsigned> NumArgumentsInExpansion =
4615         getNumArgumentsInExpansion(PatternParam->getType(), TemplateArgs);
4616     if (NumArgumentsInExpansion) {
4617       QualType PatternType =
4618           PatternParam->getType()->castAs<PackExpansionType>()->getPattern();
4619       for (unsigned Arg = 0; Arg < *NumArgumentsInExpansion; ++Arg) {
4620         ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
4621         FunctionParam->setDeclName(PatternParam->getDeclName());
4622         if (!PatternDecl->getType()->isDependentType()) {
4623           Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, Arg);
4624           QualType T =
4625               SubstType(PatternType, TemplateArgs, FunctionParam->getLocation(),
4626                         FunctionParam->getDeclName());
4627           if (T.isNull())
4628             return true;
4629           FunctionParam->setType(T);
4630         }
4631 
4632         Scope.InstantiatedLocalPackArg(PatternParam, FunctionParam);
4633         ++FParamIdx;
4634       }
4635     }
4636   }
4637 
4638   return false;
4639 }
4640 
InstantiateDefaultArgument(SourceLocation CallLoc,FunctionDecl * FD,ParmVarDecl * Param)4641 bool Sema::InstantiateDefaultArgument(SourceLocation CallLoc, FunctionDecl *FD,
4642                                       ParmVarDecl *Param) {
4643   assert(Param->hasUninstantiatedDefaultArg());
4644 
4645   // Instantiate the expression.
4646   //
4647   // FIXME: Pass in a correct Pattern argument, otherwise
4648   // getTemplateInstantiationArgs uses the lexical context of FD, e.g.
4649   //
4650   // template<typename T>
4651   // struct A {
4652   //   static int FooImpl();
4653   //
4654   //   template<typename Tp>
4655   //   // bug: default argument A<T>::FooImpl() is evaluated with 2-level
4656   //   // template argument list [[T], [Tp]], should be [[Tp]].
4657   //   friend A<Tp> Foo(int a);
4658   // };
4659   //
4660   // template<typename T>
4661   // A<T> Foo(int a = A<T>::FooImpl());
4662   MultiLevelTemplateArgumentList TemplateArgs = getTemplateInstantiationArgs(
4663       FD, FD->getLexicalDeclContext(),
4664       /*Final=*/false, /*Innermost=*/std::nullopt,
4665       /*RelativeToPrimary=*/true, /*Pattern=*/nullptr,
4666       /*ForConstraintInstantiation=*/false, /*SkipForSpecialization=*/false,
4667       /*ForDefaultArgumentSubstitution=*/true);
4668 
4669   if (SubstDefaultArgument(CallLoc, Param, TemplateArgs, /*ForCallExpr*/ true))
4670     return true;
4671 
4672   if (ASTMutationListener *L = getASTMutationListener())
4673     L->DefaultArgumentInstantiated(Param);
4674 
4675   return false;
4676 }
4677 
InstantiateExceptionSpec(SourceLocation PointOfInstantiation,FunctionDecl * Decl)4678 void Sema::InstantiateExceptionSpec(SourceLocation PointOfInstantiation,
4679                                     FunctionDecl *Decl) {
4680   const FunctionProtoType *Proto = Decl->getType()->castAs<FunctionProtoType>();
4681   if (Proto->getExceptionSpecType() != EST_Uninstantiated)
4682     return;
4683 
4684   InstantiatingTemplate Inst(*this, PointOfInstantiation, Decl,
4685                              InstantiatingTemplate::ExceptionSpecification());
4686   if (Inst.isInvalid()) {
4687     // We hit the instantiation depth limit. Clear the exception specification
4688     // so that our callers don't have to cope with EST_Uninstantiated.
4689     UpdateExceptionSpec(Decl, EST_None);
4690     return;
4691   }
4692   if (Inst.isAlreadyInstantiating()) {
4693     // This exception specification indirectly depends on itself. Reject.
4694     // FIXME: Corresponding rule in the standard?
4695     Diag(PointOfInstantiation, diag::err_exception_spec_cycle) << Decl;
4696     UpdateExceptionSpec(Decl, EST_None);
4697     return;
4698   }
4699 
4700   // Enter the scope of this instantiation. We don't use
4701   // PushDeclContext because we don't have a scope.
4702   Sema::ContextRAII savedContext(*this, Decl);
4703   LocalInstantiationScope Scope(*this);
4704 
4705   MultiLevelTemplateArgumentList TemplateArgs =
4706       getTemplateInstantiationArgs(Decl, Decl->getLexicalDeclContext(),
4707                                    /*Final=*/false, /*Innermost=*/std::nullopt,
4708                                    /*RelativeToPrimary*/ true);
4709 
4710   // FIXME: We can't use getTemplateInstantiationPattern(false) in general
4711   // here, because for a non-defining friend declaration in a class template,
4712   // we don't store enough information to map back to the friend declaration in
4713   // the template.
4714   FunctionDecl *Template = Proto->getExceptionSpecTemplate();
4715   if (addInstantiatedParametersToScope(Decl, Template, Scope, TemplateArgs)) {
4716     UpdateExceptionSpec(Decl, EST_None);
4717     return;
4718   }
4719 
4720   // The noexcept specification could reference any lambda captures. Ensure
4721   // those are added to the LocalInstantiationScope.
4722   LambdaScopeForCallOperatorInstantiationRAII PushLambdaCaptures(
4723       *this, Decl, TemplateArgs, Scope,
4724       /*ShouldAddDeclsFromParentScope=*/false);
4725 
4726   SubstExceptionSpec(Decl, Template->getType()->castAs<FunctionProtoType>(),
4727                      TemplateArgs);
4728 }
4729 
4730 /// Initializes the common fields of an instantiation function
4731 /// declaration (New) from the corresponding fields of its template (Tmpl).
4732 ///
4733 /// \returns true if there was an error
4734 bool
InitFunctionInstantiation(FunctionDecl * New,FunctionDecl * Tmpl)4735 TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New,
4736                                                     FunctionDecl *Tmpl) {
4737   New->setImplicit(Tmpl->isImplicit());
4738 
4739   // Forward the mangling number from the template to the instantiated decl.
4740   SemaRef.Context.setManglingNumber(New,
4741                                     SemaRef.Context.getManglingNumber(Tmpl));
4742 
4743   // If we are performing substituting explicitly-specified template arguments
4744   // or deduced template arguments into a function template and we reach this
4745   // point, we are now past the point where SFINAE applies and have committed
4746   // to keeping the new function template specialization. We therefore
4747   // convert the active template instantiation for the function template
4748   // into a template instantiation for this specific function template
4749   // specialization, which is not a SFINAE context, so that we diagnose any
4750   // further errors in the declaration itself.
4751   //
4752   // FIXME: This is a hack.
4753   typedef Sema::CodeSynthesisContext ActiveInstType;
4754   ActiveInstType &ActiveInst = SemaRef.CodeSynthesisContexts.back();
4755   if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution ||
4756       ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) {
4757     if (isa<FunctionTemplateDecl>(ActiveInst.Entity)) {
4758       SemaRef.InstantiatingSpecializations.erase(
4759           {ActiveInst.Entity->getCanonicalDecl(), ActiveInst.Kind});
4760       atTemplateEnd(SemaRef.TemplateInstCallbacks, SemaRef, ActiveInst);
4761       ActiveInst.Kind = ActiveInstType::TemplateInstantiation;
4762       ActiveInst.Entity = New;
4763       atTemplateBegin(SemaRef.TemplateInstCallbacks, SemaRef, ActiveInst);
4764     }
4765   }
4766 
4767   const FunctionProtoType *Proto = Tmpl->getType()->getAs<FunctionProtoType>();
4768   assert(Proto && "Function template without prototype?");
4769 
4770   if (Proto->hasExceptionSpec() || Proto->getNoReturnAttr()) {
4771     FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
4772 
4773     // DR1330: In C++11, defer instantiation of a non-trivial
4774     // exception specification.
4775     // DR1484: Local classes and their members are instantiated along with the
4776     // containing function.
4777     if (SemaRef.getLangOpts().CPlusPlus11 &&
4778         EPI.ExceptionSpec.Type != EST_None &&
4779         EPI.ExceptionSpec.Type != EST_DynamicNone &&
4780         EPI.ExceptionSpec.Type != EST_BasicNoexcept &&
4781         !Tmpl->isInLocalScopeForInstantiation()) {
4782       FunctionDecl *ExceptionSpecTemplate = Tmpl;
4783       if (EPI.ExceptionSpec.Type == EST_Uninstantiated)
4784         ExceptionSpecTemplate = EPI.ExceptionSpec.SourceTemplate;
4785       ExceptionSpecificationType NewEST = EST_Uninstantiated;
4786       if (EPI.ExceptionSpec.Type == EST_Unevaluated)
4787         NewEST = EST_Unevaluated;
4788 
4789       // Mark the function has having an uninstantiated exception specification.
4790       const FunctionProtoType *NewProto
4791         = New->getType()->getAs<FunctionProtoType>();
4792       assert(NewProto && "Template instantiation without function prototype?");
4793       EPI = NewProto->getExtProtoInfo();
4794       EPI.ExceptionSpec.Type = NewEST;
4795       EPI.ExceptionSpec.SourceDecl = New;
4796       EPI.ExceptionSpec.SourceTemplate = ExceptionSpecTemplate;
4797       New->setType(SemaRef.Context.getFunctionType(
4798           NewProto->getReturnType(), NewProto->getParamTypes(), EPI));
4799     } else {
4800       Sema::ContextRAII SwitchContext(SemaRef, New);
4801       SemaRef.SubstExceptionSpec(New, Proto, TemplateArgs);
4802     }
4803   }
4804 
4805   // Get the definition. Leaves the variable unchanged if undefined.
4806   const FunctionDecl *Definition = Tmpl;
4807   Tmpl->isDefined(Definition);
4808 
4809   SemaRef.InstantiateAttrs(TemplateArgs, Definition, New,
4810                            LateAttrs, StartingScope);
4811 
4812   return false;
4813 }
4814 
4815 /// Initializes common fields of an instantiated method
4816 /// declaration (New) from the corresponding fields of its template
4817 /// (Tmpl).
4818 ///
4819 /// \returns true if there was an error
4820 bool
InitMethodInstantiation(CXXMethodDecl * New,CXXMethodDecl * Tmpl)4821 TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New,
4822                                                   CXXMethodDecl *Tmpl) {
4823   if (InitFunctionInstantiation(New, Tmpl))
4824     return true;
4825 
4826   if (isa<CXXDestructorDecl>(New) && SemaRef.getLangOpts().CPlusPlus11)
4827     SemaRef.AdjustDestructorExceptionSpec(cast<CXXDestructorDecl>(New));
4828 
4829   New->setAccess(Tmpl->getAccess());
4830   if (Tmpl->isVirtualAsWritten())
4831     New->setVirtualAsWritten(true);
4832 
4833   // FIXME: New needs a pointer to Tmpl
4834   return false;
4835 }
4836 
SubstDefaultedFunction(FunctionDecl * New,FunctionDecl * Tmpl)4837 bool TemplateDeclInstantiator::SubstDefaultedFunction(FunctionDecl *New,
4838                                                       FunctionDecl *Tmpl) {
4839   // Transfer across any unqualified lookups.
4840   if (auto *DFI = Tmpl->getDefalutedOrDeletedInfo()) {
4841     SmallVector<DeclAccessPair, 32> Lookups;
4842     Lookups.reserve(DFI->getUnqualifiedLookups().size());
4843     bool AnyChanged = false;
4844     for (DeclAccessPair DA : DFI->getUnqualifiedLookups()) {
4845       NamedDecl *D = SemaRef.FindInstantiatedDecl(New->getLocation(),
4846                                                   DA.getDecl(), TemplateArgs);
4847       if (!D)
4848         return true;
4849       AnyChanged |= (D != DA.getDecl());
4850       Lookups.push_back(DeclAccessPair::make(D, DA.getAccess()));
4851     }
4852 
4853     // It's unlikely that substitution will change any declarations. Don't
4854     // store an unnecessary copy in that case.
4855     New->setDefaultedOrDeletedInfo(
4856         AnyChanged ? FunctionDecl::DefaultedOrDeletedFunctionInfo::Create(
4857                          SemaRef.Context, Lookups)
4858                    : DFI);
4859   }
4860 
4861   SemaRef.SetDeclDefaulted(New, Tmpl->getLocation());
4862   return false;
4863 }
4864 
InstantiateFunctionDeclaration(FunctionTemplateDecl * FTD,const TemplateArgumentList * Args,SourceLocation Loc,CodeSynthesisContext::SynthesisKind CSC)4865 FunctionDecl *Sema::InstantiateFunctionDeclaration(
4866     FunctionTemplateDecl *FTD, const TemplateArgumentList *Args,
4867     SourceLocation Loc, CodeSynthesisContext::SynthesisKind CSC) {
4868   FunctionDecl *FD = FTD->getTemplatedDecl();
4869 
4870   sema::TemplateDeductionInfo Info(Loc);
4871   InstantiatingTemplate Inst(*this, Loc, FTD, Args->asArray(), CSC, Info);
4872   if (Inst.isInvalid())
4873     return nullptr;
4874 
4875   ContextRAII SavedContext(*this, FD);
4876   MultiLevelTemplateArgumentList MArgs(FTD, Args->asArray(),
4877                                        /*Final=*/false);
4878 
4879   return cast_or_null<FunctionDecl>(SubstDecl(FD, FD->getParent(), MArgs));
4880 }
4881 
InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,FunctionDecl * Function,bool Recursive,bool DefinitionRequired,bool AtEndOfTU)4882 void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
4883                                          FunctionDecl *Function,
4884                                          bool Recursive,
4885                                          bool DefinitionRequired,
4886                                          bool AtEndOfTU) {
4887   if (Function->isInvalidDecl() || isa<CXXDeductionGuideDecl>(Function))
4888     return;
4889 
4890   // Never instantiate an explicit specialization except if it is a class scope
4891   // explicit specialization.
4892   TemplateSpecializationKind TSK =
4893       Function->getTemplateSpecializationKindForInstantiation();
4894   if (TSK == TSK_ExplicitSpecialization)
4895     return;
4896 
4897   // Never implicitly instantiate a builtin; we don't actually need a function
4898   // body.
4899   if (Function->getBuiltinID() && TSK == TSK_ImplicitInstantiation &&
4900       !DefinitionRequired)
4901     return;
4902 
4903   // Don't instantiate a definition if we already have one.
4904   const FunctionDecl *ExistingDefn = nullptr;
4905   if (Function->isDefined(ExistingDefn,
4906                           /*CheckForPendingFriendDefinition=*/true)) {
4907     if (ExistingDefn->isThisDeclarationADefinition())
4908       return;
4909 
4910     // If we're asked to instantiate a function whose body comes from an
4911     // instantiated friend declaration, attach the instantiated body to the
4912     // corresponding declaration of the function.
4913     assert(ExistingDefn->isThisDeclarationInstantiatedFromAFriendDefinition());
4914     Function = const_cast<FunctionDecl*>(ExistingDefn);
4915   }
4916 
4917   // Find the function body that we'll be substituting.
4918   const FunctionDecl *PatternDecl = Function->getTemplateInstantiationPattern();
4919   assert(PatternDecl && "instantiating a non-template");
4920 
4921   const FunctionDecl *PatternDef = PatternDecl->getDefinition();
4922   Stmt *Pattern = nullptr;
4923   if (PatternDef) {
4924     Pattern = PatternDef->getBody(PatternDef);
4925     PatternDecl = PatternDef;
4926     if (PatternDef->willHaveBody())
4927       PatternDef = nullptr;
4928   }
4929 
4930   // FIXME: We need to track the instantiation stack in order to know which
4931   // definitions should be visible within this instantiation.
4932   if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Function,
4933                                 Function->getInstantiatedFromMemberFunction(),
4934                                      PatternDecl, PatternDef, TSK,
4935                                      /*Complain*/DefinitionRequired)) {
4936     if (DefinitionRequired)
4937       Function->setInvalidDecl();
4938     else if (TSK == TSK_ExplicitInstantiationDefinition ||
4939              (Function->isConstexpr() && !Recursive)) {
4940       // Try again at the end of the translation unit (at which point a
4941       // definition will be required).
4942       assert(!Recursive);
4943       Function->setInstantiationIsPending(true);
4944       PendingInstantiations.push_back(
4945         std::make_pair(Function, PointOfInstantiation));
4946     } else if (TSK == TSK_ImplicitInstantiation) {
4947       if (AtEndOfTU && !getDiagnostics().hasErrorOccurred() &&
4948           !getSourceManager().isInSystemHeader(PatternDecl->getBeginLoc())) {
4949         Diag(PointOfInstantiation, diag::warn_func_template_missing)
4950           << Function;
4951         Diag(PatternDecl->getLocation(), diag::note_forward_template_decl);
4952         if (getLangOpts().CPlusPlus11)
4953           Diag(PointOfInstantiation, diag::note_inst_declaration_hint)
4954               << Function;
4955       }
4956     }
4957 
4958     return;
4959   }
4960 
4961   // Postpone late parsed template instantiations.
4962   if (PatternDecl->isLateTemplateParsed() &&
4963       !LateTemplateParser) {
4964     Function->setInstantiationIsPending(true);
4965     LateParsedInstantiations.push_back(
4966         std::make_pair(Function, PointOfInstantiation));
4967     return;
4968   }
4969 
4970   llvm::TimeTraceScope TimeScope("InstantiateFunction", [&]() {
4971     llvm::TimeTraceMetadata M;
4972     llvm::raw_string_ostream OS(M.Detail);
4973     Function->getNameForDiagnostic(OS, getPrintingPolicy(),
4974                                    /*Qualified=*/true);
4975     if (llvm::isTimeTraceVerbose()) {
4976       auto Loc = SourceMgr.getExpansionLoc(Function->getLocation());
4977       M.File = SourceMgr.getFilename(Loc);
4978       M.Line = SourceMgr.getExpansionLineNumber(Loc);
4979     }
4980     return M;
4981   });
4982 
4983   // If we're performing recursive template instantiation, create our own
4984   // queue of pending implicit instantiations that we will instantiate later,
4985   // while we're still within our own instantiation context.
4986   // This has to happen before LateTemplateParser below is called, so that
4987   // it marks vtables used in late parsed templates as used.
4988   GlobalEagerInstantiationScope GlobalInstantiations(*this,
4989                                                      /*Enabled=*/Recursive);
4990   LocalEagerInstantiationScope LocalInstantiations(*this);
4991 
4992   // Call the LateTemplateParser callback if there is a need to late parse
4993   // a templated function definition.
4994   if (!Pattern && PatternDecl->isLateTemplateParsed() &&
4995       LateTemplateParser) {
4996     // FIXME: Optimize to allow individual templates to be deserialized.
4997     if (PatternDecl->isFromASTFile())
4998       ExternalSource->ReadLateParsedTemplates(LateParsedTemplateMap);
4999 
5000     auto LPTIter = LateParsedTemplateMap.find(PatternDecl);
5001     assert(LPTIter != LateParsedTemplateMap.end() &&
5002            "missing LateParsedTemplate");
5003     LateTemplateParser(OpaqueParser, *LPTIter->second);
5004     Pattern = PatternDecl->getBody(PatternDecl);
5005     updateAttrsForLateParsedTemplate(PatternDecl, Function);
5006   }
5007 
5008   // Note, we should never try to instantiate a deleted function template.
5009   assert((Pattern || PatternDecl->isDefaulted() ||
5010           PatternDecl->hasSkippedBody()) &&
5011          "unexpected kind of function template definition");
5012 
5013   // C++1y [temp.explicit]p10:
5014   //   Except for inline functions, declarations with types deduced from their
5015   //   initializer or return value, and class template specializations, other
5016   //   explicit instantiation declarations have the effect of suppressing the
5017   //   implicit instantiation of the entity to which they refer.
5018   if (TSK == TSK_ExplicitInstantiationDeclaration &&
5019       !PatternDecl->isInlined() &&
5020       !PatternDecl->getReturnType()->getContainedAutoType())
5021     return;
5022 
5023   if (PatternDecl->isInlined()) {
5024     // Function, and all later redeclarations of it (from imported modules,
5025     // for instance), are now implicitly inline.
5026     for (auto *D = Function->getMostRecentDecl(); /**/;
5027          D = D->getPreviousDecl()) {
5028       D->setImplicitlyInline();
5029       if (D == Function)
5030         break;
5031     }
5032   }
5033 
5034   InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
5035   if (Inst.isInvalid() || Inst.isAlreadyInstantiating())
5036     return;
5037   PrettyDeclStackTraceEntry CrashInfo(Context, Function, SourceLocation(),
5038                                       "instantiating function definition");
5039 
5040   // The instantiation is visible here, even if it was first declared in an
5041   // unimported module.
5042   Function->setVisibleDespiteOwningModule();
5043 
5044   // Copy the source locations from the pattern.
5045   Function->setLocation(PatternDecl->getLocation());
5046   Function->setInnerLocStart(PatternDecl->getInnerLocStart());
5047   Function->setRangeEnd(PatternDecl->getEndLoc());
5048   Function->setDeclarationNameLoc(PatternDecl->getNameInfo().getInfo());
5049 
5050   EnterExpressionEvaluationContext EvalContext(
5051       *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
5052 
5053   Qualifiers ThisTypeQuals;
5054   CXXRecordDecl *ThisContext = nullptr;
5055   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
5056     ThisContext = Method->getParent();
5057     ThisTypeQuals = Method->getMethodQualifiers();
5058   }
5059   CXXThisScopeRAII ThisScope(*this, ThisContext, ThisTypeQuals);
5060 
5061   // Introduce a new scope where local variable instantiations will be
5062   // recorded, unless we're actually a member function within a local
5063   // class, in which case we need to merge our results with the parent
5064   // scope (of the enclosing function). The exception is instantiating
5065   // a function template specialization, since the template to be
5066   // instantiated already has references to locals properly substituted.
5067   bool MergeWithParentScope = false;
5068   if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Function->getDeclContext()))
5069     MergeWithParentScope =
5070         Rec->isLocalClass() && !Function->isFunctionTemplateSpecialization();
5071 
5072   LocalInstantiationScope Scope(*this, MergeWithParentScope);
5073   auto RebuildTypeSourceInfoForDefaultSpecialMembers = [&]() {
5074     // Special members might get their TypeSourceInfo set up w.r.t the
5075     // PatternDecl context, in which case parameters could still be pointing
5076     // back to the original class, make sure arguments are bound to the
5077     // instantiated record instead.
5078     assert(PatternDecl->isDefaulted() &&
5079            "Special member needs to be defaulted");
5080     auto PatternSM = getDefaultedFunctionKind(PatternDecl).asSpecialMember();
5081     if (!(PatternSM == CXXSpecialMemberKind::CopyConstructor ||
5082           PatternSM == CXXSpecialMemberKind::CopyAssignment ||
5083           PatternSM == CXXSpecialMemberKind::MoveConstructor ||
5084           PatternSM == CXXSpecialMemberKind::MoveAssignment))
5085       return;
5086 
5087     auto *NewRec = dyn_cast<CXXRecordDecl>(Function->getDeclContext());
5088     const auto *PatternRec =
5089         dyn_cast<CXXRecordDecl>(PatternDecl->getDeclContext());
5090     if (!NewRec || !PatternRec)
5091       return;
5092     if (!PatternRec->isLambda())
5093       return;
5094 
5095     struct SpecialMemberTypeInfoRebuilder
5096         : TreeTransform<SpecialMemberTypeInfoRebuilder> {
5097       using Base = TreeTransform<SpecialMemberTypeInfoRebuilder>;
5098       const CXXRecordDecl *OldDecl;
5099       CXXRecordDecl *NewDecl;
5100 
5101       SpecialMemberTypeInfoRebuilder(Sema &SemaRef, const CXXRecordDecl *O,
5102                                      CXXRecordDecl *N)
5103           : TreeTransform(SemaRef), OldDecl(O), NewDecl(N) {}
5104 
5105       bool TransformExceptionSpec(SourceLocation Loc,
5106                                   FunctionProtoType::ExceptionSpecInfo &ESI,
5107                                   SmallVectorImpl<QualType> &Exceptions,
5108                                   bool &Changed) {
5109         return false;
5110       }
5111 
5112       QualType TransformRecordType(TypeLocBuilder &TLB, RecordTypeLoc TL) {
5113         const RecordType *T = TL.getTypePtr();
5114         RecordDecl *Record = cast_or_null<RecordDecl>(
5115             getDerived().TransformDecl(TL.getNameLoc(), T->getDecl()));
5116         if (Record != OldDecl)
5117           return Base::TransformRecordType(TLB, TL);
5118 
5119         QualType Result = getDerived().RebuildRecordType(NewDecl);
5120         if (Result.isNull())
5121           return QualType();
5122 
5123         RecordTypeLoc NewTL = TLB.push<RecordTypeLoc>(Result);
5124         NewTL.setNameLoc(TL.getNameLoc());
5125         return Result;
5126       }
5127     } IR{*this, PatternRec, NewRec};
5128 
5129     TypeSourceInfo *NewSI = IR.TransformType(Function->getTypeSourceInfo());
5130     assert(NewSI && "Type Transform failed?");
5131     Function->setType(NewSI->getType());
5132     Function->setTypeSourceInfo(NewSI);
5133 
5134     ParmVarDecl *Parm = Function->getParamDecl(0);
5135     TypeSourceInfo *NewParmSI = IR.TransformType(Parm->getTypeSourceInfo());
5136     assert(NewParmSI && "Type transformation failed.");
5137     Parm->setType(NewParmSI->getType());
5138     Parm->setTypeSourceInfo(NewParmSI);
5139   };
5140 
5141   if (PatternDecl->isDefaulted()) {
5142     RebuildTypeSourceInfoForDefaultSpecialMembers();
5143     SetDeclDefaulted(Function, PatternDecl->getLocation());
5144   } else {
5145     MultiLevelTemplateArgumentList TemplateArgs = getTemplateInstantiationArgs(
5146         Function, Function->getLexicalDeclContext(), /*Final=*/false,
5147         /*Innermost=*/std::nullopt, false, PatternDecl);
5148 
5149     // Substitute into the qualifier; we can get a substitution failure here
5150     // through evil use of alias templates.
5151     // FIXME: Is CurContext correct for this? Should we go to the (instantiation
5152     // of the) lexical context of the pattern?
5153     SubstQualifier(*this, PatternDecl, Function, TemplateArgs);
5154 
5155     ActOnStartOfFunctionDef(nullptr, Function);
5156 
5157     // Enter the scope of this instantiation. We don't use
5158     // PushDeclContext because we don't have a scope.
5159     Sema::ContextRAII savedContext(*this, Function);
5160 
5161     FPFeaturesStateRAII SavedFPFeatures(*this);
5162     CurFPFeatures = FPOptions(getLangOpts());
5163     FpPragmaStack.CurrentValue = FPOptionsOverride();
5164 
5165     if (addInstantiatedParametersToScope(Function, PatternDecl, Scope,
5166                                          TemplateArgs))
5167       return;
5168 
5169     StmtResult Body;
5170     if (PatternDecl->hasSkippedBody()) {
5171       ActOnSkippedFunctionBody(Function);
5172       Body = nullptr;
5173     } else {
5174       if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Function)) {
5175         // If this is a constructor, instantiate the member initializers.
5176         InstantiateMemInitializers(Ctor, cast<CXXConstructorDecl>(PatternDecl),
5177                                    TemplateArgs);
5178 
5179         // If this is an MS ABI dllexport default constructor, instantiate any
5180         // default arguments.
5181         if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
5182             Ctor->isDefaultConstructor()) {
5183           InstantiateDefaultCtorDefaultArgs(Ctor);
5184         }
5185       }
5186 
5187       // Instantiate the function body.
5188       Body = SubstStmt(Pattern, TemplateArgs);
5189 
5190       if (Body.isInvalid())
5191         Function->setInvalidDecl();
5192     }
5193     // FIXME: finishing the function body while in an expression evaluation
5194     // context seems wrong. Investigate more.
5195     ActOnFinishFunctionBody(Function, Body.get(), /*IsInstantiation=*/true);
5196 
5197     PerformDependentDiagnostics(PatternDecl, TemplateArgs);
5198 
5199     if (auto *Listener = getASTMutationListener())
5200       Listener->FunctionDefinitionInstantiated(Function);
5201 
5202     savedContext.pop();
5203   }
5204 
5205   DeclGroupRef DG(Function);
5206   Consumer.HandleTopLevelDecl(DG);
5207 
5208   // This class may have local implicit instantiations that need to be
5209   // instantiation within this scope.
5210   LocalInstantiations.perform();
5211   Scope.Exit();
5212   GlobalInstantiations.perform();
5213 }
5214 
BuildVarTemplateInstantiation(VarTemplateDecl * VarTemplate,VarDecl * FromVar,const TemplateArgumentList * PartialSpecArgs,const TemplateArgumentListInfo & TemplateArgsInfo,SmallVectorImpl<TemplateArgument> & Converted,SourceLocation PointOfInstantiation,LateInstantiatedAttrVec * LateAttrs,LocalInstantiationScope * StartingScope)5215 VarTemplateSpecializationDecl *Sema::BuildVarTemplateInstantiation(
5216     VarTemplateDecl *VarTemplate, VarDecl *FromVar,
5217     const TemplateArgumentList *PartialSpecArgs,
5218     const TemplateArgumentListInfo &TemplateArgsInfo,
5219     SmallVectorImpl<TemplateArgument> &Converted,
5220     SourceLocation PointOfInstantiation, LateInstantiatedAttrVec *LateAttrs,
5221     LocalInstantiationScope *StartingScope) {
5222   if (FromVar->isInvalidDecl())
5223     return nullptr;
5224 
5225   InstantiatingTemplate Inst(*this, PointOfInstantiation, FromVar);
5226   if (Inst.isInvalid())
5227     return nullptr;
5228 
5229   // Instantiate the first declaration of the variable template: for a partial
5230   // specialization of a static data member template, the first declaration may
5231   // or may not be the declaration in the class; if it's in the class, we want
5232   // to instantiate a member in the class (a declaration), and if it's outside,
5233   // we want to instantiate a definition.
5234   //
5235   // If we're instantiating an explicitly-specialized member template or member
5236   // partial specialization, don't do this. The member specialization completely
5237   // replaces the original declaration in this case.
5238   bool IsMemberSpec = false;
5239   MultiLevelTemplateArgumentList MultiLevelList;
5240   if (auto *PartialSpec =
5241           dyn_cast<VarTemplatePartialSpecializationDecl>(FromVar)) {
5242     assert(PartialSpecArgs);
5243     IsMemberSpec = PartialSpec->isMemberSpecialization();
5244     MultiLevelList.addOuterTemplateArguments(
5245         PartialSpec, PartialSpecArgs->asArray(), /*Final=*/false);
5246   } else {
5247     assert(VarTemplate == FromVar->getDescribedVarTemplate());
5248     IsMemberSpec = VarTemplate->isMemberSpecialization();
5249     MultiLevelList.addOuterTemplateArguments(VarTemplate, Converted,
5250                                              /*Final=*/false);
5251   }
5252   if (!IsMemberSpec)
5253     FromVar = FromVar->getFirstDecl();
5254 
5255   TemplateDeclInstantiator Instantiator(*this, FromVar->getDeclContext(),
5256                                         MultiLevelList);
5257 
5258   // TODO: Set LateAttrs and StartingScope ...
5259 
5260   return cast_or_null<VarTemplateSpecializationDecl>(
5261       Instantiator.VisitVarTemplateSpecializationDecl(
5262           VarTemplate, FromVar, TemplateArgsInfo, Converted));
5263 }
5264 
CompleteVarTemplateSpecializationDecl(VarTemplateSpecializationDecl * VarSpec,VarDecl * PatternDecl,const MultiLevelTemplateArgumentList & TemplateArgs)5265 VarTemplateSpecializationDecl *Sema::CompleteVarTemplateSpecializationDecl(
5266     VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl,
5267     const MultiLevelTemplateArgumentList &TemplateArgs) {
5268   assert(PatternDecl->isThisDeclarationADefinition() &&
5269          "don't have a definition to instantiate from");
5270 
5271   // Do substitution on the type of the declaration
5272   TypeSourceInfo *DI =
5273       SubstType(PatternDecl->getTypeSourceInfo(), TemplateArgs,
5274                 PatternDecl->getTypeSpecStartLoc(), PatternDecl->getDeclName());
5275   if (!DI)
5276     return nullptr;
5277 
5278   // Update the type of this variable template specialization.
5279   VarSpec->setType(DI->getType());
5280 
5281   // Convert the declaration into a definition now.
5282   VarSpec->setCompleteDefinition();
5283 
5284   // Instantiate the initializer.
5285   InstantiateVariableInitializer(VarSpec, PatternDecl, TemplateArgs);
5286 
5287   if (getLangOpts().OpenCL)
5288     deduceOpenCLAddressSpace(VarSpec);
5289 
5290   return VarSpec;
5291 }
5292 
BuildVariableInstantiation(VarDecl * NewVar,VarDecl * OldVar,const MultiLevelTemplateArgumentList & TemplateArgs,LateInstantiatedAttrVec * LateAttrs,DeclContext * Owner,LocalInstantiationScope * StartingScope,bool InstantiatingVarTemplate,VarTemplateSpecializationDecl * PrevDeclForVarTemplateSpecialization)5293 void Sema::BuildVariableInstantiation(
5294     VarDecl *NewVar, VarDecl *OldVar,
5295     const MultiLevelTemplateArgumentList &TemplateArgs,
5296     LateInstantiatedAttrVec *LateAttrs, DeclContext *Owner,
5297     LocalInstantiationScope *StartingScope,
5298     bool InstantiatingVarTemplate,
5299     VarTemplateSpecializationDecl *PrevDeclForVarTemplateSpecialization) {
5300   // Instantiating a partial specialization to produce a partial
5301   // specialization.
5302   bool InstantiatingVarTemplatePartialSpec =
5303       isa<VarTemplatePartialSpecializationDecl>(OldVar) &&
5304       isa<VarTemplatePartialSpecializationDecl>(NewVar);
5305   // Instantiating from a variable template (or partial specialization) to
5306   // produce a variable template specialization.
5307   bool InstantiatingSpecFromTemplate =
5308       isa<VarTemplateSpecializationDecl>(NewVar) &&
5309       (OldVar->getDescribedVarTemplate() ||
5310        isa<VarTemplatePartialSpecializationDecl>(OldVar));
5311 
5312   // If we are instantiating a local extern declaration, the
5313   // instantiation belongs lexically to the containing function.
5314   // If we are instantiating a static data member defined
5315   // out-of-line, the instantiation will have the same lexical
5316   // context (which will be a namespace scope) as the template.
5317   if (OldVar->isLocalExternDecl()) {
5318     NewVar->setLocalExternDecl();
5319     NewVar->setLexicalDeclContext(Owner);
5320   } else if (OldVar->isOutOfLine())
5321     NewVar->setLexicalDeclContext(OldVar->getLexicalDeclContext());
5322   NewVar->setTSCSpec(OldVar->getTSCSpec());
5323   NewVar->setInitStyle(OldVar->getInitStyle());
5324   NewVar->setCXXForRangeDecl(OldVar->isCXXForRangeDecl());
5325   NewVar->setObjCForDecl(OldVar->isObjCForDecl());
5326   NewVar->setConstexpr(OldVar->isConstexpr());
5327   NewVar->setInitCapture(OldVar->isInitCapture());
5328   NewVar->setPreviousDeclInSameBlockScope(
5329       OldVar->isPreviousDeclInSameBlockScope());
5330   NewVar->setAccess(OldVar->getAccess());
5331 
5332   if (!OldVar->isStaticDataMember()) {
5333     if (OldVar->isUsed(false))
5334       NewVar->setIsUsed();
5335     NewVar->setReferenced(OldVar->isReferenced());
5336   }
5337 
5338   InstantiateAttrs(TemplateArgs, OldVar, NewVar, LateAttrs, StartingScope);
5339 
5340   LookupResult Previous(
5341       *this, NewVar->getDeclName(), NewVar->getLocation(),
5342       NewVar->isLocalExternDecl() ? Sema::LookupRedeclarationWithLinkage
5343                                   : Sema::LookupOrdinaryName,
5344       NewVar->isLocalExternDecl() ? RedeclarationKind::ForExternalRedeclaration
5345                                   : forRedeclarationInCurContext());
5346 
5347   if (NewVar->isLocalExternDecl() && OldVar->getPreviousDecl() &&
5348       (!OldVar->getPreviousDecl()->getDeclContext()->isDependentContext() ||
5349        OldVar->getPreviousDecl()->getDeclContext()==OldVar->getDeclContext())) {
5350     // We have a previous declaration. Use that one, so we merge with the
5351     // right type.
5352     if (NamedDecl *NewPrev = FindInstantiatedDecl(
5353             NewVar->getLocation(), OldVar->getPreviousDecl(), TemplateArgs))
5354       Previous.addDecl(NewPrev);
5355   } else if (!isa<VarTemplateSpecializationDecl>(NewVar) &&
5356              OldVar->hasLinkage()) {
5357     LookupQualifiedName(Previous, NewVar->getDeclContext(), false);
5358   } else if (PrevDeclForVarTemplateSpecialization) {
5359     Previous.addDecl(PrevDeclForVarTemplateSpecialization);
5360   }
5361   CheckVariableDeclaration(NewVar, Previous);
5362 
5363   if (!InstantiatingVarTemplate) {
5364     NewVar->getLexicalDeclContext()->addHiddenDecl(NewVar);
5365     if (!NewVar->isLocalExternDecl() || !NewVar->getPreviousDecl())
5366       NewVar->getDeclContext()->makeDeclVisibleInContext(NewVar);
5367   }
5368 
5369   if (!OldVar->isOutOfLine()) {
5370     if (NewVar->getDeclContext()->isFunctionOrMethod())
5371       CurrentInstantiationScope->InstantiatedLocal(OldVar, NewVar);
5372   }
5373 
5374   // Link instantiations of static data members back to the template from
5375   // which they were instantiated.
5376   //
5377   // Don't do this when instantiating a template (we link the template itself
5378   // back in that case) nor when instantiating a static data member template
5379   // (that's not a member specialization).
5380   if (NewVar->isStaticDataMember() && !InstantiatingVarTemplate &&
5381       !InstantiatingSpecFromTemplate)
5382     NewVar->setInstantiationOfStaticDataMember(OldVar,
5383                                                TSK_ImplicitInstantiation);
5384 
5385   // If the pattern is an (in-class) explicit specialization, then the result
5386   // is also an explicit specialization.
5387   if (VarTemplateSpecializationDecl *OldVTSD =
5388           dyn_cast<VarTemplateSpecializationDecl>(OldVar)) {
5389     if (OldVTSD->getSpecializationKind() == TSK_ExplicitSpecialization &&
5390         !isa<VarTemplatePartialSpecializationDecl>(OldVTSD))
5391       cast<VarTemplateSpecializationDecl>(NewVar)->setSpecializationKind(
5392           TSK_ExplicitSpecialization);
5393   }
5394 
5395   // Forward the mangling number from the template to the instantiated decl.
5396   Context.setManglingNumber(NewVar, Context.getManglingNumber(OldVar));
5397   Context.setStaticLocalNumber(NewVar, Context.getStaticLocalNumber(OldVar));
5398 
5399   // Figure out whether to eagerly instantiate the initializer.
5400   if (InstantiatingVarTemplate || InstantiatingVarTemplatePartialSpec) {
5401     // We're producing a template. Don't instantiate the initializer yet.
5402   } else if (NewVar->getType()->isUndeducedType()) {
5403     // We need the type to complete the declaration of the variable.
5404     InstantiateVariableInitializer(NewVar, OldVar, TemplateArgs);
5405   } else if (InstantiatingSpecFromTemplate ||
5406              (OldVar->isInline() && OldVar->isThisDeclarationADefinition() &&
5407               !NewVar->isThisDeclarationADefinition())) {
5408     // Delay instantiation of the initializer for variable template
5409     // specializations or inline static data members until a definition of the
5410     // variable is needed.
5411   } else {
5412     InstantiateVariableInitializer(NewVar, OldVar, TemplateArgs);
5413   }
5414 
5415   // Diagnose unused local variables with dependent types, where the diagnostic
5416   // will have been deferred.
5417   if (!NewVar->isInvalidDecl() &&
5418       NewVar->getDeclContext()->isFunctionOrMethod() &&
5419       OldVar->getType()->isDependentType())
5420     DiagnoseUnusedDecl(NewVar);
5421 }
5422 
InstantiateVariableInitializer(VarDecl * Var,VarDecl * OldVar,const MultiLevelTemplateArgumentList & TemplateArgs)5423 void Sema::InstantiateVariableInitializer(
5424     VarDecl *Var, VarDecl *OldVar,
5425     const MultiLevelTemplateArgumentList &TemplateArgs) {
5426   if (ASTMutationListener *L = getASTContext().getASTMutationListener())
5427     L->VariableDefinitionInstantiated(Var);
5428 
5429   // We propagate the 'inline' flag with the initializer, because it
5430   // would otherwise imply that the variable is a definition for a
5431   // non-static data member.
5432   if (OldVar->isInlineSpecified())
5433     Var->setInlineSpecified();
5434   else if (OldVar->isInline())
5435     Var->setImplicitlyInline();
5436 
5437   if (OldVar->getInit()) {
5438     EnterExpressionEvaluationContext Evaluated(
5439         *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated, Var);
5440 
5441     keepInLifetimeExtendingContext();
5442     // Instantiate the initializer.
5443     ExprResult Init;
5444 
5445     {
5446       ContextRAII SwitchContext(*this, Var->getDeclContext());
5447       Init = SubstInitializer(OldVar->getInit(), TemplateArgs,
5448                               OldVar->getInitStyle() == VarDecl::CallInit);
5449     }
5450 
5451     if (!Init.isInvalid()) {
5452       Expr *InitExpr = Init.get();
5453 
5454       if (Var->hasAttr<DLLImportAttr>() &&
5455           (!InitExpr ||
5456            !InitExpr->isConstantInitializer(getASTContext(), false))) {
5457         // Do not dynamically initialize dllimport variables.
5458       } else if (InitExpr) {
5459         bool DirectInit = OldVar->isDirectInit();
5460         AddInitializerToDecl(Var, InitExpr, DirectInit);
5461       } else
5462         ActOnUninitializedDecl(Var);
5463     } else {
5464       // FIXME: Not too happy about invalidating the declaration
5465       // because of a bogus initializer.
5466       Var->setInvalidDecl();
5467     }
5468   } else {
5469     // `inline` variables are a definition and declaration all in one; we won't
5470     // pick up an initializer from anywhere else.
5471     if (Var->isStaticDataMember() && !Var->isInline()) {
5472       if (!Var->isOutOfLine())
5473         return;
5474 
5475       // If the declaration inside the class had an initializer, don't add
5476       // another one to the out-of-line definition.
5477       if (OldVar->getFirstDecl()->hasInit())
5478         return;
5479     }
5480 
5481     // We'll add an initializer to a for-range declaration later.
5482     if (Var->isCXXForRangeDecl() || Var->isObjCForDecl())
5483       return;
5484 
5485     ActOnUninitializedDecl(Var);
5486   }
5487 
5488   if (getLangOpts().CUDA)
5489     CUDA().checkAllowedInitializer(Var);
5490 }
5491 
InstantiateVariableDefinition(SourceLocation PointOfInstantiation,VarDecl * Var,bool Recursive,bool DefinitionRequired,bool AtEndOfTU)5492 void Sema::InstantiateVariableDefinition(SourceLocation PointOfInstantiation,
5493                                          VarDecl *Var, bool Recursive,
5494                                       bool DefinitionRequired, bool AtEndOfTU) {
5495   if (Var->isInvalidDecl())
5496     return;
5497 
5498   // Never instantiate an explicitly-specialized entity.
5499   TemplateSpecializationKind TSK =
5500       Var->getTemplateSpecializationKindForInstantiation();
5501   if (TSK == TSK_ExplicitSpecialization)
5502     return;
5503 
5504   // Find the pattern and the arguments to substitute into it.
5505   VarDecl *PatternDecl = Var->getTemplateInstantiationPattern();
5506   assert(PatternDecl && "no pattern for templated variable");
5507   MultiLevelTemplateArgumentList TemplateArgs =
5508       getTemplateInstantiationArgs(Var);
5509 
5510   VarTemplateSpecializationDecl *VarSpec =
5511       dyn_cast<VarTemplateSpecializationDecl>(Var);
5512   if (VarSpec) {
5513     // If this is a static data member template, there might be an
5514     // uninstantiated initializer on the declaration. If so, instantiate
5515     // it now.
5516     //
5517     // FIXME: This largely duplicates what we would do below. The difference
5518     // is that along this path we may instantiate an initializer from an
5519     // in-class declaration of the template and instantiate the definition
5520     // from a separate out-of-class definition.
5521     if (PatternDecl->isStaticDataMember() &&
5522         (PatternDecl = PatternDecl->getFirstDecl())->hasInit() &&
5523         !Var->hasInit()) {
5524       // FIXME: Factor out the duplicated instantiation context setup/tear down
5525       // code here.
5526       InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
5527       if (Inst.isInvalid() || Inst.isAlreadyInstantiating())
5528         return;
5529       PrettyDeclStackTraceEntry CrashInfo(Context, Var, SourceLocation(),
5530                                           "instantiating variable initializer");
5531 
5532       // The instantiation is visible here, even if it was first declared in an
5533       // unimported module.
5534       Var->setVisibleDespiteOwningModule();
5535 
5536       // If we're performing recursive template instantiation, create our own
5537       // queue of pending implicit instantiations that we will instantiate
5538       // later, while we're still within our own instantiation context.
5539       GlobalEagerInstantiationScope GlobalInstantiations(*this,
5540                                                          /*Enabled=*/Recursive);
5541       LocalInstantiationScope Local(*this);
5542       LocalEagerInstantiationScope LocalInstantiations(*this);
5543 
5544       // Enter the scope of this instantiation. We don't use
5545       // PushDeclContext because we don't have a scope.
5546       ContextRAII PreviousContext(*this, Var->getDeclContext());
5547       InstantiateVariableInitializer(Var, PatternDecl, TemplateArgs);
5548       PreviousContext.pop();
5549 
5550       // This variable may have local implicit instantiations that need to be
5551       // instantiated within this scope.
5552       LocalInstantiations.perform();
5553       Local.Exit();
5554       GlobalInstantiations.perform();
5555     }
5556   } else {
5557     assert(Var->isStaticDataMember() && PatternDecl->isStaticDataMember() &&
5558            "not a static data member?");
5559   }
5560 
5561   VarDecl *Def = PatternDecl->getDefinition(getASTContext());
5562 
5563   // If we don't have a definition of the variable template, we won't perform
5564   // any instantiation. Rather, we rely on the user to instantiate this
5565   // definition (or provide a specialization for it) in another translation
5566   // unit.
5567   if (!Def && !DefinitionRequired) {
5568     if (TSK == TSK_ExplicitInstantiationDefinition) {
5569       PendingInstantiations.push_back(
5570         std::make_pair(Var, PointOfInstantiation));
5571     } else if (TSK == TSK_ImplicitInstantiation) {
5572       // Warn about missing definition at the end of translation unit.
5573       if (AtEndOfTU && !getDiagnostics().hasErrorOccurred() &&
5574           !getSourceManager().isInSystemHeader(PatternDecl->getBeginLoc())) {
5575         Diag(PointOfInstantiation, diag::warn_var_template_missing)
5576           << Var;
5577         Diag(PatternDecl->getLocation(), diag::note_forward_template_decl);
5578         if (getLangOpts().CPlusPlus11)
5579           Diag(PointOfInstantiation, diag::note_inst_declaration_hint) << Var;
5580       }
5581       return;
5582     }
5583   }
5584 
5585   // FIXME: We need to track the instantiation stack in order to know which
5586   // definitions should be visible within this instantiation.
5587   // FIXME: Produce diagnostics when Var->getInstantiatedFromStaticDataMember().
5588   if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Var,
5589                                      /*InstantiatedFromMember*/false,
5590                                      PatternDecl, Def, TSK,
5591                                      /*Complain*/DefinitionRequired))
5592     return;
5593 
5594   // C++11 [temp.explicit]p10:
5595   //   Except for inline functions, const variables of literal types, variables
5596   //   of reference types, [...] explicit instantiation declarations
5597   //   have the effect of suppressing the implicit instantiation of the entity
5598   //   to which they refer.
5599   //
5600   // FIXME: That's not exactly the same as "might be usable in constant
5601   // expressions", which only allows constexpr variables and const integral
5602   // types, not arbitrary const literal types.
5603   if (TSK == TSK_ExplicitInstantiationDeclaration &&
5604       !Var->mightBeUsableInConstantExpressions(getASTContext()))
5605     return;
5606 
5607   // Make sure to pass the instantiated variable to the consumer at the end.
5608   struct PassToConsumerRAII {
5609     ASTConsumer &Consumer;
5610     VarDecl *Var;
5611 
5612     PassToConsumerRAII(ASTConsumer &Consumer, VarDecl *Var)
5613       : Consumer(Consumer), Var(Var) { }
5614 
5615     ~PassToConsumerRAII() {
5616       Consumer.HandleCXXStaticMemberVarInstantiation(Var);
5617     }
5618   } PassToConsumerRAII(Consumer, Var);
5619 
5620   // If we already have a definition, we're done.
5621   if (VarDecl *Def = Var->getDefinition()) {
5622     // We may be explicitly instantiating something we've already implicitly
5623     // instantiated.
5624     Def->setTemplateSpecializationKind(Var->getTemplateSpecializationKind(),
5625                                        PointOfInstantiation);
5626     return;
5627   }
5628 
5629   InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
5630   if (Inst.isInvalid() || Inst.isAlreadyInstantiating())
5631     return;
5632   PrettyDeclStackTraceEntry CrashInfo(Context, Var, SourceLocation(),
5633                                       "instantiating variable definition");
5634 
5635   // If we're performing recursive template instantiation, create our own
5636   // queue of pending implicit instantiations that we will instantiate later,
5637   // while we're still within our own instantiation context.
5638   GlobalEagerInstantiationScope GlobalInstantiations(*this,
5639                                                      /*Enabled=*/Recursive);
5640 
5641   // Enter the scope of this instantiation. We don't use
5642   // PushDeclContext because we don't have a scope.
5643   ContextRAII PreviousContext(*this, Var->getDeclContext());
5644   LocalInstantiationScope Local(*this);
5645 
5646   LocalEagerInstantiationScope LocalInstantiations(*this);
5647 
5648   VarDecl *OldVar = Var;
5649   if (Def->isStaticDataMember() && !Def->isOutOfLine()) {
5650     // We're instantiating an inline static data member whose definition was
5651     // provided inside the class.
5652     InstantiateVariableInitializer(Var, Def, TemplateArgs);
5653   } else if (!VarSpec) {
5654     Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(),
5655                                           TemplateArgs));
5656   } else if (Var->isStaticDataMember() &&
5657              Var->getLexicalDeclContext()->isRecord()) {
5658     // We need to instantiate the definition of a static data member template,
5659     // and all we have is the in-class declaration of it. Instantiate a separate
5660     // declaration of the definition.
5661     TemplateDeclInstantiator Instantiator(*this, Var->getDeclContext(),
5662                                           TemplateArgs);
5663 
5664     TemplateArgumentListInfo TemplateArgInfo;
5665     if (const ASTTemplateArgumentListInfo *ArgInfo =
5666             VarSpec->getTemplateArgsAsWritten()) {
5667       TemplateArgInfo.setLAngleLoc(ArgInfo->getLAngleLoc());
5668       TemplateArgInfo.setRAngleLoc(ArgInfo->getRAngleLoc());
5669       for (const TemplateArgumentLoc &Arg : ArgInfo->arguments())
5670         TemplateArgInfo.addArgument(Arg);
5671     }
5672 
5673     Var = cast_or_null<VarDecl>(Instantiator.VisitVarTemplateSpecializationDecl(
5674         VarSpec->getSpecializedTemplate(), Def, TemplateArgInfo,
5675         VarSpec->getTemplateArgs().asArray(), VarSpec));
5676     if (Var) {
5677       llvm::PointerUnion<VarTemplateDecl *,
5678                          VarTemplatePartialSpecializationDecl *> PatternPtr =
5679           VarSpec->getSpecializedTemplateOrPartial();
5680       if (VarTemplatePartialSpecializationDecl *Partial =
5681           PatternPtr.dyn_cast<VarTemplatePartialSpecializationDecl *>())
5682         cast<VarTemplateSpecializationDecl>(Var)->setInstantiationOf(
5683             Partial, &VarSpec->getTemplateInstantiationArgs());
5684 
5685       // Attach the initializer.
5686       InstantiateVariableInitializer(Var, Def, TemplateArgs);
5687     }
5688   } else
5689     // Complete the existing variable's definition with an appropriately
5690     // substituted type and initializer.
5691     Var = CompleteVarTemplateSpecializationDecl(VarSpec, Def, TemplateArgs);
5692 
5693   PreviousContext.pop();
5694 
5695   if (Var) {
5696     PassToConsumerRAII.Var = Var;
5697     Var->setTemplateSpecializationKind(OldVar->getTemplateSpecializationKind(),
5698                                        OldVar->getPointOfInstantiation());
5699   }
5700 
5701   // This variable may have local implicit instantiations that need to be
5702   // instantiated within this scope.
5703   LocalInstantiations.perform();
5704   Local.Exit();
5705   GlobalInstantiations.perform();
5706 }
5707 
5708 void
InstantiateMemInitializers(CXXConstructorDecl * New,const CXXConstructorDecl * Tmpl,const MultiLevelTemplateArgumentList & TemplateArgs)5709 Sema::InstantiateMemInitializers(CXXConstructorDecl *New,
5710                                  const CXXConstructorDecl *Tmpl,
5711                            const MultiLevelTemplateArgumentList &TemplateArgs) {
5712 
5713   SmallVector<CXXCtorInitializer*, 4> NewInits;
5714   bool AnyErrors = Tmpl->isInvalidDecl();
5715 
5716   // Instantiate all the initializers.
5717   for (const auto *Init : Tmpl->inits()) {
5718     // Only instantiate written initializers, let Sema re-construct implicit
5719     // ones.
5720     if (!Init->isWritten())
5721       continue;
5722 
5723     SourceLocation EllipsisLoc;
5724 
5725     if (Init->isPackExpansion()) {
5726       // This is a pack expansion. We should expand it now.
5727       TypeLoc BaseTL = Init->getTypeSourceInfo()->getTypeLoc();
5728       SmallVector<UnexpandedParameterPack, 4> Unexpanded;
5729       collectUnexpandedParameterPacks(BaseTL, Unexpanded);
5730       collectUnexpandedParameterPacks(Init->getInit(), Unexpanded);
5731       bool ShouldExpand = false;
5732       bool RetainExpansion = false;
5733       std::optional<unsigned> NumExpansions;
5734       if (CheckParameterPacksForExpansion(Init->getEllipsisLoc(),
5735                                           BaseTL.getSourceRange(),
5736                                           Unexpanded,
5737                                           TemplateArgs, ShouldExpand,
5738                                           RetainExpansion,
5739                                           NumExpansions)) {
5740         AnyErrors = true;
5741         New->setInvalidDecl();
5742         continue;
5743       }
5744       assert(ShouldExpand && "Partial instantiation of base initializer?");
5745 
5746       // Loop over all of the arguments in the argument pack(s),
5747       for (unsigned I = 0; I != *NumExpansions; ++I) {
5748         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
5749 
5750         // Instantiate the initializer.
5751         ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs,
5752                                                /*CXXDirectInit=*/true);
5753         if (TempInit.isInvalid()) {
5754           AnyErrors = true;
5755           break;
5756         }
5757 
5758         // Instantiate the base type.
5759         TypeSourceInfo *BaseTInfo = SubstType(Init->getTypeSourceInfo(),
5760                                               TemplateArgs,
5761                                               Init->getSourceLocation(),
5762                                               New->getDeclName());
5763         if (!BaseTInfo) {
5764           AnyErrors = true;
5765           break;
5766         }
5767 
5768         // Build the initializer.
5769         MemInitResult NewInit = BuildBaseInitializer(BaseTInfo->getType(),
5770                                                      BaseTInfo, TempInit.get(),
5771                                                      New->getParent(),
5772                                                      SourceLocation());
5773         if (NewInit.isInvalid()) {
5774           AnyErrors = true;
5775           break;
5776         }
5777 
5778         NewInits.push_back(NewInit.get());
5779       }
5780 
5781       continue;
5782     }
5783 
5784     // Instantiate the initializer.
5785     ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs,
5786                                            /*CXXDirectInit=*/true);
5787     if (TempInit.isInvalid()) {
5788       AnyErrors = true;
5789       continue;
5790     }
5791 
5792     MemInitResult NewInit;
5793     if (Init->isDelegatingInitializer() || Init->isBaseInitializer()) {
5794       TypeSourceInfo *TInfo = SubstType(Init->getTypeSourceInfo(),
5795                                         TemplateArgs,
5796                                         Init->getSourceLocation(),
5797                                         New->getDeclName());
5798       if (!TInfo) {
5799         AnyErrors = true;
5800         New->setInvalidDecl();
5801         continue;
5802       }
5803 
5804       if (Init->isBaseInitializer())
5805         NewInit = BuildBaseInitializer(TInfo->getType(), TInfo, TempInit.get(),
5806                                        New->getParent(), EllipsisLoc);
5807       else
5808         NewInit = BuildDelegatingInitializer(TInfo, TempInit.get(),
5809                                   cast<CXXRecordDecl>(CurContext->getParent()));
5810     } else if (Init->isMemberInitializer()) {
5811       FieldDecl *Member = cast_or_null<FieldDecl>(FindInstantiatedDecl(
5812                                                      Init->getMemberLocation(),
5813                                                      Init->getMember(),
5814                                                      TemplateArgs));
5815       if (!Member) {
5816         AnyErrors = true;
5817         New->setInvalidDecl();
5818         continue;
5819       }
5820 
5821       NewInit = BuildMemberInitializer(Member, TempInit.get(),
5822                                        Init->getSourceLocation());
5823     } else if (Init->isIndirectMemberInitializer()) {
5824       IndirectFieldDecl *IndirectMember =
5825          cast_or_null<IndirectFieldDecl>(FindInstantiatedDecl(
5826                                  Init->getMemberLocation(),
5827                                  Init->getIndirectMember(), TemplateArgs));
5828 
5829       if (!IndirectMember) {
5830         AnyErrors = true;
5831         New->setInvalidDecl();
5832         continue;
5833       }
5834 
5835       NewInit = BuildMemberInitializer(IndirectMember, TempInit.get(),
5836                                        Init->getSourceLocation());
5837     }
5838 
5839     if (NewInit.isInvalid()) {
5840       AnyErrors = true;
5841       New->setInvalidDecl();
5842     } else {
5843       NewInits.push_back(NewInit.get());
5844     }
5845   }
5846 
5847   // Assign all the initializers to the new constructor.
5848   ActOnMemInitializers(New,
5849                        /*FIXME: ColonLoc */
5850                        SourceLocation(),
5851                        NewInits,
5852                        AnyErrors);
5853 }
5854 
5855 // TODO: this could be templated if the various decl types used the
5856 // same method name.
isInstantiationOf(ClassTemplateDecl * Pattern,ClassTemplateDecl * Instance)5857 static bool isInstantiationOf(ClassTemplateDecl *Pattern,
5858                               ClassTemplateDecl *Instance) {
5859   Pattern = Pattern->getCanonicalDecl();
5860 
5861   do {
5862     Instance = Instance->getCanonicalDecl();
5863     if (Pattern == Instance) return true;
5864     Instance = Instance->getInstantiatedFromMemberTemplate();
5865   } while (Instance);
5866 
5867   return false;
5868 }
5869 
isInstantiationOf(FunctionTemplateDecl * Pattern,FunctionTemplateDecl * Instance)5870 static bool isInstantiationOf(FunctionTemplateDecl *Pattern,
5871                               FunctionTemplateDecl *Instance) {
5872   Pattern = Pattern->getCanonicalDecl();
5873 
5874   do {
5875     Instance = Instance->getCanonicalDecl();
5876     if (Pattern == Instance) return true;
5877     Instance = Instance->getInstantiatedFromMemberTemplate();
5878   } while (Instance);
5879 
5880   return false;
5881 }
5882 
5883 static bool
isInstantiationOf(ClassTemplatePartialSpecializationDecl * Pattern,ClassTemplatePartialSpecializationDecl * Instance)5884 isInstantiationOf(ClassTemplatePartialSpecializationDecl *Pattern,
5885                   ClassTemplatePartialSpecializationDecl *Instance) {
5886   Pattern
5887     = cast<ClassTemplatePartialSpecializationDecl>(Pattern->getCanonicalDecl());
5888   do {
5889     Instance = cast<ClassTemplatePartialSpecializationDecl>(
5890                                                 Instance->getCanonicalDecl());
5891     if (Pattern == Instance)
5892       return true;
5893     Instance = Instance->getInstantiatedFromMember();
5894   } while (Instance);
5895 
5896   return false;
5897 }
5898 
isInstantiationOf(CXXRecordDecl * Pattern,CXXRecordDecl * Instance)5899 static bool isInstantiationOf(CXXRecordDecl *Pattern,
5900                               CXXRecordDecl *Instance) {
5901   Pattern = Pattern->getCanonicalDecl();
5902 
5903   do {
5904     Instance = Instance->getCanonicalDecl();
5905     if (Pattern == Instance) return true;
5906     Instance = Instance->getInstantiatedFromMemberClass();
5907   } while (Instance);
5908 
5909   return false;
5910 }
5911 
isInstantiationOf(FunctionDecl * Pattern,FunctionDecl * Instance)5912 static bool isInstantiationOf(FunctionDecl *Pattern,
5913                               FunctionDecl *Instance) {
5914   Pattern = Pattern->getCanonicalDecl();
5915 
5916   do {
5917     Instance = Instance->getCanonicalDecl();
5918     if (Pattern == Instance) return true;
5919     Instance = Instance->getInstantiatedFromMemberFunction();
5920   } while (Instance);
5921 
5922   return false;
5923 }
5924 
isInstantiationOf(EnumDecl * Pattern,EnumDecl * Instance)5925 static bool isInstantiationOf(EnumDecl *Pattern,
5926                               EnumDecl *Instance) {
5927   Pattern = Pattern->getCanonicalDecl();
5928 
5929   do {
5930     Instance = Instance->getCanonicalDecl();
5931     if (Pattern == Instance) return true;
5932     Instance = Instance->getInstantiatedFromMemberEnum();
5933   } while (Instance);
5934 
5935   return false;
5936 }
5937 
isInstantiationOf(UsingShadowDecl * Pattern,UsingShadowDecl * Instance,ASTContext & C)5938 static bool isInstantiationOf(UsingShadowDecl *Pattern,
5939                               UsingShadowDecl *Instance,
5940                               ASTContext &C) {
5941   return declaresSameEntity(C.getInstantiatedFromUsingShadowDecl(Instance),
5942                             Pattern);
5943 }
5944 
isInstantiationOf(UsingDecl * Pattern,UsingDecl * Instance,ASTContext & C)5945 static bool isInstantiationOf(UsingDecl *Pattern, UsingDecl *Instance,
5946                               ASTContext &C) {
5947   return declaresSameEntity(C.getInstantiatedFromUsingDecl(Instance), Pattern);
5948 }
5949 
5950 template<typename T>
isInstantiationOfUnresolvedUsingDecl(T * Pattern,Decl * Other,ASTContext & Ctx)5951 static bool isInstantiationOfUnresolvedUsingDecl(T *Pattern, Decl *Other,
5952                                                  ASTContext &Ctx) {
5953   // An unresolved using declaration can instantiate to an unresolved using
5954   // declaration, or to a using declaration or a using declaration pack.
5955   //
5956   // Multiple declarations can claim to be instantiated from an unresolved
5957   // using declaration if it's a pack expansion. We want the UsingPackDecl
5958   // in that case, not the individual UsingDecls within the pack.
5959   bool OtherIsPackExpansion;
5960   NamedDecl *OtherFrom;
5961   if (auto *OtherUUD = dyn_cast<T>(Other)) {
5962     OtherIsPackExpansion = OtherUUD->isPackExpansion();
5963     OtherFrom = Ctx.getInstantiatedFromUsingDecl(OtherUUD);
5964   } else if (auto *OtherUPD = dyn_cast<UsingPackDecl>(Other)) {
5965     OtherIsPackExpansion = true;
5966     OtherFrom = OtherUPD->getInstantiatedFromUsingDecl();
5967   } else if (auto *OtherUD = dyn_cast<UsingDecl>(Other)) {
5968     OtherIsPackExpansion = false;
5969     OtherFrom = Ctx.getInstantiatedFromUsingDecl(OtherUD);
5970   } else {
5971     return false;
5972   }
5973   return Pattern->isPackExpansion() == OtherIsPackExpansion &&
5974          declaresSameEntity(OtherFrom, Pattern);
5975 }
5976 
isInstantiationOfStaticDataMember(VarDecl * Pattern,VarDecl * Instance)5977 static bool isInstantiationOfStaticDataMember(VarDecl *Pattern,
5978                                               VarDecl *Instance) {
5979   assert(Instance->isStaticDataMember());
5980 
5981   Pattern = Pattern->getCanonicalDecl();
5982 
5983   do {
5984     Instance = Instance->getCanonicalDecl();
5985     if (Pattern == Instance) return true;
5986     Instance = Instance->getInstantiatedFromStaticDataMember();
5987   } while (Instance);
5988 
5989   return false;
5990 }
5991 
5992 // Other is the prospective instantiation
5993 // D is the prospective pattern
isInstantiationOf(ASTContext & Ctx,NamedDecl * D,Decl * Other)5994 static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) {
5995   if (auto *UUD = dyn_cast<UnresolvedUsingTypenameDecl>(D))
5996     return isInstantiationOfUnresolvedUsingDecl(UUD, Other, Ctx);
5997 
5998   if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(D))
5999     return isInstantiationOfUnresolvedUsingDecl(UUD, Other, Ctx);
6000 
6001   if (D->getKind() != Other->getKind())
6002     return false;
6003 
6004   if (auto *Record = dyn_cast<CXXRecordDecl>(Other))
6005     return isInstantiationOf(cast<CXXRecordDecl>(D), Record);
6006 
6007   if (auto *Function = dyn_cast<FunctionDecl>(Other))
6008     return isInstantiationOf(cast<FunctionDecl>(D), Function);
6009 
6010   if (auto *Enum = dyn_cast<EnumDecl>(Other))
6011     return isInstantiationOf(cast<EnumDecl>(D), Enum);
6012 
6013   if (auto *Var = dyn_cast<VarDecl>(Other))
6014     if (Var->isStaticDataMember())
6015       return isInstantiationOfStaticDataMember(cast<VarDecl>(D), Var);
6016 
6017   if (auto *Temp = dyn_cast<ClassTemplateDecl>(Other))
6018     return isInstantiationOf(cast<ClassTemplateDecl>(D), Temp);
6019 
6020   if (auto *Temp = dyn_cast<FunctionTemplateDecl>(Other))
6021     return isInstantiationOf(cast<FunctionTemplateDecl>(D), Temp);
6022 
6023   if (auto *PartialSpec =
6024           dyn_cast<ClassTemplatePartialSpecializationDecl>(Other))
6025     return isInstantiationOf(cast<ClassTemplatePartialSpecializationDecl>(D),
6026                              PartialSpec);
6027 
6028   if (auto *Field = dyn_cast<FieldDecl>(Other)) {
6029     if (!Field->getDeclName()) {
6030       // This is an unnamed field.
6031       return declaresSameEntity(Ctx.getInstantiatedFromUnnamedFieldDecl(Field),
6032                                 cast<FieldDecl>(D));
6033     }
6034   }
6035 
6036   if (auto *Using = dyn_cast<UsingDecl>(Other))
6037     return isInstantiationOf(cast<UsingDecl>(D), Using, Ctx);
6038 
6039   if (auto *Shadow = dyn_cast<UsingShadowDecl>(Other))
6040     return isInstantiationOf(cast<UsingShadowDecl>(D), Shadow, Ctx);
6041 
6042   return D->getDeclName() &&
6043          D->getDeclName() == cast<NamedDecl>(Other)->getDeclName();
6044 }
6045 
6046 template<typename ForwardIterator>
findInstantiationOf(ASTContext & Ctx,NamedDecl * D,ForwardIterator first,ForwardIterator last)6047 static NamedDecl *findInstantiationOf(ASTContext &Ctx,
6048                                       NamedDecl *D,
6049                                       ForwardIterator first,
6050                                       ForwardIterator last) {
6051   for (; first != last; ++first)
6052     if (isInstantiationOf(Ctx, D, *first))
6053       return cast<NamedDecl>(*first);
6054 
6055   return nullptr;
6056 }
6057 
FindInstantiatedContext(SourceLocation Loc,DeclContext * DC,const MultiLevelTemplateArgumentList & TemplateArgs)6058 DeclContext *Sema::FindInstantiatedContext(SourceLocation Loc, DeclContext* DC,
6059                           const MultiLevelTemplateArgumentList &TemplateArgs) {
6060   if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) {
6061     Decl* ID = FindInstantiatedDecl(Loc, D, TemplateArgs, true);
6062     return cast_or_null<DeclContext>(ID);
6063   } else return DC;
6064 }
6065 
6066 /// Determine whether the given context is dependent on template parameters at
6067 /// level \p Level or below.
6068 ///
6069 /// Sometimes we only substitute an inner set of template arguments and leave
6070 /// the outer templates alone. In such cases, contexts dependent only on the
6071 /// outer levels are not effectively dependent.
isDependentContextAtLevel(DeclContext * DC,unsigned Level)6072 static bool isDependentContextAtLevel(DeclContext *DC, unsigned Level) {
6073   if (!DC->isDependentContext())
6074     return false;
6075   if (!Level)
6076     return true;
6077   return cast<Decl>(DC)->getTemplateDepth() > Level;
6078 }
6079 
FindInstantiatedDecl(SourceLocation Loc,NamedDecl * D,const MultiLevelTemplateArgumentList & TemplateArgs,bool FindingInstantiatedContext)6080 NamedDecl *Sema::FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
6081                           const MultiLevelTemplateArgumentList &TemplateArgs,
6082                           bool FindingInstantiatedContext) {
6083   DeclContext *ParentDC = D->getDeclContext();
6084   // Determine whether our parent context depends on any of the template
6085   // arguments we're currently substituting.
6086   bool ParentDependsOnArgs = isDependentContextAtLevel(
6087       ParentDC, TemplateArgs.getNumRetainedOuterLevels());
6088   // FIXME: Parameters of pointer to functions (y below) that are themselves
6089   // parameters (p below) can have their ParentDC set to the translation-unit
6090   // - thus we can not consistently check if the ParentDC of such a parameter
6091   // is Dependent or/and a FunctionOrMethod.
6092   // For e.g. this code, during Template argument deduction tries to
6093   // find an instantiated decl for (T y) when the ParentDC for y is
6094   // the translation unit.
6095   //   e.g. template <class T> void Foo(auto (*p)(T y) -> decltype(y())) {}
6096   //   float baz(float(*)()) { return 0.0; }
6097   //   Foo(baz);
6098   // The better fix here is perhaps to ensure that a ParmVarDecl, by the time
6099   // it gets here, always has a FunctionOrMethod as its ParentDC??
6100   // For now:
6101   //  - as long as we have a ParmVarDecl whose parent is non-dependent and
6102   //    whose type is not instantiation dependent, do nothing to the decl
6103   //  - otherwise find its instantiated decl.
6104   if (isa<ParmVarDecl>(D) && !ParentDependsOnArgs &&
6105       !cast<ParmVarDecl>(D)->getType()->isInstantiationDependentType())
6106     return D;
6107   if (isa<ParmVarDecl>(D) || isa<NonTypeTemplateParmDecl>(D) ||
6108       isa<TemplateTypeParmDecl>(D) || isa<TemplateTemplateParmDecl>(D) ||
6109       (ParentDependsOnArgs && (ParentDC->isFunctionOrMethod() ||
6110                                isa<OMPDeclareReductionDecl>(ParentDC) ||
6111                                isa<OMPDeclareMapperDecl>(ParentDC))) ||
6112       (isa<CXXRecordDecl>(D) && cast<CXXRecordDecl>(D)->isLambda() &&
6113        cast<CXXRecordDecl>(D)->getTemplateDepth() >
6114            TemplateArgs.getNumRetainedOuterLevels())) {
6115     // D is a local of some kind. Look into the map of local
6116     // declarations to their instantiations.
6117     if (CurrentInstantiationScope) {
6118       if (auto Found = CurrentInstantiationScope->findInstantiationOf(D)) {
6119         if (Decl *FD = Found->dyn_cast<Decl *>())
6120           return cast<NamedDecl>(FD);
6121 
6122         int PackIdx = ArgumentPackSubstitutionIndex;
6123         assert(PackIdx != -1 &&
6124                "found declaration pack but not pack expanding");
6125         typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
6126         return cast<NamedDecl>((*Found->get<DeclArgumentPack *>())[PackIdx]);
6127       }
6128     }
6129 
6130     // If we're performing a partial substitution during template argument
6131     // deduction, we may not have values for template parameters yet. They
6132     // just map to themselves.
6133     if (isa<NonTypeTemplateParmDecl>(D) || isa<TemplateTypeParmDecl>(D) ||
6134         isa<TemplateTemplateParmDecl>(D))
6135       return D;
6136 
6137     if (D->isInvalidDecl())
6138       return nullptr;
6139 
6140     // Normally this function only searches for already instantiated declaration
6141     // however we have to make an exclusion for local types used before
6142     // definition as in the code:
6143     //
6144     //   template<typename T> void f1() {
6145     //     void g1(struct x1);
6146     //     struct x1 {};
6147     //   }
6148     //
6149     // In this case instantiation of the type of 'g1' requires definition of
6150     // 'x1', which is defined later. Error recovery may produce an enum used
6151     // before definition. In these cases we need to instantiate relevant
6152     // declarations here.
6153     bool NeedInstantiate = false;
6154     if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
6155       NeedInstantiate = RD->isLocalClass();
6156     else if (isa<TypedefNameDecl>(D) &&
6157              isa<CXXDeductionGuideDecl>(D->getDeclContext()))
6158       NeedInstantiate = true;
6159     else
6160       NeedInstantiate = isa<EnumDecl>(D);
6161     if (NeedInstantiate) {
6162       Decl *Inst = SubstDecl(D, CurContext, TemplateArgs);
6163       CurrentInstantiationScope->InstantiatedLocal(D, Inst);
6164       return cast<TypeDecl>(Inst);
6165     }
6166 
6167     // If we didn't find the decl, then we must have a label decl that hasn't
6168     // been found yet.  Lazily instantiate it and return it now.
6169     assert(isa<LabelDecl>(D));
6170 
6171     Decl *Inst = SubstDecl(D, CurContext, TemplateArgs);
6172     assert(Inst && "Failed to instantiate label??");
6173 
6174     CurrentInstantiationScope->InstantiatedLocal(D, Inst);
6175     return cast<LabelDecl>(Inst);
6176   }
6177 
6178   if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
6179     if (!Record->isDependentContext())
6180       return D;
6181 
6182     // Determine whether this record is the "templated" declaration describing
6183     // a class template or class template specialization.
6184     ClassTemplateDecl *ClassTemplate = Record->getDescribedClassTemplate();
6185     if (ClassTemplate)
6186       ClassTemplate = ClassTemplate->getCanonicalDecl();
6187     else if (ClassTemplateSpecializationDecl *Spec =
6188                  dyn_cast<ClassTemplateSpecializationDecl>(Record))
6189       ClassTemplate = Spec->getSpecializedTemplate()->getCanonicalDecl();
6190 
6191     // Walk the current context to find either the record or an instantiation of
6192     // it.
6193     DeclContext *DC = CurContext;
6194     while (!DC->isFileContext()) {
6195       // If we're performing substitution while we're inside the template
6196       // definition, we'll find our own context. We're done.
6197       if (DC->Equals(Record))
6198         return Record;
6199 
6200       if (CXXRecordDecl *InstRecord = dyn_cast<CXXRecordDecl>(DC)) {
6201         // Check whether we're in the process of instantiating a class template
6202         // specialization of the template we're mapping.
6203         if (ClassTemplateSpecializationDecl *InstSpec
6204                       = dyn_cast<ClassTemplateSpecializationDecl>(InstRecord)){
6205           ClassTemplateDecl *SpecTemplate = InstSpec->getSpecializedTemplate();
6206           if (ClassTemplate && isInstantiationOf(ClassTemplate, SpecTemplate))
6207             return InstRecord;
6208         }
6209 
6210         // Check whether we're in the process of instantiating a member class.
6211         if (isInstantiationOf(Record, InstRecord))
6212           return InstRecord;
6213       }
6214 
6215       // Move to the outer template scope.
6216       if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC)) {
6217         if (FD->getFriendObjectKind() &&
6218             FD->getNonTransparentDeclContext()->isFileContext()) {
6219           DC = FD->getLexicalDeclContext();
6220           continue;
6221         }
6222         // An implicit deduction guide acts as if it's within the class template
6223         // specialization described by its name and first N template params.
6224         auto *Guide = dyn_cast<CXXDeductionGuideDecl>(FD);
6225         if (Guide && Guide->isImplicit()) {
6226           TemplateDecl *TD = Guide->getDeducedTemplate();
6227           // Convert the arguments to an "as-written" list.
6228           TemplateArgumentListInfo Args(Loc, Loc);
6229           for (TemplateArgument Arg : TemplateArgs.getInnermost().take_front(
6230                                         TD->getTemplateParameters()->size())) {
6231             ArrayRef<TemplateArgument> Unpacked(Arg);
6232             if (Arg.getKind() == TemplateArgument::Pack)
6233               Unpacked = Arg.pack_elements();
6234             for (TemplateArgument UnpackedArg : Unpacked)
6235               Args.addArgument(
6236                   getTrivialTemplateArgumentLoc(UnpackedArg, QualType(), Loc));
6237           }
6238           QualType T = CheckTemplateIdType(TemplateName(TD), Loc, Args);
6239           // We may get a non-null type with errors, in which case
6240           // `getAsCXXRecordDecl` will return `nullptr`. For instance, this
6241           // happens when one of the template arguments is an invalid
6242           // expression. We return early to avoid triggering the assertion
6243           // about the `CodeSynthesisContext`.
6244           if (T.isNull() || T->containsErrors())
6245             return nullptr;
6246           CXXRecordDecl *SubstRecord = T->getAsCXXRecordDecl();
6247 
6248           if (!SubstRecord) {
6249             // T can be a dependent TemplateSpecializationType when performing a
6250             // substitution for building a deduction guide.
6251             assert(CodeSynthesisContexts.back().Kind ==
6252                    CodeSynthesisContext::BuildingDeductionGuides);
6253             // Return a nullptr as a sentinel value, we handle it properly in
6254             // the TemplateInstantiator::TransformInjectedClassNameType
6255             // override, which we transform it to a TemplateSpecializationType.
6256             return nullptr;
6257           }
6258           // Check that this template-id names the primary template and not a
6259           // partial or explicit specialization. (In the latter cases, it's
6260           // meaningless to attempt to find an instantiation of D within the
6261           // specialization.)
6262           // FIXME: The standard doesn't say what should happen here.
6263           if (FindingInstantiatedContext &&
6264               usesPartialOrExplicitSpecialization(
6265                   Loc, cast<ClassTemplateSpecializationDecl>(SubstRecord))) {
6266             Diag(Loc, diag::err_specialization_not_primary_template)
6267               << T << (SubstRecord->getTemplateSpecializationKind() ==
6268                            TSK_ExplicitSpecialization);
6269             return nullptr;
6270           }
6271           DC = SubstRecord;
6272           continue;
6273         }
6274       }
6275 
6276       DC = DC->getParent();
6277     }
6278 
6279     // Fall through to deal with other dependent record types (e.g.,
6280     // anonymous unions in class templates).
6281   }
6282 
6283   if (!ParentDependsOnArgs)
6284     return D;
6285 
6286   ParentDC = FindInstantiatedContext(Loc, ParentDC, TemplateArgs);
6287   if (!ParentDC)
6288     return nullptr;
6289 
6290   if (ParentDC != D->getDeclContext()) {
6291     // We performed some kind of instantiation in the parent context,
6292     // so now we need to look into the instantiated parent context to
6293     // find the instantiation of the declaration D.
6294 
6295     // If our context used to be dependent, we may need to instantiate
6296     // it before performing lookup into that context.
6297     bool IsBeingInstantiated = false;
6298     if (CXXRecordDecl *Spec = dyn_cast<CXXRecordDecl>(ParentDC)) {
6299       if (!Spec->isDependentContext()) {
6300         QualType T = Context.getTypeDeclType(Spec);
6301         const RecordType *Tag = T->getAs<RecordType>();
6302         assert(Tag && "type of non-dependent record is not a RecordType");
6303         if (Tag->isBeingDefined())
6304           IsBeingInstantiated = true;
6305         if (!Tag->isBeingDefined() &&
6306             RequireCompleteType(Loc, T, diag::err_incomplete_type))
6307           return nullptr;
6308 
6309         ParentDC = Tag->getDecl();
6310       }
6311     }
6312 
6313     NamedDecl *Result = nullptr;
6314     // FIXME: If the name is a dependent name, this lookup won't necessarily
6315     // find it. Does that ever matter?
6316     if (auto Name = D->getDeclName()) {
6317       DeclarationNameInfo NameInfo(Name, D->getLocation());
6318       DeclarationNameInfo NewNameInfo =
6319           SubstDeclarationNameInfo(NameInfo, TemplateArgs);
6320       Name = NewNameInfo.getName();
6321       if (!Name)
6322         return nullptr;
6323       DeclContext::lookup_result Found = ParentDC->lookup(Name);
6324 
6325       Result = findInstantiationOf(Context, D, Found.begin(), Found.end());
6326     } else {
6327       // Since we don't have a name for the entity we're looking for,
6328       // our only option is to walk through all of the declarations to
6329       // find that name. This will occur in a few cases:
6330       //
6331       //   - anonymous struct/union within a template
6332       //   - unnamed class/struct/union/enum within a template
6333       //
6334       // FIXME: Find a better way to find these instantiations!
6335       Result = findInstantiationOf(Context, D,
6336                                    ParentDC->decls_begin(),
6337                                    ParentDC->decls_end());
6338     }
6339 
6340     if (!Result) {
6341       if (isa<UsingShadowDecl>(D)) {
6342         // UsingShadowDecls can instantiate to nothing because of using hiding.
6343       } else if (hasUncompilableErrorOccurred()) {
6344         // We've already complained about some ill-formed code, so most likely
6345         // this declaration failed to instantiate. There's no point in
6346         // complaining further, since this is normal in invalid code.
6347         // FIXME: Use more fine-grained 'invalid' tracking for this.
6348       } else if (IsBeingInstantiated) {
6349         // The class in which this member exists is currently being
6350         // instantiated, and we haven't gotten around to instantiating this
6351         // member yet. This can happen when the code uses forward declarations
6352         // of member classes, and introduces ordering dependencies via
6353         // template instantiation.
6354         Diag(Loc, diag::err_member_not_yet_instantiated)
6355           << D->getDeclName()
6356           << Context.getTypeDeclType(cast<CXXRecordDecl>(ParentDC));
6357         Diag(D->getLocation(), diag::note_non_instantiated_member_here);
6358       } else if (EnumConstantDecl *ED = dyn_cast<EnumConstantDecl>(D)) {
6359         // This enumeration constant was found when the template was defined,
6360         // but can't be found in the instantiation. This can happen if an
6361         // unscoped enumeration member is explicitly specialized.
6362         EnumDecl *Enum = cast<EnumDecl>(ED->getLexicalDeclContext());
6363         EnumDecl *Spec = cast<EnumDecl>(FindInstantiatedDecl(Loc, Enum,
6364                                                              TemplateArgs));
6365         assert(Spec->getTemplateSpecializationKind() ==
6366                  TSK_ExplicitSpecialization);
6367         Diag(Loc, diag::err_enumerator_does_not_exist)
6368           << D->getDeclName()
6369           << Context.getTypeDeclType(cast<TypeDecl>(Spec->getDeclContext()));
6370         Diag(Spec->getLocation(), diag::note_enum_specialized_here)
6371           << Context.getTypeDeclType(Spec);
6372       } else {
6373         // We should have found something, but didn't.
6374         llvm_unreachable("Unable to find instantiation of declaration!");
6375       }
6376     }
6377 
6378     D = Result;
6379   }
6380 
6381   return D;
6382 }
6383 
PerformPendingInstantiations(bool LocalOnly)6384 void Sema::PerformPendingInstantiations(bool LocalOnly) {
6385   std::deque<PendingImplicitInstantiation> delayedPCHInstantiations;
6386   while (!PendingLocalImplicitInstantiations.empty() ||
6387          (!LocalOnly && !PendingInstantiations.empty())) {
6388     PendingImplicitInstantiation Inst;
6389 
6390     if (PendingLocalImplicitInstantiations.empty()) {
6391       Inst = PendingInstantiations.front();
6392       PendingInstantiations.pop_front();
6393     } else {
6394       Inst = PendingLocalImplicitInstantiations.front();
6395       PendingLocalImplicitInstantiations.pop_front();
6396     }
6397 
6398     // Instantiate function definitions
6399     if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) {
6400       bool DefinitionRequired = Function->getTemplateSpecializationKind() ==
6401                                 TSK_ExplicitInstantiationDefinition;
6402       if (Function->isMultiVersion()) {
6403         getASTContext().forEachMultiversionedFunctionVersion(
6404             Function, [this, Inst, DefinitionRequired](FunctionDecl *CurFD) {
6405               InstantiateFunctionDefinition(/*FIXME:*/ Inst.second, CurFD, true,
6406                                             DefinitionRequired, true);
6407               if (CurFD->isDefined())
6408                 CurFD->setInstantiationIsPending(false);
6409             });
6410       } else {
6411         InstantiateFunctionDefinition(/*FIXME:*/ Inst.second, Function, true,
6412                                       DefinitionRequired, true);
6413         if (Function->isDefined())
6414           Function->setInstantiationIsPending(false);
6415       }
6416       // Definition of a PCH-ed template declaration may be available only in the TU.
6417       if (!LocalOnly && LangOpts.PCHInstantiateTemplates &&
6418           TUKind == TU_Prefix && Function->instantiationIsPending())
6419         delayedPCHInstantiations.push_back(Inst);
6420       continue;
6421     }
6422 
6423     // Instantiate variable definitions
6424     VarDecl *Var = cast<VarDecl>(Inst.first);
6425 
6426     assert((Var->isStaticDataMember() ||
6427             isa<VarTemplateSpecializationDecl>(Var)) &&
6428            "Not a static data member, nor a variable template"
6429            " specialization?");
6430 
6431     // Don't try to instantiate declarations if the most recent redeclaration
6432     // is invalid.
6433     if (Var->getMostRecentDecl()->isInvalidDecl())
6434       continue;
6435 
6436     // Check if the most recent declaration has changed the specialization kind
6437     // and removed the need for implicit instantiation.
6438     switch (Var->getMostRecentDecl()
6439                 ->getTemplateSpecializationKindForInstantiation()) {
6440     case TSK_Undeclared:
6441       llvm_unreachable("Cannot instantitiate an undeclared specialization.");
6442     case TSK_ExplicitInstantiationDeclaration:
6443     case TSK_ExplicitSpecialization:
6444       continue;  // No longer need to instantiate this type.
6445     case TSK_ExplicitInstantiationDefinition:
6446       // We only need an instantiation if the pending instantiation *is* the
6447       // explicit instantiation.
6448       if (Var != Var->getMostRecentDecl())
6449         continue;
6450       break;
6451     case TSK_ImplicitInstantiation:
6452       break;
6453     }
6454 
6455     PrettyDeclStackTraceEntry CrashInfo(Context, Var, SourceLocation(),
6456                                         "instantiating variable definition");
6457     bool DefinitionRequired = Var->getTemplateSpecializationKind() ==
6458                               TSK_ExplicitInstantiationDefinition;
6459 
6460     // Instantiate static data member definitions or variable template
6461     // specializations.
6462     InstantiateVariableDefinition(/*FIXME:*/ Inst.second, Var, true,
6463                                   DefinitionRequired, true);
6464   }
6465 
6466   if (!LocalOnly && LangOpts.PCHInstantiateTemplates)
6467     PendingInstantiations.swap(delayedPCHInstantiations);
6468 }
6469 
PerformDependentDiagnostics(const DeclContext * Pattern,const MultiLevelTemplateArgumentList & TemplateArgs)6470 void Sema::PerformDependentDiagnostics(const DeclContext *Pattern,
6471                        const MultiLevelTemplateArgumentList &TemplateArgs) {
6472   for (auto *DD : Pattern->ddiags()) {
6473     switch (DD->getKind()) {
6474     case DependentDiagnostic::Access:
6475       HandleDependentAccessCheck(*DD, TemplateArgs);
6476       break;
6477     }
6478   }
6479 }
6480