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