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