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

source code of clang/lib/Sema/SemaTemplateInstantiateDecl.cpp