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