clang 19.0.0git
SemaTemplateInstantiateDecl.cpp
Go to the documentation of this file.
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"
19#include "clang/AST/Expr.h"
20#include "clang/AST/ExprCXX.h"
22#include "clang/AST/TypeLoc.h"
27#include "clang/Sema/Lookup.h"
30#include "clang/Sema/SemaCUDA.h"
32#include "clang/Sema/SemaObjC.h"
35#include "clang/Sema/Template.h"
37#include "llvm/Support/TimeProfiler.h"
38#include <optional>
39
40using namespace clang;
41
42static bool isDeclWithinFunction(const Decl *D) {
43 const DeclContext *DC = D->getDeclContext();
44 if (DC->isFunctionOrMethod())
45 return true;
46
47 if (DC->isRecord())
48 return cast<CXXRecordDecl>(DC)->isLocalClass();
49
50 return false;
51}
52
53template<typename DeclT>
54static bool SubstQualifier(Sema &SemaRef, const DeclT *OldDecl, DeclT *NewDecl,
55 const MultiLevelTemplateArgumentList &TemplateArgs) {
56 if (!OldDecl->getQualifierLoc())
57 return false;
58
59 assert((NewDecl->getFriendObjectKind() ||
60 !OldDecl->getLexicalDeclContext()->isDependentContext()) &&
61 "non-friend with qualified name defined in dependent context");
62 Sema::ContextRAII SavedContext(
63 SemaRef,
64 const_cast<DeclContext *>(NewDecl->getFriendObjectKind()
65 ? NewDecl->getLexicalDeclContext()
66 : OldDecl->getLexicalDeclContext()));
67
68 NestedNameSpecifierLoc NewQualifierLoc
69 = SemaRef.SubstNestedNameSpecifierLoc(OldDecl->getQualifierLoc(),
70 TemplateArgs);
71
72 if (!NewQualifierLoc)
73 return true;
74
75 NewDecl->setQualifierInfo(NewQualifierLoc);
76 return false;
77}
78
80 DeclaratorDecl *NewDecl) {
81 return ::SubstQualifier(SemaRef, OldDecl, NewDecl, TemplateArgs);
82}
83
85 TagDecl *NewDecl) {
86 return ::SubstQualifier(SemaRef, OldDecl, NewDecl, TemplateArgs);
87}
88
89// Include attribute instantiation code.
90#include "clang/Sema/AttrTemplateInstantiate.inc"
91
93 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
94 const AlignedAttr *Aligned, Decl *New, bool IsPackExpansion) {
95 if (Aligned->isAlignmentExpr()) {
96 // The alignment expression is a constant expression.
99 ExprResult Result = S.SubstExpr(Aligned->getAlignmentExpr(), TemplateArgs);
100 if (!Result.isInvalid())
101 S.AddAlignedAttr(New, *Aligned, Result.getAs<Expr>(), IsPackExpansion);
102 } else {
104 S.SubstType(Aligned->getAlignmentType(), TemplateArgs,
105 Aligned->getLocation(), DeclarationName())) {
106 if (!S.CheckAlignasTypeArgument(Aligned->getSpelling(), Result,
107 Aligned->getLocation(),
108 Result->getTypeLoc().getSourceRange()))
109 S.AddAlignedAttr(New, *Aligned, Result, IsPackExpansion);
110 }
111 }
112}
113
115 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
116 const AlignedAttr *Aligned, Decl *New) {
117 if (!Aligned->isPackExpansion()) {
118 instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, false);
119 return;
120 }
121
123 if (Aligned->isAlignmentExpr())
124 S.collectUnexpandedParameterPacks(Aligned->getAlignmentExpr(),
125 Unexpanded);
126 else
127 S.collectUnexpandedParameterPacks(Aligned->getAlignmentType()->getTypeLoc(),
128 Unexpanded);
129 assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
130
131 // Determine whether we can expand this attribute pack yet.
132 bool Expand = true, RetainExpansion = false;
133 std::optional<unsigned> NumExpansions;
134 // FIXME: Use the actual location of the ellipsis.
135 SourceLocation EllipsisLoc = Aligned->getLocation();
136 if (S.CheckParameterPacksForExpansion(EllipsisLoc, Aligned->getRange(),
137 Unexpanded, TemplateArgs, Expand,
138 RetainExpansion, NumExpansions))
139 return;
140
141 if (!Expand) {
143 instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, true);
144 } else {
145 for (unsigned I = 0; I != *NumExpansions; ++I) {
147 instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, false);
148 }
149 }
150}
151
153 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
154 const AssumeAlignedAttr *Aligned, Decl *New) {
155 // The alignment expression is a constant expression.
158
159 Expr *E, *OE = nullptr;
160 ExprResult Result = S.SubstExpr(Aligned->getAlignment(), TemplateArgs);
161 if (Result.isInvalid())
162 return;
163 E = Result.getAs<Expr>();
164
165 if (Aligned->getOffset()) {
166 Result = S.SubstExpr(Aligned->getOffset(), TemplateArgs);
167 if (Result.isInvalid())
168 return;
169 OE = Result.getAs<Expr>();
170 }
171
172 S.AddAssumeAlignedAttr(New, *Aligned, E, OE);
173}
174
176 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
177 const AlignValueAttr *Aligned, Decl *New) {
178 // The alignment expression is a constant expression.
181 ExprResult Result = S.SubstExpr(Aligned->getAlignment(), TemplateArgs);
182 if (!Result.isInvalid())
183 S.AddAlignValueAttr(New, *Aligned, Result.getAs<Expr>());
184}
185
187 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
188 const AllocAlignAttr *Align, Decl *New) {
190 S.getASTContext(),
191 llvm::APInt(64, Align->getParamIndex().getSourceIndex()),
192 S.getASTContext().UnsignedLongLongTy, Align->getLocation());
193 S.AddAllocAlignAttr(New, *Align, Param);
194}
195
197 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
198 const AnnotateAttr *Attr, Decl *New) {
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
212 if (S.SubstExprs(ArgsToInstantiate,
213 /*IsCall=*/false, TemplateArgs, Args))
214 return;
215
216 StringRef Str = Attr->getAnnotation();
217 if (HasDelayedArgs) {
218 if (Args.size() < 1) {
219 S.Diag(Attr->getLoc(), diag::err_attribute_too_few_arguments)
220 << Attr << 1;
221 return;
222 }
223
224 if (!S.checkStringLiteralArgumentAttr(*Attr, Args[0], Str))
225 return;
226
228 ActualArgs.insert(ActualArgs.begin(), Args.begin() + 1, Args.end());
229 std::swap(Args, ActualArgs);
230 }
231 S.AddAnnotationAttr(New, *Attr, Str, Args);
232}
233
235 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
236 const Attr *A, Expr *OldCond, const Decl *Tmpl, FunctionDecl *New) {
237 Expr *Cond = nullptr;
238 {
239 Sema::ContextRAII SwitchContext(S, New);
242 ExprResult Result = S.SubstExpr(OldCond, TemplateArgs);
243 if (Result.isInvalid())
244 return nullptr;
245 Cond = Result.getAs<Expr>();
246 }
247 if (!Cond->isTypeDependent()) {
249 if (Converted.isInvalid())
250 return nullptr;
251 Cond = Converted.get();
252 }
253
255 if (OldCond->isValueDependent() && !Cond->isValueDependent() &&
256 !Expr::isPotentialConstantExprUnevaluated(Cond, New, Diags)) {
257 S.Diag(A->getLocation(), diag::err_attr_cond_never_constant_expr) << A;
258 for (const auto &P : Diags)
259 S.Diag(P.first, P.second);
260 return nullptr;
261 }
262 return Cond;
263}
264
266 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
267 const EnableIfAttr *EIA, const Decl *Tmpl, FunctionDecl *New) {
269 S, TemplateArgs, EIA, EIA->getCond(), Tmpl, New);
270
271 if (Cond)
272 New->addAttr(new (S.getASTContext()) EnableIfAttr(S.getASTContext(), *EIA,
273 Cond, EIA->getMessage()));
274}
275
277 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
278 const DiagnoseIfAttr *DIA, const Decl *Tmpl, FunctionDecl *New) {
280 S, TemplateArgs, DIA, DIA->getCond(), Tmpl, New);
281
282 if (Cond)
283 New->addAttr(new (S.getASTContext()) DiagnoseIfAttr(
284 S.getASTContext(), *DIA, Cond, DIA->getMessage(),
285 DIA->getDiagnosticType(), DIA->getArgDependent(), New));
286}
287
288// Constructs and adds to New a new instance of CUDALaunchBoundsAttr using
289// template A as the base and arguments from TemplateArgs.
291 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
292 const CUDALaunchBoundsAttr &Attr, Decl *New) {
293 // The alignment expression is a constant expression.
296
297 ExprResult Result = S.SubstExpr(Attr.getMaxThreads(), TemplateArgs);
298 if (Result.isInvalid())
299 return;
300 Expr *MaxThreads = Result.getAs<Expr>();
301
302 Expr *MinBlocks = nullptr;
303 if (Attr.getMinBlocks()) {
304 Result = S.SubstExpr(Attr.getMinBlocks(), TemplateArgs);
305 if (Result.isInvalid())
306 return;
307 MinBlocks = Result.getAs<Expr>();
308 }
309
310 Expr *MaxBlocks = nullptr;
311 if (Attr.getMaxBlocks()) {
312 Result = S.SubstExpr(Attr.getMaxBlocks(), TemplateArgs);
313 if (Result.isInvalid())
314 return;
315 MaxBlocks = Result.getAs<Expr>();
316 }
317
318 S.AddLaunchBoundsAttr(New, Attr, MaxThreads, MinBlocks, MaxBlocks);
319}
320
321static void
323 const MultiLevelTemplateArgumentList &TemplateArgs,
324 const ModeAttr &Attr, Decl *New) {
325 S.AddModeAttr(New, Attr, Attr.getMode(),
326 /*InInstantiation=*/true);
327}
328
329/// Instantiation of 'declare simd' attribute and its arguments.
331 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
332 const OMPDeclareSimdDeclAttr &Attr, Decl *New) {
333 // Allow 'this' in clauses with varlists.
334 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(New))
335 New = FTD->getTemplatedDecl();
336 auto *FD = cast<FunctionDecl>(New);
337 auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(FD->getDeclContext());
338 SmallVector<Expr *, 4> Uniforms, Aligneds, Alignments, Linears, Steps;
339 SmallVector<unsigned, 4> LinModifiers;
340
341 auto SubstExpr = [&](Expr *E) -> ExprResult {
342 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
343 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
344 Sema::ContextRAII SavedContext(S, FD);
346 if (FD->getNumParams() > PVD->getFunctionScopeIndex())
347 Local.InstantiatedLocal(
348 PVD, FD->getParamDecl(PVD->getFunctionScopeIndex()));
349 return S.SubstExpr(E, TemplateArgs);
350 }
351 Sema::CXXThisScopeRAII ThisScope(S, ThisContext, Qualifiers(),
352 FD->isCXXInstanceMember());
353 return S.SubstExpr(E, TemplateArgs);
354 };
355
356 // Substitute a single OpenMP clause, which is a potentially-evaluated
357 // full-expression.
358 auto Subst = [&](Expr *E) -> ExprResult {
361 ExprResult Res = SubstExpr(E);
362 if (Res.isInvalid())
363 return Res;
364 return S.ActOnFinishFullExpr(Res.get(), false);
365 };
366
367 ExprResult Simdlen;
368 if (auto *E = Attr.getSimdlen())
369 Simdlen = Subst(E);
370
371 if (Attr.uniforms_size() > 0) {
372 for(auto *E : Attr.uniforms()) {
373 ExprResult Inst = Subst(E);
374 if (Inst.isInvalid())
375 continue;
376 Uniforms.push_back(Inst.get());
377 }
378 }
379
380 auto AI = Attr.alignments_begin();
381 for (auto *E : Attr.aligneds()) {
382 ExprResult Inst = Subst(E);
383 if (Inst.isInvalid())
384 continue;
385 Aligneds.push_back(Inst.get());
386 Inst = ExprEmpty();
387 if (*AI)
388 Inst = S.SubstExpr(*AI, TemplateArgs);
389 Alignments.push_back(Inst.get());
390 ++AI;
391 }
392
393 auto SI = Attr.steps_begin();
394 for (auto *E : Attr.linears()) {
395 ExprResult Inst = Subst(E);
396 if (Inst.isInvalid())
397 continue;
398 Linears.push_back(Inst.get());
399 Inst = ExprEmpty();
400 if (*SI)
401 Inst = S.SubstExpr(*SI, TemplateArgs);
402 Steps.push_back(Inst.get());
403 ++SI;
404 }
405 LinModifiers.append(Attr.modifiers_begin(), Attr.modifiers_end());
407 S.ConvertDeclToDeclGroup(New), Attr.getBranchState(), Simdlen.get(),
408 Uniforms, Aligneds, Alignments, Linears, LinModifiers, Steps,
409 Attr.getRange());
410}
411
412/// Instantiation of 'declare variant' attribute and its arguments.
414 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
415 const OMPDeclareVariantAttr &Attr, Decl *New) {
416 // Allow 'this' in clauses with varlists.
417 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(New))
418 New = FTD->getTemplatedDecl();
419 auto *FD = cast<FunctionDecl>(New);
420 auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(FD->getDeclContext());
421
422 auto &&SubstExpr = [FD, ThisContext, &S, &TemplateArgs](Expr *E) {
423 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
424 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
425 Sema::ContextRAII SavedContext(S, FD);
427 if (FD->getNumParams() > PVD->getFunctionScopeIndex())
428 Local.InstantiatedLocal(
429 PVD, FD->getParamDecl(PVD->getFunctionScopeIndex()));
430 return S.SubstExpr(E, TemplateArgs);
431 }
432 Sema::CXXThisScopeRAII ThisScope(S, ThisContext, Qualifiers(),
433 FD->isCXXInstanceMember());
434 return S.SubstExpr(E, TemplateArgs);
435 };
436
437 // Substitute a single OpenMP clause, which is a potentially-evaluated
438 // full-expression.
439 auto &&Subst = [&SubstExpr, &S](Expr *E) {
442 ExprResult Res = SubstExpr(E);
443 if (Res.isInvalid())
444 return Res;
445 return S.ActOnFinishFullExpr(Res.get(), false);
446 };
447
448 ExprResult VariantFuncRef;
449 if (Expr *E = Attr.getVariantFuncRef()) {
450 // Do not mark function as is used to prevent its emission if this is the
451 // only place where it is used.
454 VariantFuncRef = Subst(E);
455 }
456
457 // Copy the template version of the OMPTraitInfo and run substitute on all
458 // score and condition expressiosn.
460 TI = *Attr.getTraitInfos();
461
462 // Try to substitute template parameters in score and condition expressions.
463 auto SubstScoreOrConditionExpr = [&S, Subst](Expr *&E, bool) {
464 if (E) {
467 ExprResult ER = Subst(E);
468 if (ER.isUsable())
469 E = ER.get();
470 else
471 return true;
472 }
473 return false;
474 };
475 if (TI.anyScoreOrCondition(SubstScoreOrConditionExpr))
476 return;
477
478 Expr *E = VariantFuncRef.get();
479
480 // Check function/variant ref for `omp declare variant` but not for `omp
481 // begin declare variant` (which use implicit attributes).
482 std::optional<std::pair<FunctionDecl *, Expr *>> DeclVarData =
484 S.ConvertDeclToDeclGroup(New), E, TI, Attr.appendArgs_size(),
485 Attr.getRange());
486
487 if (!DeclVarData)
488 return;
489
490 E = DeclVarData->second;
491 FD = DeclVarData->first;
492
493 if (auto *VariantDRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts())) {
494 if (auto *VariantFD = dyn_cast<FunctionDecl>(VariantDRE->getDecl())) {
495 if (auto *VariantFTD = VariantFD->getDescribedFunctionTemplate()) {
496 if (!VariantFTD->isThisDeclarationADefinition())
497 return;
500 S.Context, TemplateArgs.getInnermost());
501
502 auto *SubstFD = S.InstantiateFunctionDeclaration(VariantFTD, TAL,
503 New->getLocation());
504 if (!SubstFD)
505 return;
507 SubstFD->getType(), FD->getType(),
508 /* OfBlockPointer */ false,
509 /* Unqualified */ false, /* AllowCXX */ true);
510 if (NewType.isNull())
511 return;
513 New->getLocation(), SubstFD, /* Recursive */ true,
514 /* DefinitionRequired */ false, /* AtEndOfTU */ false);
515 SubstFD->setInstantiationIsPending(!SubstFD->isDefined());
517 SourceLocation(), SubstFD,
518 /* RefersToEnclosingVariableOrCapture */ false,
519 /* NameLoc */ SubstFD->getLocation(),
520 SubstFD->getType(), ExprValueKind::VK_PRValue);
521 }
522 }
523 }
524
525 SmallVector<Expr *, 8> NothingExprs;
526 SmallVector<Expr *, 8> NeedDevicePtrExprs;
528
529 for (Expr *E : Attr.adjustArgsNothing()) {
530 ExprResult ER = Subst(E);
531 if (ER.isInvalid())
532 continue;
533 NothingExprs.push_back(ER.get());
534 }
535 for (Expr *E : Attr.adjustArgsNeedDevicePtr()) {
536 ExprResult ER = Subst(E);
537 if (ER.isInvalid())
538 continue;
539 NeedDevicePtrExprs.push_back(ER.get());
540 }
541 for (OMPInteropInfo &II : Attr.appendArgs()) {
542 // When prefer_type is implemented for append_args handle them here too.
543 AppendArgs.emplace_back(II.IsTarget, II.IsTargetSync);
544 }
545
547 FD, E, TI, NothingExprs, NeedDevicePtrExprs, AppendArgs, SourceLocation(),
549}
550
552 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
553 const AMDGPUFlatWorkGroupSizeAttr &Attr, Decl *New) {
554 // Both min and max expression are constant expressions.
557
558 ExprResult Result = S.SubstExpr(Attr.getMin(), TemplateArgs);
559 if (Result.isInvalid())
560 return;
561 Expr *MinExpr = Result.getAs<Expr>();
562
563 Result = S.SubstExpr(Attr.getMax(), TemplateArgs);
564 if (Result.isInvalid())
565 return;
566 Expr *MaxExpr = Result.getAs<Expr>();
567
568 S.AMDGPU().addAMDGPUFlatWorkGroupSizeAttr(New, Attr, MinExpr, MaxExpr);
569}
570
572 const MultiLevelTemplateArgumentList &TemplateArgs, ExplicitSpecifier ES) {
573 if (!ES.getExpr())
574 return ES;
575 Expr *OldCond = ES.getExpr();
576 Expr *Cond = nullptr;
577 {
580 ExprResult SubstResult = SubstExpr(OldCond, TemplateArgs);
581 if (SubstResult.isInvalid()) {
583 }
584 Cond = SubstResult.get();
585 }
586 ExplicitSpecifier Result(Cond, ES.getKind());
587 if (!Cond->isTypeDependent())
589 return Result;
590}
591
593 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
594 const AMDGPUWavesPerEUAttr &Attr, Decl *New) {
595 // Both min and max expression are constant expressions.
598
599 ExprResult Result = S.SubstExpr(Attr.getMin(), TemplateArgs);
600 if (Result.isInvalid())
601 return;
602 Expr *MinExpr = Result.getAs<Expr>();
603
604 Expr *MaxExpr = nullptr;
605 if (auto Max = Attr.getMax()) {
606 Result = S.SubstExpr(Max, TemplateArgs);
607 if (Result.isInvalid())
608 return;
609 MaxExpr = Result.getAs<Expr>();
610 }
611
612 S.AMDGPU().addAMDGPUWavesPerEUAttr(New, Attr, MinExpr, MaxExpr);
613}
614
616 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
617 const AMDGPUMaxNumWorkGroupsAttr &Attr, Decl *New) {
620
621 ExprResult ResultX = S.SubstExpr(Attr.getMaxNumWorkGroupsX(), TemplateArgs);
622 if (!ResultX.isUsable())
623 return;
624 ExprResult ResultY = S.SubstExpr(Attr.getMaxNumWorkGroupsY(), TemplateArgs);
625 if (!ResultY.isUsable())
626 return;
627 ExprResult ResultZ = S.SubstExpr(Attr.getMaxNumWorkGroupsZ(), TemplateArgs);
628 if (!ResultZ.isUsable())
629 return;
630
631 Expr *XExpr = ResultX.getAs<Expr>();
632 Expr *YExpr = ResultY.getAs<Expr>();
633 Expr *ZExpr = ResultZ.getAs<Expr>();
634
635 S.AMDGPU().addAMDGPUMaxNumWorkGroupsAttr(New, Attr, XExpr, YExpr, ZExpr);
636}
637
638// This doesn't take any template parameters, but we have a custom action that
639// needs to happen when the kernel itself is instantiated. We need to run the
640// ItaniumMangler to mark the names required to name this kernel.
642 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
643 const SYCLKernelAttr &Attr, Decl *New) {
644 New->addAttr(Attr.clone(S.getASTContext()));
645}
646
647/// Determine whether the attribute A might be relevant to the declaration D.
648/// If not, we can skip instantiating it. The attribute may or may not have
649/// been instantiated yet.
650static bool isRelevantAttr(Sema &S, const Decl *D, const Attr *A) {
651 // 'preferred_name' is only relevant to the matching specialization of the
652 // template.
653 if (const auto *PNA = dyn_cast<PreferredNameAttr>(A)) {
654 QualType T = PNA->getTypedefType();
655 const auto *RD = cast<CXXRecordDecl>(D);
656 if (!T->isDependentType() && !RD->isDependentContext() &&
658 return false;
659 for (const auto *ExistingPNA : D->specific_attrs<PreferredNameAttr>())
660 if (S.Context.hasSameType(ExistingPNA->getTypedefType(),
661 PNA->getTypedefType()))
662 return false;
663 return true;
664 }
665
666 if (const auto *BA = dyn_cast<BuiltinAttr>(A)) {
667 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
668 switch (BA->getID()) {
669 case Builtin::BIforward:
670 // Do not treat 'std::forward' as a builtin if it takes an rvalue reference
671 // type and returns an lvalue reference type. The library implementation
672 // will produce an error in this case; don't get in its way.
673 if (FD && FD->getNumParams() >= 1 &&
676 return false;
677 }
678 [[fallthrough]];
679 case Builtin::BImove:
680 case Builtin::BImove_if_noexcept:
681 // HACK: Super-old versions of libc++ (3.1 and earlier) provide
682 // std::forward and std::move overloads that sometimes return by value
683 // instead of by reference when building in C++98 mode. Don't treat such
684 // cases as builtins.
685 if (FD && !FD->getReturnType()->isReferenceType())
686 return false;
687 break;
688 }
689 }
690
691 return true;
692}
693
695 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
696 const HLSLParamModifierAttr *Attr, Decl *New) {
697 ParmVarDecl *P = cast<ParmVarDecl>(New);
698 P->addAttr(Attr->clone(S.getASTContext()));
699 P->setType(S.getASTContext().getLValueReferenceType(P->getType()));
700}
701
703 const MultiLevelTemplateArgumentList &TemplateArgs, const Decl *Tmpl,
704 Decl *New, LateInstantiatedAttrVec *LateAttrs,
705 LocalInstantiationScope *OuterMostScope) {
706 if (NamedDecl *ND = dyn_cast<NamedDecl>(New)) {
707 // FIXME: This function is called multiple times for the same template
708 // specialization. We should only instantiate attributes that were added
709 // since the previous instantiation.
710 for (const auto *TmplAttr : Tmpl->attrs()) {
711 if (!isRelevantAttr(*this, New, TmplAttr))
712 continue;
713
714 // FIXME: If any of the special case versions from InstantiateAttrs become
715 // applicable to template declaration, we'll need to add them here.
716 CXXThisScopeRAII ThisScope(
717 *this, dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext()),
718 Qualifiers(), ND->isCXXInstanceMember());
719
721 TmplAttr, Context, *this, TemplateArgs);
722 if (NewAttr && isRelevantAttr(*this, New, NewAttr))
723 New->addAttr(NewAttr);
724 }
725 }
726}
727
730 switch (A->getKind()) {
731 case clang::attr::CFConsumed:
733 case clang::attr::OSConsumed:
735 case clang::attr::NSConsumed:
737 default:
738 llvm_unreachable("Wrong argument supplied");
739 }
740}
741
743 const Decl *Tmpl, Decl *New,
744 LateInstantiatedAttrVec *LateAttrs,
745 LocalInstantiationScope *OuterMostScope) {
746 for (const auto *TmplAttr : Tmpl->attrs()) {
747 if (!isRelevantAttr(*this, New, TmplAttr))
748 continue;
749
750 // FIXME: This should be generalized to more than just the AlignedAttr.
751 const AlignedAttr *Aligned = dyn_cast<AlignedAttr>(TmplAttr);
752 if (Aligned && Aligned->isAlignmentDependent()) {
753 instantiateDependentAlignedAttr(*this, TemplateArgs, Aligned, New);
754 continue;
755 }
756
757 if (const auto *AssumeAligned = dyn_cast<AssumeAlignedAttr>(TmplAttr)) {
758 instantiateDependentAssumeAlignedAttr(*this, TemplateArgs, AssumeAligned, New);
759 continue;
760 }
761
762 if (const auto *AlignValue = dyn_cast<AlignValueAttr>(TmplAttr)) {
763 instantiateDependentAlignValueAttr(*this, TemplateArgs, AlignValue, New);
764 continue;
765 }
766
767 if (const auto *AllocAlign = dyn_cast<AllocAlignAttr>(TmplAttr)) {
768 instantiateDependentAllocAlignAttr(*this, TemplateArgs, AllocAlign, New);
769 continue;
770 }
771
772 if (const auto *Annotate = dyn_cast<AnnotateAttr>(TmplAttr)) {
773 instantiateDependentAnnotationAttr(*this, TemplateArgs, Annotate, New);
774 continue;
775 }
776
777 if (const auto *EnableIf = dyn_cast<EnableIfAttr>(TmplAttr)) {
778 instantiateDependentEnableIfAttr(*this, TemplateArgs, EnableIf, Tmpl,
779 cast<FunctionDecl>(New));
780 continue;
781 }
782
783 if (const auto *DiagnoseIf = dyn_cast<DiagnoseIfAttr>(TmplAttr)) {
784 instantiateDependentDiagnoseIfAttr(*this, TemplateArgs, DiagnoseIf, Tmpl,
785 cast<FunctionDecl>(New));
786 continue;
787 }
788
789 if (const auto *CUDALaunchBounds =
790 dyn_cast<CUDALaunchBoundsAttr>(TmplAttr)) {
792 *CUDALaunchBounds, New);
793 continue;
794 }
795
796 if (const auto *Mode = dyn_cast<ModeAttr>(TmplAttr)) {
797 instantiateDependentModeAttr(*this, TemplateArgs, *Mode, New);
798 continue;
799 }
800
801 if (const auto *OMPAttr = dyn_cast<OMPDeclareSimdDeclAttr>(TmplAttr)) {
802 instantiateOMPDeclareSimdDeclAttr(*this, TemplateArgs, *OMPAttr, New);
803 continue;
804 }
805
806 if (const auto *OMPAttr = dyn_cast<OMPDeclareVariantAttr>(TmplAttr)) {
807 instantiateOMPDeclareVariantAttr(*this, TemplateArgs, *OMPAttr, New);
808 continue;
809 }
810
811 if (const auto *AMDGPUFlatWorkGroupSize =
812 dyn_cast<AMDGPUFlatWorkGroupSizeAttr>(TmplAttr)) {
814 *this, TemplateArgs, *AMDGPUFlatWorkGroupSize, New);
815 }
816
817 if (const auto *AMDGPUFlatWorkGroupSize =
818 dyn_cast<AMDGPUWavesPerEUAttr>(TmplAttr)) {
820 *AMDGPUFlatWorkGroupSize, New);
821 }
822
823 if (const auto *AMDGPUMaxNumWorkGroups =
824 dyn_cast<AMDGPUMaxNumWorkGroupsAttr>(TmplAttr)) {
826 *this, TemplateArgs, *AMDGPUMaxNumWorkGroups, New);
827 }
828
829 if (const auto *ParamAttr = dyn_cast<HLSLParamModifierAttr>(TmplAttr)) {
830 instantiateDependentHLSLParamModifierAttr(*this, TemplateArgs, ParamAttr,
831 New);
832 continue;
833 }
834
835 // Existing DLL attribute on the instantiation takes precedence.
836 if (TmplAttr->getKind() == attr::DLLExport ||
837 TmplAttr->getKind() == attr::DLLImport) {
838 if (New->hasAttr<DLLExportAttr>() || New->hasAttr<DLLImportAttr>()) {
839 continue;
840 }
841 }
842
843 if (const auto *ABIAttr = dyn_cast<ParameterABIAttr>(TmplAttr)) {
844 Swift().AddParameterABIAttr(New, *ABIAttr, ABIAttr->getABI());
845 continue;
846 }
847
848 if (isa<NSConsumedAttr>(TmplAttr) || isa<OSConsumedAttr>(TmplAttr) ||
849 isa<CFConsumedAttr>(TmplAttr)) {
850 ObjC().AddXConsumedAttr(New, *TmplAttr,
852 /*template instantiation=*/true);
853 continue;
854 }
855
856 if (auto *A = dyn_cast<PointerAttr>(TmplAttr)) {
857 if (!New->hasAttr<PointerAttr>())
858 New->addAttr(A->clone(Context));
859 continue;
860 }
861
862 if (auto *A = dyn_cast<OwnerAttr>(TmplAttr)) {
863 if (!New->hasAttr<OwnerAttr>())
864 New->addAttr(A->clone(Context));
865 continue;
866 }
867
868 if (auto *A = dyn_cast<SYCLKernelAttr>(TmplAttr)) {
869 instantiateDependentSYCLKernelAttr(*this, TemplateArgs, *A, New);
870 continue;
871 }
872
873 assert(!TmplAttr->isPackExpansion());
874 if (TmplAttr->isLateParsed() && LateAttrs) {
875 // Late parsed attributes must be instantiated and attached after the
876 // enclosing class has been instantiated. See Sema::InstantiateClass.
877 LocalInstantiationScope *Saved = nullptr;
879 Saved = CurrentInstantiationScope->cloneScopes(OuterMostScope);
880 LateAttrs->push_back(LateInstantiatedAttribute(TmplAttr, Saved, New));
881 } else {
882 // Allow 'this' within late-parsed attributes.
883 auto *ND = cast<NamedDecl>(New);
884 auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext());
885 CXXThisScopeRAII ThisScope(*this, ThisContext, Qualifiers(),
886 ND->isCXXInstanceMember());
887
889 *this, TemplateArgs);
890 if (NewAttr && isRelevantAttr(*this, New, TmplAttr))
891 New->addAttr(NewAttr);
892 }
893 }
894}
895
896/// Update instantiation attributes after template was late parsed.
897///
898/// Some attributes are evaluated based on the body of template. If it is
899/// late parsed, such attributes cannot be evaluated when declaration is
900/// instantiated. This function is used to update instantiation attributes when
901/// template definition is ready.
903 for (const auto *Attr : Pattern->attrs()) {
904 if (auto *A = dyn_cast<StrictFPAttr>(Attr)) {
905 if (!Inst->hasAttr<StrictFPAttr>())
906 Inst->addAttr(A->clone(getASTContext()));
907 continue;
908 }
909 }
910}
911
912/// In the MS ABI, we need to instantiate default arguments of dllexported
913/// default constructors along with the constructor definition. This allows IR
914/// gen to emit a constructor closure which calls the default constructor with
915/// its default arguments.
918 Ctor->isDefaultConstructor());
919 unsigned NumParams = Ctor->getNumParams();
920 if (NumParams == 0)
921 return;
922 DLLExportAttr *Attr = Ctor->getAttr<DLLExportAttr>();
923 if (!Attr)
924 return;
925 for (unsigned I = 0; I != NumParams; ++I) {
927 Ctor->getParamDecl(I));
929 }
930}
931
932/// Get the previous declaration of a declaration for the purposes of template
933/// instantiation. If this finds a previous declaration, then the previous
934/// declaration of the instantiation of D should be an instantiation of the
935/// result of this function.
936template<typename DeclT>
937static DeclT *getPreviousDeclForInstantiation(DeclT *D) {
938 DeclT *Result = D->getPreviousDecl();
939
940 // If the declaration is within a class, and the previous declaration was
941 // merged from a different definition of that class, then we don't have a
942 // previous declaration for the purpose of template instantiation.
943 if (Result && isa<CXXRecordDecl>(D->getDeclContext()) &&
944 D->getLexicalDeclContext() != Result->getLexicalDeclContext())
945 return nullptr;
946
947 return Result;
948}
949
950Decl *
951TemplateDeclInstantiator::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
952 llvm_unreachable("Translation units cannot be instantiated");
953}
954
955Decl *TemplateDeclInstantiator::VisitHLSLBufferDecl(HLSLBufferDecl *Decl) {
956 llvm_unreachable("HLSL buffer declarations cannot be instantiated");
957}
958
959Decl *
960TemplateDeclInstantiator::VisitPragmaCommentDecl(PragmaCommentDecl *D) {
961 llvm_unreachable("pragma comment cannot be instantiated");
962}
963
964Decl *TemplateDeclInstantiator::VisitPragmaDetectMismatchDecl(
966 llvm_unreachable("pragma comment cannot be instantiated");
967}
968
969Decl *
970TemplateDeclInstantiator::VisitExternCContextDecl(ExternCContextDecl *D) {
971 llvm_unreachable("extern \"C\" context cannot be instantiated");
972}
973
974Decl *TemplateDeclInstantiator::VisitMSGuidDecl(MSGuidDecl *D) {
975 llvm_unreachable("GUID declaration cannot be instantiated");
976}
977
978Decl *TemplateDeclInstantiator::VisitUnnamedGlobalConstantDecl(
980 llvm_unreachable("UnnamedGlobalConstantDecl cannot be instantiated");
981}
982
983Decl *TemplateDeclInstantiator::VisitTemplateParamObjectDecl(
985 llvm_unreachable("template parameter objects cannot be instantiated");
986}
987
988Decl *
989TemplateDeclInstantiator::VisitLabelDecl(LabelDecl *D) {
990 LabelDecl *Inst = LabelDecl::Create(SemaRef.Context, Owner, D->getLocation(),
991 D->getIdentifier());
992 Owner->addDecl(Inst);
993 return Inst;
994}
995
996Decl *
997TemplateDeclInstantiator::VisitNamespaceDecl(NamespaceDecl *D) {
998 llvm_unreachable("Namespaces cannot be instantiated");
999}
1000
1001Decl *
1002TemplateDeclInstantiator::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
1003 NamespaceAliasDecl *Inst
1004 = NamespaceAliasDecl::Create(SemaRef.Context, Owner,
1005 D->getNamespaceLoc(),
1006 D->getAliasLoc(),
1007 D->getIdentifier(),
1008 D->getQualifierLoc(),
1009 D->getTargetNameLoc(),
1010 D->getNamespace());
1011 Owner->addDecl(Inst);
1012 return Inst;
1013}
1014
1016 bool IsTypeAlias) {
1017 bool Invalid = false;
1021 DI = SemaRef.SubstType(DI, TemplateArgs,
1022 D->getLocation(), D->getDeclName());
1023 if (!DI) {
1024 Invalid = true;
1025 DI = SemaRef.Context.getTrivialTypeSourceInfo(SemaRef.Context.IntTy);
1026 }
1027 } else {
1029 }
1030
1031 // HACK: 2012-10-23 g++ has a bug where it gets the value kind of ?: wrong.
1032 // libstdc++ relies upon this bug in its implementation of common_type. If we
1033 // happen to be processing that implementation, fake up the g++ ?:
1034 // semantics. See LWG issue 2141 for more information on the bug. The bugs
1035 // are fixed in g++ and libstdc++ 4.9.0 (2014-04-22).
1036 const DecltypeType *DT = DI->getType()->getAs<DecltypeType>();
1037 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D->getDeclContext());
1038 if (DT && RD && isa<ConditionalOperator>(DT->getUnderlyingExpr()) &&
1039 DT->isReferenceType() &&
1040 RD->getEnclosingNamespaceContext() == SemaRef.getStdNamespace() &&
1041 RD->getIdentifier() && RD->getIdentifier()->isStr("common_type") &&
1042 D->getIdentifier() && D->getIdentifier()->isStr("type") &&
1044 // Fold it to the (non-reference) type which g++ would have produced.
1045 DI = SemaRef.Context.getTrivialTypeSourceInfo(
1047
1048 // Create the new typedef
1049 TypedefNameDecl *Typedef;
1050 if (IsTypeAlias)
1051 Typedef = TypeAliasDecl::Create(SemaRef.Context, Owner, D->getBeginLoc(),
1052 D->getLocation(), D->getIdentifier(), DI);
1053 else
1054 Typedef = TypedefDecl::Create(SemaRef.Context, Owner, D->getBeginLoc(),
1055 D->getLocation(), D->getIdentifier(), DI);
1056 if (Invalid)
1057 Typedef->setInvalidDecl();
1058
1059 // If the old typedef was the name for linkage purposes of an anonymous
1060 // tag decl, re-establish that relationship for the new typedef.
1061 if (const TagType *oldTagType = D->getUnderlyingType()->getAs<TagType>()) {
1062 TagDecl *oldTag = oldTagType->getDecl();
1063 if (oldTag->getTypedefNameForAnonDecl() == D && !Invalid) {
1064 TagDecl *newTag = DI->getType()->castAs<TagType>()->getDecl();
1065 assert(!newTag->hasNameForLinkage());
1066 newTag->setTypedefNameForAnonDecl(Typedef);
1067 }
1068 }
1069
1071 NamedDecl *InstPrev = SemaRef.FindInstantiatedDecl(D->getLocation(), Prev,
1072 TemplateArgs);
1073 if (!InstPrev)
1074 return nullptr;
1075
1076 TypedefNameDecl *InstPrevTypedef = cast<TypedefNameDecl>(InstPrev);
1077
1078 // If the typedef types are not identical, reject them.
1079 SemaRef.isIncompatibleTypedef(InstPrevTypedef, Typedef);
1080
1081 Typedef->setPreviousDecl(InstPrevTypedef);
1082 }
1083
1084 SemaRef.InstantiateAttrs(TemplateArgs, D, Typedef);
1085
1087 SemaRef.inferGslPointerAttribute(Typedef);
1088
1089 Typedef->setAccess(D->getAccess());
1090 Typedef->setReferenced(D->isReferenced());
1091
1092 return Typedef;
1093}
1094
1095Decl *TemplateDeclInstantiator::VisitTypedefDecl(TypedefDecl *D) {
1096 Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/false);
1097 if (Typedef)
1098 Owner->addDecl(Typedef);
1099 return Typedef;
1100}
1101
1102Decl *TemplateDeclInstantiator::VisitTypeAliasDecl(TypeAliasDecl *D) {
1103 Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/true);
1104 if (Typedef)
1105 Owner->addDecl(Typedef);
1106 return Typedef;
1107}
1108
1109Decl *
1110TemplateDeclInstantiator::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) {
1111 // Create a local instantiation scope for this type alias template, which
1112 // will contain the instantiations of the template parameters.
1114
1116 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1117 if (!InstParams)
1118 return nullptr;
1119
1120 TypeAliasDecl *Pattern = D->getTemplatedDecl();
1121 Sema::InstantiatingTemplate InstTemplate(
1122 SemaRef, D->getBeginLoc(), D,
1123 D->getTemplateDepth() >= TemplateArgs.getNumLevels()
1125 : (TemplateArgs.begin() + TemplateArgs.getNumLevels() - 1 -
1126 D->getTemplateDepth())
1127 ->Args);
1128 if (InstTemplate.isInvalid())
1129 return nullptr;
1130
1131 TypeAliasTemplateDecl *PrevAliasTemplate = nullptr;
1132 if (getPreviousDeclForInstantiation<TypedefNameDecl>(Pattern)) {
1133 DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
1134 if (!Found.empty()) {
1135 PrevAliasTemplate = dyn_cast<TypeAliasTemplateDecl>(Found.front());
1136 }
1137 }
1138
1139 TypeAliasDecl *AliasInst = cast_or_null<TypeAliasDecl>(
1140 InstantiateTypedefNameDecl(Pattern, /*IsTypeAlias=*/true));
1141 if (!AliasInst)
1142 return nullptr;
1143
1145 = TypeAliasTemplateDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1146 D->getDeclName(), InstParams, AliasInst);
1147 AliasInst->setDescribedAliasTemplate(Inst);
1148 if (PrevAliasTemplate)
1149 Inst->setPreviousDecl(PrevAliasTemplate);
1150
1151 Inst->setAccess(D->getAccess());
1152
1153 if (!PrevAliasTemplate)
1155
1156 Owner->addDecl(Inst);
1157
1158 return Inst;
1159}
1160
1161Decl *TemplateDeclInstantiator::VisitBindingDecl(BindingDecl *D) {
1162 auto *NewBD = BindingDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1163 D->getIdentifier());
1164 NewBD->setReferenced(D->isReferenced());
1166 return NewBD;
1167}
1168
1169Decl *TemplateDeclInstantiator::VisitDecompositionDecl(DecompositionDecl *D) {
1170 // Transform the bindings first.
1172 for (auto *OldBD : D->bindings())
1173 NewBindings.push_back(cast<BindingDecl>(VisitBindingDecl(OldBD)));
1174 ArrayRef<BindingDecl*> NewBindingArray = NewBindings;
1175
1176 auto *NewDD = cast_or_null<DecompositionDecl>(
1177 VisitVarDecl(D, /*InstantiatingVarTemplate=*/false, &NewBindingArray));
1178
1179 if (!NewDD || NewDD->isInvalidDecl())
1180 for (auto *NewBD : NewBindings)
1181 NewBD->setInvalidDecl();
1182
1183 return NewDD;
1184}
1185
1187 return VisitVarDecl(D, /*InstantiatingVarTemplate=*/false);
1188}
1189
1191 bool InstantiatingVarTemplate,
1193
1194 // Do substitution on the type of the declaration
1195 TypeSourceInfo *DI = SemaRef.SubstType(
1196 D->getTypeSourceInfo(), TemplateArgs, D->getTypeSpecStartLoc(),
1197 D->getDeclName(), /*AllowDeducedTST*/true);
1198 if (!DI)
1199 return nullptr;
1200
1201 if (DI->getType()->isFunctionType()) {
1202 SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function)
1203 << D->isStaticDataMember() << DI->getType();
1204 return nullptr;
1205 }
1206
1207 DeclContext *DC = Owner;
1208 if (D->isLocalExternDecl())
1210
1211 // Build the instantiated declaration.
1212 VarDecl *Var;
1213 if (Bindings)
1214 Var = DecompositionDecl::Create(SemaRef.Context, DC, D->getInnerLocStart(),
1215 D->getLocation(), DI->getType(), DI,
1216 D->getStorageClass(), *Bindings);
1217 else
1218 Var = VarDecl::Create(SemaRef.Context, DC, D->getInnerLocStart(),
1219 D->getLocation(), D->getIdentifier(), DI->getType(),
1220 DI, D->getStorageClass());
1221
1222 // In ARC, infer 'retaining' for variables of retainable type.
1223 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
1224 SemaRef.ObjC().inferObjCARCLifetime(Var))
1225 Var->setInvalidDecl();
1226
1227 if (SemaRef.getLangOpts().OpenCL)
1228 SemaRef.deduceOpenCLAddressSpace(Var);
1229
1230 // Substitute the nested name specifier, if any.
1231 if (SubstQualifier(D, Var))
1232 return nullptr;
1233
1234 SemaRef.BuildVariableInstantiation(Var, D, TemplateArgs, LateAttrs, Owner,
1235 StartingScope, InstantiatingVarTemplate);
1236 if (D->isNRVOVariable() && !Var->isInvalidDecl()) {
1237 QualType RT;
1238 if (auto *F = dyn_cast<FunctionDecl>(DC))
1239 RT = F->getReturnType();
1240 else if (isa<BlockDecl>(DC))
1241 RT = cast<FunctionType>(SemaRef.getCurBlock()->FunctionType)
1242 ->getReturnType();
1243 else
1244 llvm_unreachable("Unknown context type");
1245
1246 // This is the last chance we have of checking copy elision eligibility
1247 // for functions in dependent contexts. The sema actions for building
1248 // the return statement during template instantiation will have no effect
1249 // regarding copy elision, since NRVO propagation runs on the scope exit
1250 // actions, and these are not run on instantiation.
1251 // This might run through some VarDecls which were returned from non-taken
1252 // 'if constexpr' branches, and these will end up being constructed on the
1253 // return slot even if they will never be returned, as a sort of accidental
1254 // 'optimization'. Notably, functions with 'auto' return types won't have it
1255 // deduced by this point. Coupled with the limitation described
1256 // previously, this makes it very hard to support copy elision for these.
1257 Sema::NamedReturnInfo Info = SemaRef.getNamedReturnInfo(Var);
1258 bool NRVO = SemaRef.getCopyElisionCandidate(Info, RT) != nullptr;
1259 Var->setNRVOVariable(NRVO);
1260 }
1261
1262 Var->setImplicit(D->isImplicit());
1263
1264 if (Var->isStaticLocal())
1265 SemaRef.CheckStaticLocalForDllExport(Var);
1266
1267 if (Var->getTLSKind())
1269
1270 return Var;
1271}
1272
1273Decl *TemplateDeclInstantiator::VisitAccessSpecDecl(AccessSpecDecl *D) {
1274 AccessSpecDecl* AD
1275 = AccessSpecDecl::Create(SemaRef.Context, D->getAccess(), Owner,
1277 Owner->addHiddenDecl(AD);
1278 return AD;
1279}
1280
1281Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) {
1282 bool Invalid = false;
1286 DI = SemaRef.SubstType(DI, TemplateArgs,
1287 D->getLocation(), D->getDeclName());
1288 if (!DI) {
1289 DI = D->getTypeSourceInfo();
1290 Invalid = true;
1291 } else if (DI->getType()->isFunctionType()) {
1292 // C++ [temp.arg.type]p3:
1293 // If a declaration acquires a function type through a type
1294 // dependent on a template-parameter and this causes a
1295 // declaration that does not use the syntactic form of a
1296 // function declarator to have function type, the program is
1297 // ill-formed.
1298 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
1299 << DI->getType();
1300 Invalid = true;
1301 }
1302 } else {
1304 }
1305
1306 Expr *BitWidth = D->getBitWidth();
1307 if (Invalid)
1308 BitWidth = nullptr;
1309 else if (BitWidth) {
1310 // The bit-width expression is a constant expression.
1313
1314 ExprResult InstantiatedBitWidth
1315 = SemaRef.SubstExpr(BitWidth, TemplateArgs);
1316 if (InstantiatedBitWidth.isInvalid()) {
1317 Invalid = true;
1318 BitWidth = nullptr;
1319 } else
1320 BitWidth = InstantiatedBitWidth.getAs<Expr>();
1321 }
1322
1323 FieldDecl *Field = SemaRef.CheckFieldDecl(D->getDeclName(),
1324 DI->getType(), DI,
1325 cast<RecordDecl>(Owner),
1326 D->getLocation(),
1327 D->isMutable(),
1328 BitWidth,
1330 D->getInnerLocStart(),
1331 D->getAccess(),
1332 nullptr);
1333 if (!Field) {
1334 cast<Decl>(Owner)->setInvalidDecl();
1335 return nullptr;
1336 }
1337
1338 SemaRef.InstantiateAttrs(TemplateArgs, D, Field, LateAttrs, StartingScope);
1339
1340 if (Field->hasAttrs())
1341 SemaRef.CheckAlignasUnderalignment(Field);
1342
1343 if (Invalid)
1344 Field->setInvalidDecl();
1345
1346 if (!Field->getDeclName()) {
1347 // Keep track of where this decl came from.
1349 }
1350 if (CXXRecordDecl *Parent= dyn_cast<CXXRecordDecl>(Field->getDeclContext())) {
1351 if (Parent->isAnonymousStructOrUnion() &&
1352 Parent->getRedeclContext()->isFunctionOrMethod())
1354 }
1355
1356 Field->setImplicit(D->isImplicit());
1357 Field->setAccess(D->getAccess());
1358 Owner->addDecl(Field);
1359
1360 return Field;
1361}
1362
1363Decl *TemplateDeclInstantiator::VisitMSPropertyDecl(MSPropertyDecl *D) {
1364 bool Invalid = false;
1366
1367 if (DI->getType()->isVariablyModifiedType()) {
1368 SemaRef.Diag(D->getLocation(), diag::err_property_is_variably_modified)
1369 << D;
1370 Invalid = true;
1371 } else if (DI->getType()->isInstantiationDependentType()) {
1372 DI = SemaRef.SubstType(DI, TemplateArgs,
1373 D->getLocation(), D->getDeclName());
1374 if (!DI) {
1375 DI = D->getTypeSourceInfo();
1376 Invalid = true;
1377 } else if (DI->getType()->isFunctionType()) {
1378 // C++ [temp.arg.type]p3:
1379 // If a declaration acquires a function type through a type
1380 // dependent on a template-parameter and this causes a
1381 // declaration that does not use the syntactic form of a
1382 // function declarator to have function type, the program is
1383 // ill-formed.
1384 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
1385 << DI->getType();
1386 Invalid = true;
1387 }
1388 } else {
1390 }
1391
1393 SemaRef.Context, Owner, D->getLocation(), D->getDeclName(), DI->getType(),
1394 DI, D->getBeginLoc(), D->getGetterId(), D->getSetterId());
1395
1396 SemaRef.InstantiateAttrs(TemplateArgs, D, Property, LateAttrs,
1397 StartingScope);
1398
1399 if (Invalid)
1400 Property->setInvalidDecl();
1401
1402 Property->setAccess(D->getAccess());
1403 Owner->addDecl(Property);
1404
1405 return Property;
1406}
1407
1408Decl *TemplateDeclInstantiator::VisitIndirectFieldDecl(IndirectFieldDecl *D) {
1409 NamedDecl **NamedChain =
1410 new (SemaRef.Context)NamedDecl*[D->getChainingSize()];
1411
1412 int i = 0;
1413 for (auto *PI : D->chain()) {
1414 NamedDecl *Next = SemaRef.FindInstantiatedDecl(D->getLocation(), PI,
1415 TemplateArgs);
1416 if (!Next)
1417 return nullptr;
1418
1419 NamedChain[i++] = Next;
1420 }
1421
1422 QualType T = cast<FieldDecl>(NamedChain[i-1])->getType();
1424 SemaRef.Context, Owner, D->getLocation(), D->getIdentifier(), T,
1425 {NamedChain, D->getChainingSize()});
1426
1427 for (const auto *Attr : D->attrs())
1428 IndirectField->addAttr(Attr->clone(SemaRef.Context));
1429
1430 IndirectField->setImplicit(D->isImplicit());
1431 IndirectField->setAccess(D->getAccess());
1432 Owner->addDecl(IndirectField);
1433 return IndirectField;
1434}
1435
1436Decl *TemplateDeclInstantiator::VisitFriendDecl(FriendDecl *D) {
1437 // Handle friend type expressions by simply substituting template
1438 // parameters into the pattern type and checking the result.
1439 if (TypeSourceInfo *Ty = D->getFriendType()) {
1440 TypeSourceInfo *InstTy;
1441 // If this is an unsupported friend, don't bother substituting template
1442 // arguments into it. The actual type referred to won't be used by any
1443 // parts of Clang, and may not be valid for instantiating. Just use the
1444 // same info for the instantiated friend.
1445 if (D->isUnsupportedFriend()) {
1446 InstTy = Ty;
1447 } else {
1448 InstTy = SemaRef.SubstType(Ty, TemplateArgs,
1450 }
1451 if (!InstTy)
1452 return nullptr;
1453
1455 SemaRef.Context, Owner, D->getLocation(), InstTy, D->getFriendLoc());
1456 FD->setAccess(AS_public);
1458 Owner->addDecl(FD);
1459 return FD;
1460 }
1461
1462 NamedDecl *ND = D->getFriendDecl();
1463 assert(ND && "friend decl must be a decl or a type!");
1464
1465 // All of the Visit implementations for the various potential friend
1466 // declarations have to be carefully written to work for friend
1467 // objects, with the most important detail being that the target
1468 // decl should almost certainly not be placed in Owner.
1469 Decl *NewND = Visit(ND);
1470 if (!NewND) return nullptr;
1471
1472 FriendDecl *FD =
1473 FriendDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1474 cast<NamedDecl>(NewND), D->getFriendLoc());
1475 FD->setAccess(AS_public);
1477 Owner->addDecl(FD);
1478 return FD;
1479}
1480
1481Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) {
1482 Expr *AssertExpr = D->getAssertExpr();
1483
1484 // The expression in a static assertion is a constant expression.
1487
1488 ExprResult InstantiatedAssertExpr
1489 = SemaRef.SubstExpr(AssertExpr, TemplateArgs);
1490 if (InstantiatedAssertExpr.isInvalid())
1491 return nullptr;
1492
1493 ExprResult InstantiatedMessageExpr =
1494 SemaRef.SubstExpr(D->getMessage(), TemplateArgs);
1495 if (InstantiatedMessageExpr.isInvalid())
1496 return nullptr;
1497
1498 return SemaRef.BuildStaticAssertDeclaration(
1499 D->getLocation(), InstantiatedAssertExpr.get(),
1500 InstantiatedMessageExpr.get(), D->getRParenLoc(), D->isFailed());
1501}
1502
1503Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) {
1504 EnumDecl *PrevDecl = nullptr;
1505 if (EnumDecl *PatternPrev = getPreviousDeclForInstantiation(D)) {
1506 NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
1507 PatternPrev,
1508 TemplateArgs);
1509 if (!Prev) return nullptr;
1510 PrevDecl = cast<EnumDecl>(Prev);
1511 }
1512
1513 EnumDecl *Enum =
1514 EnumDecl::Create(SemaRef.Context, Owner, D->getBeginLoc(),
1515 D->getLocation(), D->getIdentifier(), PrevDecl,
1516 D->isScoped(), D->isScopedUsingClassTag(), D->isFixed());
1517 if (D->isFixed()) {
1519 // If we have type source information for the underlying type, it means it
1520 // has been explicitly set by the user. Perform substitution on it before
1521 // moving on.
1522 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
1523 TypeSourceInfo *NewTI = SemaRef.SubstType(TI, TemplateArgs, UnderlyingLoc,
1524 DeclarationName());
1525 if (!NewTI || SemaRef.CheckEnumUnderlyingType(NewTI))
1526 Enum->setIntegerType(SemaRef.Context.IntTy);
1527 else
1528 Enum->setIntegerTypeSourceInfo(NewTI);
1529 } else {
1530 assert(!D->getIntegerType()->isDependentType()
1531 && "Dependent type without type source info");
1532 Enum->setIntegerType(D->getIntegerType());
1533 }
1534 }
1535
1536 SemaRef.InstantiateAttrs(TemplateArgs, D, Enum);
1537
1538 Enum->setInstantiationOfMemberEnum(D, TSK_ImplicitInstantiation);
1539 Enum->setAccess(D->getAccess());
1540 // Forward the mangling number from the template to the instantiated decl.
1542 // See if the old tag was defined along with a declarator.
1543 // If it did, mark the new tag as being associated with that declarator.
1546 // See if the old tag was defined along with a typedef.
1547 // If it did, mark the new tag as being associated with that typedef.
1550 if (SubstQualifier(D, Enum)) return nullptr;
1551 Owner->addDecl(Enum);
1552
1553 EnumDecl *Def = D->getDefinition();
1554 if (Def && Def != D) {
1555 // If this is an out-of-line definition of an enum member template, check
1556 // that the underlying types match in the instantiation of both
1557 // declarations.
1558 if (TypeSourceInfo *TI = Def->getIntegerTypeSourceInfo()) {
1559 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
1560 QualType DefnUnderlying =
1561 SemaRef.SubstType(TI->getType(), TemplateArgs,
1562 UnderlyingLoc, DeclarationName());
1563 SemaRef.CheckEnumRedeclaration(Def->getLocation(), Def->isScoped(),
1564 DefnUnderlying, /*IsFixed=*/true, Enum);
1565 }
1566 }
1567
1568 // C++11 [temp.inst]p1: The implicit instantiation of a class template
1569 // specialization causes the implicit instantiation of the declarations, but
1570 // not the definitions of scoped member enumerations.
1571 //
1572 // DR1484 clarifies that enumeration definitions inside of a template
1573 // declaration aren't considered entities that can be separately instantiated
1574 // from the rest of the entity they are declared inside of.
1575 if (isDeclWithinFunction(D) ? D == Def : Def && !Enum->isScoped()) {
1578 }
1579
1580 return Enum;
1581}
1582
1584 EnumDecl *Enum, EnumDecl *Pattern) {
1585 Enum->startDefinition();
1586
1587 // Update the location to refer to the definition.
1588 Enum->setLocation(Pattern->getLocation());
1589
1590 SmallVector<Decl*, 4> Enumerators;
1591
1592 EnumConstantDecl *LastEnumConst = nullptr;
1593 for (auto *EC : Pattern->enumerators()) {
1594 // The specified value for the enumerator.
1595 ExprResult Value((Expr *)nullptr);
1596 if (Expr *UninstValue = EC->getInitExpr()) {
1597 // The enumerator's value expression is a constant expression.
1600
1601 Value = SemaRef.SubstExpr(UninstValue, TemplateArgs);
1602 }
1603
1604 // Drop the initial value and continue.
1605 bool isInvalid = false;
1606 if (Value.isInvalid()) {
1607 Value = nullptr;
1608 isInvalid = true;
1609 }
1610
1611 EnumConstantDecl *EnumConst
1612 = SemaRef.CheckEnumConstant(Enum, LastEnumConst,
1613 EC->getLocation(), EC->getIdentifier(),
1614 Value.get());
1615
1616 if (isInvalid) {
1617 if (EnumConst)
1618 EnumConst->setInvalidDecl();
1619 Enum->setInvalidDecl();
1620 }
1621
1622 if (EnumConst) {
1623 SemaRef.InstantiateAttrs(TemplateArgs, EC, EnumConst);
1624
1625 EnumConst->setAccess(Enum->getAccess());
1626 Enum->addDecl(EnumConst);
1627 Enumerators.push_back(EnumConst);
1628 LastEnumConst = EnumConst;
1629
1630 if (Pattern->getDeclContext()->isFunctionOrMethod() &&
1631 !Enum->isScoped()) {
1632 // If the enumeration is within a function or method, record the enum
1633 // constant as a local.
1634 SemaRef.CurrentInstantiationScope->InstantiatedLocal(EC, EnumConst);
1635 }
1636 }
1637 }
1638
1639 SemaRef.ActOnEnumBody(Enum->getLocation(), Enum->getBraceRange(), Enum,
1640 Enumerators, nullptr, ParsedAttributesView());
1641}
1642
1643Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) {
1644 llvm_unreachable("EnumConstantDecls can only occur within EnumDecls.");
1645}
1646
1647Decl *
1648TemplateDeclInstantiator::VisitBuiltinTemplateDecl(BuiltinTemplateDecl *D) {
1649 llvm_unreachable("BuiltinTemplateDecls cannot be instantiated.");
1650}
1651
1652Decl *TemplateDeclInstantiator::VisitClassTemplateDecl(ClassTemplateDecl *D) {
1653 bool isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
1654
1655 // Create a local instantiation scope for this class template, which
1656 // will contain the instantiations of the template parameters.
1659 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1660 if (!InstParams)
1661 return nullptr;
1662
1663 CXXRecordDecl *Pattern = D->getTemplatedDecl();
1664
1665 // Instantiate the qualifier. We have to do this first in case
1666 // we're a friend declaration, because if we are then we need to put
1667 // the new declaration in the appropriate context.
1668 NestedNameSpecifierLoc QualifierLoc = Pattern->getQualifierLoc();
1669 if (QualifierLoc) {
1670 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
1671 TemplateArgs);
1672 if (!QualifierLoc)
1673 return nullptr;
1674 }
1675
1676 CXXRecordDecl *PrevDecl = nullptr;
1677 ClassTemplateDecl *PrevClassTemplate = nullptr;
1678
1679 if (!isFriend && getPreviousDeclForInstantiation(Pattern)) {
1680 DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
1681 if (!Found.empty()) {
1682 PrevClassTemplate = dyn_cast<ClassTemplateDecl>(Found.front());
1683 if (PrevClassTemplate)
1684 PrevDecl = PrevClassTemplate->getTemplatedDecl();
1685 }
1686 }
1687
1688 // If this isn't a friend, then it's a member template, in which
1689 // case we just want to build the instantiation in the
1690 // specialization. If it is a friend, we want to build it in
1691 // the appropriate context.
1692 DeclContext *DC = Owner;
1693 if (isFriend) {
1694 if (QualifierLoc) {
1695 CXXScopeSpec SS;
1696 SS.Adopt(QualifierLoc);
1697 DC = SemaRef.computeDeclContext(SS);
1698 if (!DC) return nullptr;
1699 } else {
1700 DC = SemaRef.FindInstantiatedContext(Pattern->getLocation(),
1701 Pattern->getDeclContext(),
1702 TemplateArgs);
1703 }
1704
1705 // Look for a previous declaration of the template in the owning
1706 // context.
1707 LookupResult R(SemaRef, Pattern->getDeclName(), Pattern->getLocation(),
1710 SemaRef.LookupQualifiedName(R, DC);
1711
1712 if (R.isSingleResult()) {
1713 PrevClassTemplate = R.getAsSingle<ClassTemplateDecl>();
1714 if (PrevClassTemplate)
1715 PrevDecl = PrevClassTemplate->getTemplatedDecl();
1716 }
1717
1718 if (!PrevClassTemplate && QualifierLoc) {
1719 SemaRef.Diag(Pattern->getLocation(), diag::err_not_tag_in_scope)
1720 << llvm::to_underlying(D->getTemplatedDecl()->getTagKind())
1721 << Pattern->getDeclName() << DC << QualifierLoc.getSourceRange();
1722 return nullptr;
1723 }
1724 }
1725
1727 SemaRef.Context, Pattern->getTagKind(), DC, Pattern->getBeginLoc(),
1728 Pattern->getLocation(), Pattern->getIdentifier(), PrevDecl,
1729 /*DelayTypeCreation=*/true);
1730 if (QualifierLoc)
1731 RecordInst->setQualifierInfo(QualifierLoc);
1732
1733 SemaRef.InstantiateAttrsForDecl(TemplateArgs, Pattern, RecordInst, LateAttrs,
1734 StartingScope);
1735
1736 ClassTemplateDecl *Inst
1737 = ClassTemplateDecl::Create(SemaRef.Context, DC, D->getLocation(),
1738 D->getIdentifier(), InstParams, RecordInst);
1739 RecordInst->setDescribedClassTemplate(Inst);
1740
1741 if (isFriend) {
1742 assert(!Owner->isDependentContext());
1743 Inst->setLexicalDeclContext(Owner);
1744 RecordInst->setLexicalDeclContext(Owner);
1745 Inst->setObjectOfFriendDecl();
1746
1747 if (PrevClassTemplate) {
1748 Inst->setCommonPtr(PrevClassTemplate->getCommonPtr());
1749 RecordInst->setTypeForDecl(
1750 PrevClassTemplate->getTemplatedDecl()->getTypeForDecl());
1751 const ClassTemplateDecl *MostRecentPrevCT =
1752 PrevClassTemplate->getMostRecentDecl();
1753 TemplateParameterList *PrevParams =
1754 MostRecentPrevCT->getTemplateParameters();
1755
1756 // Make sure the parameter lists match.
1757 if (!SemaRef.TemplateParameterListsAreEqual(
1758 RecordInst, InstParams, MostRecentPrevCT->getTemplatedDecl(),
1759 PrevParams, true, Sema::TPL_TemplateMatch))
1760 return nullptr;
1761
1762 // Do some additional validation, then merge default arguments
1763 // from the existing declarations.
1764 if (SemaRef.CheckTemplateParameterList(InstParams, PrevParams,
1766 return nullptr;
1767
1768 Inst->setAccess(PrevClassTemplate->getAccess());
1769 } else {
1770 Inst->setAccess(D->getAccess());
1771 }
1772
1773 Inst->setObjectOfFriendDecl();
1774 // TODO: do we want to track the instantiation progeny of this
1775 // friend target decl?
1776 } else {
1777 Inst->setAccess(D->getAccess());
1778 if (!PrevClassTemplate)
1780 }
1781
1782 Inst->setPreviousDecl(PrevClassTemplate);
1783
1784 // Trigger creation of the type for the instantiation.
1786 RecordInst, Inst->getInjectedClassNameSpecialization());
1787
1788 // Finish handling of friends.
1789 if (isFriend) {
1790 DC->makeDeclVisibleInContext(Inst);
1791 return Inst;
1792 }
1793
1794 if (D->isOutOfLine()) {
1797 }
1798
1799 Owner->addDecl(Inst);
1800
1801 if (!PrevClassTemplate) {
1802 // Queue up any out-of-line partial specializations of this member
1803 // class template; the client will force their instantiation once
1804 // the enclosing class has been instantiated.
1806 D->getPartialSpecializations(PartialSpecs);
1807 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
1808 if (PartialSpecs[I]->getFirstDecl()->isOutOfLine())
1809 OutOfLinePartialSpecs.push_back(std::make_pair(Inst, PartialSpecs[I]));
1810 }
1811
1812 return Inst;
1813}
1814
1815Decl *
1816TemplateDeclInstantiator::VisitClassTemplatePartialSpecializationDecl(
1818 ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
1819
1820 // Lookup the already-instantiated declaration in the instantiation
1821 // of the class template and return that.
1823 = Owner->lookup(ClassTemplate->getDeclName());
1824 if (Found.empty())
1825 return nullptr;
1826
1827 ClassTemplateDecl *InstClassTemplate
1828 = dyn_cast<ClassTemplateDecl>(Found.front());
1829 if (!InstClassTemplate)
1830 return nullptr;
1831
1833 = InstClassTemplate->findPartialSpecInstantiatedFromMember(D))
1834 return Result;
1835
1836 return InstantiateClassTemplatePartialSpecialization(InstClassTemplate, D);
1837}
1838
1839Decl *TemplateDeclInstantiator::VisitVarTemplateDecl(VarTemplateDecl *D) {
1840 assert(D->getTemplatedDecl()->isStaticDataMember() &&
1841 "Only static data member templates are allowed.");
1842
1843 // Create a local instantiation scope for this variable template, which
1844 // will contain the instantiations of the template parameters.
1847 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1848 if (!InstParams)
1849 return nullptr;
1850
1851 VarDecl *Pattern = D->getTemplatedDecl();
1852 VarTemplateDecl *PrevVarTemplate = nullptr;
1853
1854 if (getPreviousDeclForInstantiation(Pattern)) {
1855 DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
1856 if (!Found.empty())
1857 PrevVarTemplate = dyn_cast<VarTemplateDecl>(Found.front());
1858 }
1859
1860 VarDecl *VarInst =
1861 cast_or_null<VarDecl>(VisitVarDecl(Pattern,
1862 /*InstantiatingVarTemplate=*/true));
1863 if (!VarInst) return nullptr;
1864
1865 DeclContext *DC = Owner;
1866
1868 SemaRef.Context, DC, D->getLocation(), D->getIdentifier(), InstParams,
1869 VarInst);
1870 VarInst->setDescribedVarTemplate(Inst);
1871 Inst->setPreviousDecl(PrevVarTemplate);
1872
1873 Inst->setAccess(D->getAccess());
1874 if (!PrevVarTemplate)
1876
1877 if (D->isOutOfLine()) {
1880 }
1881
1882 Owner->addDecl(Inst);
1883
1884 if (!PrevVarTemplate) {
1885 // Queue up any out-of-line partial specializations of this member
1886 // variable template; the client will force their instantiation once
1887 // the enclosing class has been instantiated.
1889 D->getPartialSpecializations(PartialSpecs);
1890 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
1891 if (PartialSpecs[I]->getFirstDecl()->isOutOfLine())
1892 OutOfLineVarPartialSpecs.push_back(
1893 std::make_pair(Inst, PartialSpecs[I]));
1894 }
1895
1896 return Inst;
1897}
1898
1899Decl *TemplateDeclInstantiator::VisitVarTemplatePartialSpecializationDecl(
1901 assert(D->isStaticDataMember() &&
1902 "Only static data member templates are allowed.");
1903
1904 VarTemplateDecl *VarTemplate = D->getSpecializedTemplate();
1905
1906 // Lookup the already-instantiated declaration and return that.
1907 DeclContext::lookup_result Found = Owner->lookup(VarTemplate->getDeclName());
1908 assert(!Found.empty() && "Instantiation found nothing?");
1909
1910 VarTemplateDecl *InstVarTemplate = dyn_cast<VarTemplateDecl>(Found.front());
1911 assert(InstVarTemplate && "Instantiation did not find a variable template?");
1912
1914 InstVarTemplate->findPartialSpecInstantiatedFromMember(D))
1915 return Result;
1916
1917 return InstantiateVarTemplatePartialSpecialization(InstVarTemplate, D);
1918}
1919
1920Decl *
1921TemplateDeclInstantiator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
1922 // Create a local instantiation scope for this function template, which
1923 // will contain the instantiations of the template parameters and then get
1924 // merged with the local instantiation scope for the function template
1925 // itself.
1928
1930 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1931 if (!InstParams)
1932 return nullptr;
1933
1934 FunctionDecl *Instantiated = nullptr;
1935 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(D->getTemplatedDecl()))
1936 Instantiated = cast_or_null<FunctionDecl>(VisitCXXMethodDecl(DMethod,
1937 InstParams));
1938 else
1939 Instantiated = cast_or_null<FunctionDecl>(VisitFunctionDecl(
1940 D->getTemplatedDecl(),
1941 InstParams));
1942
1943 if (!Instantiated)
1944 return nullptr;
1945
1946 // Link the instantiated function template declaration to the function
1947 // template from which it was instantiated.
1948 FunctionTemplateDecl *InstTemplate
1949 = Instantiated->getDescribedFunctionTemplate();
1950 InstTemplate->setAccess(D->getAccess());
1951 assert(InstTemplate &&
1952 "VisitFunctionDecl/CXXMethodDecl didn't create a template!");
1953
1954 bool isFriend = (InstTemplate->getFriendObjectKind() != Decl::FOK_None);
1955
1956 // Link the instantiation back to the pattern *unless* this is a
1957 // non-definition friend declaration.
1958 if (!InstTemplate->getInstantiatedFromMemberTemplate() &&
1959 !(isFriend && !D->getTemplatedDecl()->isThisDeclarationADefinition()))
1960 InstTemplate->setInstantiatedFromMemberTemplate(D);
1961
1962 // Make declarations visible in the appropriate context.
1963 if (!isFriend) {
1964 Owner->addDecl(InstTemplate);
1965 } else if (InstTemplate->getDeclContext()->isRecord() &&
1967 SemaRef.CheckFriendAccess(InstTemplate);
1968 }
1969
1970 return InstTemplate;
1971}
1972
1973Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) {
1974 CXXRecordDecl *PrevDecl = nullptr;
1975 if (CXXRecordDecl *PatternPrev = getPreviousDeclForInstantiation(D)) {
1976 NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
1977 PatternPrev,
1978 TemplateArgs);
1979 if (!Prev) return nullptr;
1980 PrevDecl = cast<CXXRecordDecl>(Prev);
1981 }
1982
1983 CXXRecordDecl *Record = nullptr;
1984 bool IsInjectedClassName = D->isInjectedClassName();
1985 if (D->isLambda())
1987 SemaRef.Context, Owner, D->getLambdaTypeInfo(), D->getLocation(),
1990 else
1991 Record = CXXRecordDecl::Create(SemaRef.Context, D->getTagKind(), Owner,
1992 D->getBeginLoc(), D->getLocation(),
1993 D->getIdentifier(), PrevDecl,
1994 /*DelayTypeCreation=*/IsInjectedClassName);
1995 // Link the type of the injected-class-name to that of the outer class.
1996 if (IsInjectedClassName)
1997 (void)SemaRef.Context.getTypeDeclType(Record, cast<CXXRecordDecl>(Owner));
1998
1999 // Substitute the nested name specifier, if any.
2000 if (SubstQualifier(D, Record))
2001 return nullptr;
2002
2003 SemaRef.InstantiateAttrsForDecl(TemplateArgs, D, Record, LateAttrs,
2004 StartingScope);
2005
2006 Record->setImplicit(D->isImplicit());
2007 // FIXME: Check against AS_none is an ugly hack to work around the issue that
2008 // the tag decls introduced by friend class declarations don't have an access
2009 // specifier. Remove once this area of the code gets sorted out.
2010 if (D->getAccess() != AS_none)
2011 Record->setAccess(D->getAccess());
2012 if (!IsInjectedClassName)
2013 Record->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
2014
2015 // If the original function was part of a friend declaration,
2016 // inherit its namespace state.
2017 if (D->getFriendObjectKind())
2018 Record->setObjectOfFriendDecl();
2019
2020 // Make sure that anonymous structs and unions are recorded.
2021 if (D->isAnonymousStructOrUnion())
2022 Record->setAnonymousStructOrUnion(true);
2023
2024 if (D->isLocalClass())
2026
2027 // Forward the mangling number from the template to the instantiated decl.
2029 SemaRef.Context.getManglingNumber(D));
2030
2031 // See if the old tag was defined along with a declarator.
2032 // If it did, mark the new tag as being associated with that declarator.
2035
2036 // See if the old tag was defined along with a typedef.
2037 // If it did, mark the new tag as being associated with that typedef.
2040
2041 Owner->addDecl(Record);
2042
2043 // DR1484 clarifies that the members of a local class are instantiated as part
2044 // of the instantiation of their enclosing entity.
2045 if (D->isCompleteDefinition() && D->isLocalClass()) {
2046 Sema::LocalEagerInstantiationScope LocalInstantiations(SemaRef);
2047
2048 SemaRef.InstantiateClass(D->getLocation(), Record, D, TemplateArgs,
2050 /*Complain=*/true);
2051
2052 // For nested local classes, we will instantiate the members when we
2053 // reach the end of the outermost (non-nested) local class.
2054 if (!D->isCXXClassMember())
2055 SemaRef.InstantiateClassMembers(D->getLocation(), Record, TemplateArgs,
2057
2058 // This class may have local implicit instantiations that need to be
2059 // performed within this scope.
2060 LocalInstantiations.perform();
2061 }
2062
2064
2065 if (IsInjectedClassName)
2066 assert(Record->isInjectedClassName() && "Broken injected-class-name");
2067
2068 return Record;
2069}
2070
2071/// Adjust the given function type for an instantiation of the
2072/// given declaration, to cope with modifications to the function's type that
2073/// aren't reflected in the type-source information.
2074///
2075/// \param D The declaration we're instantiating.
2076/// \param TInfo The already-instantiated type.
2078 FunctionDecl *D,
2079 TypeSourceInfo *TInfo) {
2080 const FunctionProtoType *OrigFunc
2081 = D->getType()->castAs<FunctionProtoType>();
2082 const FunctionProtoType *NewFunc
2083 = TInfo->getType()->castAs<FunctionProtoType>();
2084 if (OrigFunc->getExtInfo() == NewFunc->getExtInfo())
2085 return TInfo->getType();
2086
2087 FunctionProtoType::ExtProtoInfo NewEPI = NewFunc->getExtProtoInfo();
2088 NewEPI.ExtInfo = OrigFunc->getExtInfo();
2089 return Context.getFunctionType(NewFunc->getReturnType(),
2090 NewFunc->getParamTypes(), NewEPI);
2091}
2092
2093/// Normal class members are of more specific types and therefore
2094/// don't make it here. This function serves three purposes:
2095/// 1) instantiating function templates
2096/// 2) substituting friend and local function declarations
2097/// 3) substituting deduction guide declarations for nested class templates
2099 FunctionDecl *D, TemplateParameterList *TemplateParams,
2100 RewriteKind FunctionRewriteKind) {
2101 // Check whether there is already a function template specialization for
2102 // this declaration.
2103 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
2104 if (FunctionTemplate && !TemplateParams) {
2105 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
2106
2107 void *InsertPos = nullptr;
2108 FunctionDecl *SpecFunc
2109 = FunctionTemplate->findSpecialization(Innermost, InsertPos);
2110
2111 // If we already have a function template specialization, return it.
2112 if (SpecFunc)
2113 return SpecFunc;
2114 }
2115
2116 bool isFriend;
2117 if (FunctionTemplate)
2118 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
2119 else
2120 isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
2121
2122 bool MergeWithParentScope = (TemplateParams != nullptr) ||
2123 Owner->isFunctionOrMethod() ||
2124 !(isa<Decl>(Owner) &&
2125 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
2126 LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
2127
2128 ExplicitSpecifier InstantiatedExplicitSpecifier;
2129 if (auto *DGuide = dyn_cast<CXXDeductionGuideDecl>(D)) {
2130 InstantiatedExplicitSpecifier = SemaRef.instantiateExplicitSpecifier(
2131 TemplateArgs, DGuide->getExplicitSpecifier());
2132 if (InstantiatedExplicitSpecifier.isInvalid())
2133 return nullptr;
2134 }
2135
2137 TypeSourceInfo *TInfo = SubstFunctionType(D, Params);
2138 if (!TInfo)
2139 return nullptr;
2141
2142 if (TemplateParams && TemplateParams->size()) {
2143 auto *LastParam =
2144 dyn_cast<TemplateTypeParmDecl>(TemplateParams->asArray().back());
2145 if (LastParam && LastParam->isImplicit() &&
2146 LastParam->hasTypeConstraint()) {
2147 // In abbreviated templates, the type-constraints of invented template
2148 // type parameters are instantiated with the function type, invalidating
2149 // the TemplateParameterList which relied on the template type parameter
2150 // not having a type constraint. Recreate the TemplateParameterList with
2151 // the updated parameter list.
2152 TemplateParams = TemplateParameterList::Create(
2153 SemaRef.Context, TemplateParams->getTemplateLoc(),
2154 TemplateParams->getLAngleLoc(), TemplateParams->asArray(),
2155 TemplateParams->getRAngleLoc(), TemplateParams->getRequiresClause());
2156 }
2157 }
2158
2159 NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
2160 if (QualifierLoc) {
2161 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
2162 TemplateArgs);
2163 if (!QualifierLoc)
2164 return nullptr;
2165 }
2166
2167 Expr *TrailingRequiresClause = D->getTrailingRequiresClause();
2168
2169 // If we're instantiating a local function declaration, put the result
2170 // in the enclosing namespace; otherwise we need to find the instantiated
2171 // context.
2172 DeclContext *DC;
2173 if (D->isLocalExternDecl()) {
2174 DC = Owner;
2176 } else if (isFriend && QualifierLoc) {
2177 CXXScopeSpec SS;
2178 SS.Adopt(QualifierLoc);
2179 DC = SemaRef.computeDeclContext(SS);
2180 if (!DC) return nullptr;
2181 } else {
2182 DC = SemaRef.FindInstantiatedContext(D->getLocation(), D->getDeclContext(),
2183 TemplateArgs);
2184 }
2185
2186 DeclarationNameInfo NameInfo
2187 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
2188
2189 if (FunctionRewriteKind != RewriteKind::None)
2190 adjustForRewrite(FunctionRewriteKind, D, T, TInfo, NameInfo);
2191
2193 if (auto *DGuide = dyn_cast<CXXDeductionGuideDecl>(D)) {
2195 SemaRef.Context, DC, D->getInnerLocStart(),
2196 InstantiatedExplicitSpecifier, NameInfo, T, TInfo,
2197 D->getSourceRange().getEnd(), DGuide->getCorrespondingConstructor(),
2198 DGuide->getDeductionCandidateKind());
2199 Function->setAccess(D->getAccess());
2200 } else {
2202 SemaRef.Context, DC, D->getInnerLocStart(), NameInfo, T, TInfo,
2205 TrailingRequiresClause);
2206 Function->setFriendConstraintRefersToEnclosingTemplate(
2208 Function->setRangeEnd(D->getSourceRange().getEnd());
2209 }
2210
2211 if (D->isInlined())
2212 Function->setImplicitlyInline();
2213
2214 if (QualifierLoc)
2215 Function->setQualifierInfo(QualifierLoc);
2216
2217 if (D->isLocalExternDecl())
2218 Function->setLocalExternDecl();
2219
2220 DeclContext *LexicalDC = Owner;
2221 if (!isFriend && D->isOutOfLine() && !D->isLocalExternDecl()) {
2222 assert(D->getDeclContext()->isFileContext());
2223 LexicalDC = D->getDeclContext();
2224 }
2225 else if (D->isLocalExternDecl()) {
2226 LexicalDC = SemaRef.CurContext;
2227 }
2228
2229 Function->setLexicalDeclContext(LexicalDC);
2230
2231 // Attach the parameters
2232 for (unsigned P = 0; P < Params.size(); ++P)
2233 if (Params[P])
2234 Params[P]->setOwningFunction(Function);
2235 Function->setParams(Params);
2236
2237 if (TrailingRequiresClause)
2238 Function->setTrailingRequiresClause(TrailingRequiresClause);
2239
2240 if (TemplateParams) {
2241 // Our resulting instantiation is actually a function template, since we
2242 // are substituting only the outer template parameters. For example, given
2243 //
2244 // template<typename T>
2245 // struct X {
2246 // template<typename U> friend void f(T, U);
2247 // };
2248 //
2249 // X<int> x;
2250 //
2251 // We are instantiating the friend function template "f" within X<int>,
2252 // which means substituting int for T, but leaving "f" as a friend function
2253 // template.
2254 // Build the function template itself.
2255 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, DC,
2256 Function->getLocation(),
2257 Function->getDeclName(),
2258 TemplateParams, Function);
2259 Function->setDescribedFunctionTemplate(FunctionTemplate);
2260
2261 FunctionTemplate->setLexicalDeclContext(LexicalDC);
2262
2263 if (isFriend && D->isThisDeclarationADefinition()) {
2264 FunctionTemplate->setInstantiatedFromMemberTemplate(
2266 }
2267 } else if (FunctionTemplate &&
2268 SemaRef.CodeSynthesisContexts.back().Kind !=
2270 // Record this function template specialization.
2271 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
2272 Function->setFunctionTemplateSpecialization(FunctionTemplate,
2274 Innermost),
2275 /*InsertPos=*/nullptr);
2276 } else if (FunctionRewriteKind == RewriteKind::None) {
2277 if (isFriend && D->isThisDeclarationADefinition()) {
2278 // Do not connect the friend to the template unless it's actually a
2279 // definition. We don't want non-template functions to be marked as being
2280 // template instantiations.
2281 Function->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
2282 } else if (!isFriend) {
2283 // If this is not a function template, and this is not a friend (that is,
2284 // this is a locally declared function), save the instantiation
2285 // relationship for the purposes of constraint instantiation.
2286 Function->setInstantiatedFromDecl(D);
2287 }
2288 }
2289
2290 if (isFriend) {
2291 Function->setObjectOfFriendDecl();
2292 if (FunctionTemplateDecl *FT = Function->getDescribedFunctionTemplate())
2293 FT->setObjectOfFriendDecl();
2294 }
2295
2297 Function->setInvalidDecl();
2298
2299 bool IsExplicitSpecialization = false;
2300
2302 SemaRef, Function->getDeclName(), SourceLocation(),
2305 D->isLocalExternDecl() ? RedeclarationKind::ForExternalRedeclaration
2306 : SemaRef.forRedeclarationInCurContext());
2307
2310 assert(isFriend && "dependent specialization info on "
2311 "non-member non-friend function?");
2312
2313 // Instantiate the explicit template arguments.
2314 TemplateArgumentListInfo ExplicitArgs;
2315 if (const auto *ArgsWritten = DFTSI->TemplateArgumentsAsWritten) {
2316 ExplicitArgs.setLAngleLoc(ArgsWritten->getLAngleLoc());
2317 ExplicitArgs.setRAngleLoc(ArgsWritten->getRAngleLoc());
2318 if (SemaRef.SubstTemplateArguments(ArgsWritten->arguments(), TemplateArgs,
2319 ExplicitArgs))
2320 return nullptr;
2321 }
2322
2323 // Map the candidates for the primary template to their instantiations.
2324 for (FunctionTemplateDecl *FTD : DFTSI->getCandidates()) {
2325 if (NamedDecl *ND =
2326 SemaRef.FindInstantiatedDecl(D->getLocation(), FTD, TemplateArgs))
2327 Previous.addDecl(ND);
2328 else
2329 return nullptr;
2330 }
2331
2333 Function,
2334 DFTSI->TemplateArgumentsAsWritten ? &ExplicitArgs : nullptr,
2335 Previous))
2336 Function->setInvalidDecl();
2337
2338 IsExplicitSpecialization = true;
2339 } else if (const ASTTemplateArgumentListInfo *ArgsWritten =
2341 // The name of this function was written as a template-id.
2342 SemaRef.LookupQualifiedName(Previous, DC);
2343
2344 // Instantiate the explicit template arguments.
2345 TemplateArgumentListInfo ExplicitArgs(ArgsWritten->getLAngleLoc(),
2346 ArgsWritten->getRAngleLoc());
2347 if (SemaRef.SubstTemplateArguments(ArgsWritten->arguments(), TemplateArgs,
2348 ExplicitArgs))
2349 return nullptr;
2350
2352 &ExplicitArgs,
2353 Previous))
2354 Function->setInvalidDecl();
2355
2356 IsExplicitSpecialization = true;
2357 } else if (TemplateParams || !FunctionTemplate) {
2358 // Look only into the namespace where the friend would be declared to
2359 // find a previous declaration. This is the innermost enclosing namespace,
2360 // as described in ActOnFriendFunctionDecl.
2362
2363 // In C++, the previous declaration we find might be a tag type
2364 // (class or enum). In this case, the new declaration will hide the
2365 // tag type. Note that this does not apply if we're declaring a
2366 // typedef (C++ [dcl.typedef]p4).
2367 if (Previous.isSingleTagDecl())
2368 Previous.clear();
2369
2370 // Filter out previous declarations that don't match the scope. The only
2371 // effect this has is to remove declarations found in inline namespaces
2372 // for friend declarations with unqualified names.
2373 if (isFriend && !QualifierLoc) {
2374 SemaRef.FilterLookupForScope(Previous, DC, /*Scope=*/ nullptr,
2375 /*ConsiderLinkage=*/ true,
2376 QualifierLoc.hasQualifier());
2377 }
2378 }
2379
2380 // Per [temp.inst], default arguments in function declarations at local scope
2381 // are instantiated along with the enclosing declaration. For example:
2382 //
2383 // template<typename T>
2384 // void ft() {
2385 // void f(int = []{ return T::value; }());
2386 // }
2387 // template void ft<int>(); // error: type 'int' cannot be used prior
2388 // to '::' because it has no members
2389 //
2390 // The error is issued during instantiation of ft<int>() because substitution
2391 // into the default argument fails; the default argument is instantiated even
2392 // though it is never used.
2393 if (Function->isLocalExternDecl()) {
2394 for (ParmVarDecl *PVD : Function->parameters()) {
2395 if (!PVD->hasDefaultArg())
2396 continue;
2397 if (SemaRef.SubstDefaultArgument(D->getInnerLocStart(), PVD, TemplateArgs)) {
2398 // If substitution fails, the default argument is set to a
2399 // RecoveryExpr that wraps the uninstantiated default argument so
2400 // that downstream diagnostics are omitted.
2401 Expr *UninstExpr = PVD->getUninstantiatedDefaultArg();
2402 ExprResult ErrorResult = SemaRef.CreateRecoveryExpr(
2403 UninstExpr->getBeginLoc(), UninstExpr->getEndLoc(),
2404 { UninstExpr }, UninstExpr->getType());
2405 if (ErrorResult.isUsable())
2406 PVD->setDefaultArg(ErrorResult.get());
2407 }
2408 }
2409 }
2410
2411 SemaRef.CheckFunctionDeclaration(/*Scope*/ nullptr, Function, Previous,
2412 IsExplicitSpecialization,
2413 Function->isThisDeclarationADefinition());
2414
2415 // Check the template parameter list against the previous declaration. The
2416 // goal here is to pick up default arguments added since the friend was
2417 // declared; we know the template parameter lists match, since otherwise
2418 // we would not have picked this template as the previous declaration.
2419 if (isFriend && TemplateParams && FunctionTemplate->getPreviousDecl()) {
2421 TemplateParams,
2422 FunctionTemplate->getPreviousDecl()->getTemplateParameters(),
2423 Function->isThisDeclarationADefinition()
2426 }
2427
2428 // If we're introducing a friend definition after the first use, trigger
2429 // instantiation.
2430 // FIXME: If this is a friend function template definition, we should check
2431 // to see if any specializations have been used.
2432 if (isFriend && D->isThisDeclarationADefinition() && Function->isUsed(false)) {
2433 if (MemberSpecializationInfo *MSInfo =
2434 Function->getMemberSpecializationInfo()) {
2435 if (MSInfo->getPointOfInstantiation().isInvalid()) {
2436 SourceLocation Loc = D->getLocation(); // FIXME
2437 MSInfo->setPointOfInstantiation(Loc);
2438 SemaRef.PendingLocalImplicitInstantiations.push_back(
2439 std::make_pair(Function, Loc));
2440 }
2441 }
2442 }
2443
2444 if (D->isExplicitlyDefaulted()) {
2446 return nullptr;
2447 }
2448 if (D->isDeleted())
2450
2451 NamedDecl *PrincipalDecl =
2452 (TemplateParams ? cast<NamedDecl>(FunctionTemplate) : Function);
2453
2454 // If this declaration lives in a different context from its lexical context,
2455 // add it to the corresponding lookup table.
2456 if (isFriend ||
2457 (Function->isLocalExternDecl() && !Function->getPreviousDecl()))
2458 DC->makeDeclVisibleInContext(PrincipalDecl);
2459
2460 if (Function->isOverloadedOperator() && !DC->isRecord() &&
2462 PrincipalDecl->setNonMemberOperator();
2463
2464 return Function;
2465}
2466
2468 CXXMethodDecl *D, TemplateParameterList *TemplateParams,
2469 RewriteKind FunctionRewriteKind) {
2470 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
2471 if (FunctionTemplate && !TemplateParams) {
2472 // We are creating a function template specialization from a function
2473 // template. Check whether there is already a function template
2474 // specialization for this particular set of template arguments.
2475 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
2476
2477 void *InsertPos = nullptr;
2478 FunctionDecl *SpecFunc
2479 = FunctionTemplate->findSpecialization(Innermost, InsertPos);
2480
2481 // If we already have a function template specialization, return it.
2482 if (SpecFunc)
2483 return SpecFunc;
2484 }
2485
2486 bool isFriend;
2487 if (FunctionTemplate)
2488 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
2489 else
2490 isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
2491
2492 bool MergeWithParentScope = (TemplateParams != nullptr) ||
2493 !(isa<Decl>(Owner) &&
2494 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
2495 LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
2496
2498 SemaRef, const_cast<CXXMethodDecl *>(D), TemplateArgs, Scope);
2499
2500 // Instantiate enclosing template arguments for friends.
2502 unsigned NumTempParamLists = 0;
2503 if (isFriend && (NumTempParamLists = D->getNumTemplateParameterLists())) {
2504 TempParamLists.resize(NumTempParamLists);
2505 for (unsigned I = 0; I != NumTempParamLists; ++I) {
2507 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
2508 if (!InstParams)
2509 return nullptr;
2510 TempParamLists[I] = InstParams;
2511 }
2512 }
2513
2514 auto InstantiatedExplicitSpecifier = ExplicitSpecifier::getFromDecl(D);
2515 // deduction guides need this
2516 const bool CouldInstantiate =
2517 InstantiatedExplicitSpecifier.getExpr() == nullptr ||
2518 !InstantiatedExplicitSpecifier.getExpr()->isValueDependent();
2519
2520 // Delay the instantiation of the explicit-specifier until after the
2521 // constraints are checked during template argument deduction.
2522 if (CouldInstantiate ||
2523 SemaRef.CodeSynthesisContexts.back().Kind !=
2525 InstantiatedExplicitSpecifier = SemaRef.instantiateExplicitSpecifier(
2526 TemplateArgs, InstantiatedExplicitSpecifier);
2527
2528 if (InstantiatedExplicitSpecifier.isInvalid())
2529 return nullptr;
2530 } else {
2531 InstantiatedExplicitSpecifier.setKind(ExplicitSpecKind::Unresolved);
2532 }
2533
2534 // Implicit destructors/constructors created for local classes in
2535 // DeclareImplicit* (see SemaDeclCXX.cpp) might not have an associated TSI.
2536 // Unfortunately there isn't enough context in those functions to
2537 // conditionally populate the TSI without breaking non-template related use
2538 // cases. Populate TSIs prior to calling SubstFunctionType to make sure we get
2539 // a proper transformation.
2540 if (cast<CXXRecordDecl>(D->getParent())->isLambda() &&
2541 !D->getTypeSourceInfo() &&
2542 isa<CXXConstructorDecl, CXXDestructorDecl>(D)) {
2543 TypeSourceInfo *TSI =
2545 D->setTypeSourceInfo(TSI);
2546 }
2547
2549 TypeSourceInfo *TInfo = SubstFunctionType(D, Params);
2550 if (!TInfo)
2551 return nullptr;
2553
2554 if (TemplateParams && TemplateParams->size()) {
2555 auto *LastParam =
2556 dyn_cast<TemplateTypeParmDecl>(TemplateParams->asArray().back());
2557 if (LastParam && LastParam->isImplicit() &&
2558 LastParam->hasTypeConstraint()) {
2559 // In abbreviated templates, the type-constraints of invented template
2560 // type parameters are instantiated with the function type, invalidating
2561 // the TemplateParameterList which relied on the template type parameter
2562 // not having a type constraint. Recreate the TemplateParameterList with
2563 // the updated parameter list.
2564 TemplateParams = TemplateParameterList::Create(
2565 SemaRef.Context, TemplateParams->getTemplateLoc(),
2566 TemplateParams->getLAngleLoc(), TemplateParams->asArray(),
2567 TemplateParams->getRAngleLoc(), TemplateParams->getRequiresClause());
2568 }
2569 }
2570
2571 NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
2572 if (QualifierLoc) {
2573 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
2574 TemplateArgs);
2575 if (!QualifierLoc)
2576 return nullptr;
2577 }
2578
2579 DeclContext *DC = Owner;
2580 if (isFriend) {
2581 if (QualifierLoc) {
2582 CXXScopeSpec SS;
2583 SS.Adopt(QualifierLoc);
2584 DC = SemaRef.computeDeclContext(SS);
2585
2586 if (DC && SemaRef.RequireCompleteDeclContext(SS, DC))
2587 return nullptr;
2588 } else {
2589 DC = SemaRef.FindInstantiatedContext(D->getLocation(),
2590 D->getDeclContext(),
2591 TemplateArgs);
2592 }
2593 if (!DC) return nullptr;
2594 }
2595
2596 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
2597 Expr *TrailingRequiresClause = D->getTrailingRequiresClause();
2598
2599 DeclarationNameInfo NameInfo
2600 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
2601
2602 if (FunctionRewriteKind != RewriteKind::None)
2603 adjustForRewrite(FunctionRewriteKind, D, T, TInfo, NameInfo);
2604
2605 // Build the instantiated method declaration.
2606 CXXMethodDecl *Method = nullptr;
2607
2608 SourceLocation StartLoc = D->getInnerLocStart();
2609 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
2611 SemaRef.Context, Record, StartLoc, NameInfo, T, TInfo,
2612 InstantiatedExplicitSpecifier, Constructor->UsesFPIntrin(),
2613 Constructor->isInlineSpecified(), false,
2614 Constructor->getConstexprKind(), InheritedConstructor(),
2615 TrailingRequiresClause);
2616 Method->setRangeEnd(Constructor->getEndLoc());
2617 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
2619 SemaRef.Context, Record, StartLoc, NameInfo, T, TInfo,
2620 Destructor->UsesFPIntrin(), Destructor->isInlineSpecified(), false,
2621 Destructor->getConstexprKind(), TrailingRequiresClause);
2622 Method->setIneligibleOrNotSelected(true);
2623 Method->setRangeEnd(Destructor->getEndLoc());
2625 SemaRef.Context.getCanonicalType(
2626 SemaRef.Context.getTypeDeclType(Record))));
2627 } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) {
2629 SemaRef.Context, Record, StartLoc, NameInfo, T, TInfo,
2630 Conversion->UsesFPIntrin(), Conversion->isInlineSpecified(),
2631 InstantiatedExplicitSpecifier, Conversion->getConstexprKind(),
2632 Conversion->getEndLoc(), TrailingRequiresClause);
2633 } else {
2634 StorageClass SC = D->isStatic() ? SC_Static : SC_None;
2635 Method = CXXMethodDecl::Create(
2636 SemaRef.Context, Record, StartLoc, NameInfo, T, TInfo, SC,
2638 D->getEndLoc(), TrailingRequiresClause);
2639 }
2640
2641 if (D->isInlined())
2642 Method->setImplicitlyInline();
2643
2644 if (QualifierLoc)
2645 Method->setQualifierInfo(QualifierLoc);
2646
2647 if (TemplateParams) {
2648 // Our resulting instantiation is actually a function template, since we
2649 // are substituting only the outer template parameters. For example, given
2650 //
2651 // template<typename T>
2652 // struct X {
2653 // template<typename U> void f(T, U);
2654 // };
2655 //
2656 // X<int> x;
2657 //
2658 // We are instantiating the member template "f" within X<int>, which means
2659 // substituting int for T, but leaving "f" as a member function template.
2660 // Build the function template itself.
2661 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Record,
2662 Method->getLocation(),
2663 Method->getDeclName(),
2664 TemplateParams, Method);
2665 if (isFriend) {
2666 FunctionTemplate->setLexicalDeclContext(Owner);
2667 FunctionTemplate->setObjectOfFriendDecl();
2668 } else if (D->isOutOfLine())
2669 FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
2670 Method->setDescribedFunctionTemplate(FunctionTemplate);
2671 } else if (FunctionTemplate) {
2672 // Record this function template specialization.
2673 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
2674 Method->setFunctionTemplateSpecialization(FunctionTemplate,
2676 Innermost),
2677 /*InsertPos=*/nullptr);
2678 } else if (!isFriend && FunctionRewriteKind == RewriteKind::None) {
2679 // Record that this is an instantiation of a member function.
2681 }
2682
2683 // If we are instantiating a member function defined
2684 // out-of-line, the instantiation will have the same lexical
2685 // context (which will be a namespace scope) as the template.
2686 if (isFriend) {
2687 if (NumTempParamLists)
2689 SemaRef.Context,
2690 llvm::ArrayRef(TempParamLists.data(), NumTempParamLists));
2691
2692 Method->setLexicalDeclContext(Owner);
2693 Method->setObjectOfFriendDecl();
2694 } else if (D->isOutOfLine())
2696
2697 // Attach the parameters
2698 for (unsigned P = 0; P < Params.size(); ++P)
2699 Params[P]->setOwningFunction(Method);
2700 Method->setParams(Params);
2701
2702 if (InitMethodInstantiation(Method, D))
2703 Method->setInvalidDecl();
2704
2706 RedeclarationKind::ForExternalRedeclaration);
2707
2708 bool IsExplicitSpecialization = false;
2709
2710 // If the name of this function was written as a template-id, instantiate
2711 // the explicit template arguments.
2714 // Instantiate the explicit template arguments.
2715 TemplateArgumentListInfo ExplicitArgs;
2716 if (const auto *ArgsWritten = DFTSI->TemplateArgumentsAsWritten) {
2717 ExplicitArgs.setLAngleLoc(ArgsWritten->getLAngleLoc());
2718 ExplicitArgs.setRAngleLoc(ArgsWritten->getRAngleLoc());
2719 if (SemaRef.SubstTemplateArguments(ArgsWritten->arguments(), TemplateArgs,
2720 ExplicitArgs))
2721 return nullptr;
2722 }
2723
2724 // Map the candidates for the primary template to their instantiations.
2725 for (FunctionTemplateDecl *FTD : DFTSI->getCandidates()) {
2726 if (NamedDecl *ND =
2727 SemaRef.FindInstantiatedDecl(D->getLocation(), FTD, TemplateArgs))
2728 Previous.addDecl(ND);
2729 else
2730 return nullptr;
2731 }
2732
2734 Method, DFTSI->TemplateArgumentsAsWritten ? &ExplicitArgs : nullptr,
2735 Previous))
2736 Method->setInvalidDecl();
2737
2738 IsExplicitSpecialization = true;
2739 } else if (const ASTTemplateArgumentListInfo *ArgsWritten =
2741 SemaRef.LookupQualifiedName(Previous, DC);
2742
2743 TemplateArgumentListInfo ExplicitArgs(ArgsWritten->getLAngleLoc(),
2744 ArgsWritten->getRAngleLoc());
2745
2746 if (SemaRef.SubstTemplateArguments(ArgsWritten->arguments(), TemplateArgs,
2747 ExplicitArgs))
2748 return nullptr;
2749
2750 if (SemaRef.CheckFunctionTemplateSpecialization(Method,
2751 &ExplicitArgs,
2752 Previous))
2753 Method->setInvalidDecl();
2754
2755 IsExplicitSpecialization = true;
2756 } else if (!FunctionTemplate || TemplateParams || isFriend) {
2758
2759 // In C++, the previous declaration we find might be a tag type
2760 // (class or enum). In this case, the new declaration will hide the
2761 // tag type. Note that this does not apply if we're declaring a
2762 // typedef (C++ [dcl.typedef]p4).
2763 if (Previous.isSingleTagDecl())
2764 Previous.clear();
2765 }
2766
2767 // Per [temp.inst], default arguments in member functions of local classes
2768 // are instantiated along with the member function declaration. For example:
2769 //
2770 // template<typename T>
2771 // void ft() {
2772 // struct lc {
2773 // int operator()(int p = []{ return T::value; }());
2774 // };
2775 // }
2776 // template void ft<int>(); // error: type 'int' cannot be used prior
2777 // to '::'because it has no members
2778 //
2779 // The error is issued during instantiation of ft<int>()::lc::operator()
2780 // because substitution into the default argument fails; the default argument
2781 // is instantiated even though it is never used.
2783 for (unsigned P = 0; P < Params.size(); ++P) {
2784 if (!Params[P]->hasDefaultArg())
2785 continue;
2786 if (SemaRef.SubstDefaultArgument(StartLoc, Params[P], TemplateArgs)) {
2787 // If substitution fails, the default argument is set to a
2788 // RecoveryExpr that wraps the uninstantiated default argument so
2789 // that downstream diagnostics are omitted.
2790 Expr *UninstExpr = Params[P]->getUninstantiatedDefaultArg();
2791 ExprResult ErrorResult = SemaRef.CreateRecoveryExpr(
2792 UninstExpr->getBeginLoc(), UninstExpr->getEndLoc(),
2793 { UninstExpr }, UninstExpr->getType());
2794 if (ErrorResult.isUsable())
2795 Params[P]->setDefaultArg(ErrorResult.get());
2796 }
2797 }
2798 }
2799
2800 SemaRef.CheckFunctionDeclaration(nullptr, Method, Previous,
2801 IsExplicitSpecialization,
2803
2804 if (D->isPureVirtual())
2805 SemaRef.CheckPureMethod(Method, SourceRange());
2806
2807 // Propagate access. For a non-friend declaration, the access is
2808 // whatever we're propagating from. For a friend, it should be the
2809 // previous declaration we just found.
2810 if (isFriend && Method->getPreviousDecl())
2811 Method->setAccess(Method->getPreviousDecl()->getAccess());
2812 else
2813 Method->setAccess(D->getAccess());
2814 if (FunctionTemplate)
2815 FunctionTemplate->setAccess(Method->getAccess());
2816
2817 SemaRef.CheckOverrideControl(Method);
2818
2819 // If a function is defined as defaulted or deleted, mark it as such now.
2820 if (D->isExplicitlyDefaulted()) {
2821 if (SubstDefaultedFunction(Method, D))
2822 return nullptr;
2823 }
2824 if (D->isDeletedAsWritten())
2825 SemaRef.SetDeclDeleted(Method, Method->getLocation(),
2826 D->getDeletedMessage());
2827
2828 // If this is an explicit specialization, mark the implicitly-instantiated
2829 // template specialization as being an explicit specialization too.
2830 // FIXME: Is this necessary?
2831 if (IsExplicitSpecialization && !isFriend)
2832 SemaRef.CompleteMemberSpecialization(Method, Previous);
2833
2834 // If the method is a special member function, we need to mark it as
2835 // ineligible so that Owner->addDecl() won't mark the class as non trivial.
2836 // At the end of the class instantiation, we calculate eligibility again and
2837 // then we adjust trivility if needed.
2838 // We need this check to happen only after the method parameters are set,
2839 // because being e.g. a copy constructor depends on the instantiated
2840 // arguments.
2841 if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Method)) {
2842 if (Constructor->isDefaultConstructor() ||
2843 Constructor->isCopyOrMoveConstructor())
2844 Method->setIneligibleOrNotSelected(true);
2845 } else if (Method->isCopyAssignmentOperator() ||
2846 Method->isMoveAssignmentOperator()) {
2847 Method->setIneligibleOrNotSelected(true);
2848 }
2849
2850 // If there's a function template, let our caller handle it.
2851 if (FunctionTemplate) {
2852 // do nothing
2853
2854 // Don't hide a (potentially) valid declaration with an invalid one.
2855 } else if (Method->isInvalidDecl() && !Previous.empty()) {
2856 // do nothing
2857
2858 // Otherwise, check access to friends and make them visible.
2859 } else if (isFriend) {
2860 // We only need to re-check access for methods which we didn't
2861 // manage to match during parsing.
2862 if (!D->getPreviousDecl())
2863 SemaRef.CheckFriendAccess(Method);
2864
2865 Record->makeDeclVisibleInContext(Method);
2866
2867 // Otherwise, add the declaration. We don't need to do this for
2868 // class-scope specializations because we'll have matched them with
2869 // the appropriate template.
2870 } else {
2871 Owner->addDecl(Method);
2872 }
2873
2874 // PR17480: Honor the used attribute to instantiate member function
2875 // definitions
2876 if (Method->hasAttr<UsedAttr>()) {
2877 if (const auto *A = dyn_cast<CXXRecordDecl>(Owner)) {
2879 if (const MemberSpecializationInfo *MSInfo =
2880 A->getMemberSpecializationInfo())
2881 Loc = MSInfo->getPointOfInstantiation();
2882 else if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(A))
2883 Loc = Spec->getPointOfInstantiation();
2884 SemaRef.MarkFunctionReferenced(Loc, Method);
2885 }
2886 }
2887
2888 return Method;
2889}
2890
2891Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
2892 return VisitCXXMethodDecl(D);
2893}
2894
2895Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
2896 return VisitCXXMethodDecl(D);
2897}
2898
2899Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
2900 return VisitCXXMethodDecl(D);
2901}
2902
2903Decl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
2904 return SemaRef.SubstParmVarDecl(D, TemplateArgs, /*indexAdjustment*/ 0,
2905 std::nullopt,
2906 /*ExpectParameterPack=*/false);
2907}
2908
2909Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl(
2911 assert(D->getTypeForDecl()->isTemplateTypeParmType());
2912
2913 std::optional<unsigned> NumExpanded;
2914
2915 if (const TypeConstraint *TC = D->getTypeConstraint()) {
2916 if (D->isPackExpansion() && !D->isExpandedParameterPack()) {
2917 assert(TC->getTemplateArgsAsWritten() &&
2918 "type parameter can only be an expansion when explicit arguments "
2919 "are specified");
2920 // The template type parameter pack's type is a pack expansion of types.
2921 // Determine whether we need to expand this parameter pack into separate
2922 // types.
2924 for (auto &ArgLoc : TC->getTemplateArgsAsWritten()->arguments())
2925 SemaRef.collectUnexpandedParameterPacks(ArgLoc, Unexpanded);
2926
2927 // Determine whether the set of unexpanded parameter packs can and should
2928 // be expanded.
2929 bool Expand = true;
2930 bool RetainExpansion = false;
2932 cast<CXXFoldExpr>(TC->getImmediatelyDeclaredConstraint())
2933 ->getEllipsisLoc(),
2934 SourceRange(TC->getConceptNameLoc(),
2935 TC->hasExplicitTemplateArgs() ?
2936 TC->getTemplateArgsAsWritten()->getRAngleLoc() :
2937 TC->getConceptNameInfo().getEndLoc()),
2938 Unexpanded, TemplateArgs, Expand, RetainExpansion, NumExpanded))
2939 return nullptr;
2940 }
2941 }
2942
2944 SemaRef.Context, Owner, D->getBeginLoc(), D->getLocation(),
2945 D->getDepth() - TemplateArgs.getNumSubstitutedLevels(), D->getIndex(),
2947 D->hasTypeConstraint(), NumExpanded);
2948
2949 Inst->setAccess(AS_public);
2950 Inst->setImplicit(D->isImplicit());
2951 if (auto *TC = D->getTypeConstraint()) {
2952 if (!D->isImplicit()) {
2953 // Invented template parameter type constraints will be instantiated
2954 // with the corresponding auto-typed parameter as it might reference
2955 // other parameters.
2956 if (SemaRef.SubstTypeConstraint(Inst, TC, TemplateArgs,
2957 EvaluateConstraints))
2958 return nullptr;
2959 }
2960 }
2962 TemplateArgumentLoc Output;
2963 if (!SemaRef.SubstTemplateArgument(D->getDefaultArgument(), TemplateArgs,
2964 Output))
2965 Inst->setDefaultArgument(SemaRef.getASTContext(), Output);
2966 }
2967
2968 // Introduce this template parameter's instantiation into the instantiation
2969 // scope.
2971
2972 return Inst;
2973}
2974
2975Decl *TemplateDeclInstantiator::VisitNonTypeTemplateParmDecl(
2977 // Substitute into the type of the non-type template parameter.
2979 SmallVector<TypeSourceInfo *, 4> ExpandedParameterPackTypesAsWritten;
2980 SmallVector<QualType, 4> ExpandedParameterPackTypes;
2981 bool IsExpandedParameterPack = false;
2982 TypeSourceInfo *DI;
2983 QualType T;
2984 bool Invalid = false;
2985
2986 if (D->isExpandedParameterPack()) {
2987 // The non-type template parameter pack is an already-expanded pack
2988 // expansion of types. Substitute into each of the expanded types.
2989 ExpandedParameterPackTypes.reserve(D->getNumExpansionTypes());
2990 ExpandedParameterPackTypesAsWritten.reserve(D->getNumExpansionTypes());
2991 for (unsigned I = 0, N = D->getNumExpansionTypes(); I != N; ++I) {
2992 TypeSourceInfo *NewDI =
2993 SemaRef.SubstType(D->getExpansionTypeSourceInfo(I), TemplateArgs,
2994 D->getLocation(), D->getDeclName());
2995 if (!NewDI)
2996 return nullptr;
2997
2998 QualType NewT =
3000 if (NewT.isNull())
3001 return nullptr;
3002
3003 ExpandedParameterPackTypesAsWritten.push_back(NewDI);
3004 ExpandedParameterPackTypes.push_back(NewT);
3005 }
3006
3007 IsExpandedParameterPack = true;
3008 DI = D->getTypeSourceInfo();
3009 T = DI->getType();
3010 } else if (D->isPackExpansion()) {
3011 // The non-type template parameter pack's type is a pack expansion of types.
3012 // Determine whether we need to expand this parameter pack into separate
3013 // types.
3015 TypeLoc Pattern = Expansion.getPatternLoc();
3017 SemaRef.collectUnexpandedParameterPacks(Pattern, Unexpanded);
3018
3019 // Determine whether the set of unexpanded parameter packs can and should
3020 // be expanded.
3021 bool Expand = true;
3022 bool RetainExpansion = false;
3023 std::optional<unsigned> OrigNumExpansions =
3024 Expansion.getTypePtr()->getNumExpansions();
3025 std::optional<unsigned> NumExpansions = OrigNumExpansions;
3026 if (SemaRef.CheckParameterPacksForExpansion(Expansion.getEllipsisLoc(),
3027 Pattern.getSourceRange(),
3028 Unexpanded,
3029 TemplateArgs,
3030 Expand, RetainExpansion,
3031 NumExpansions))
3032 return nullptr;
3033
3034 if (Expand) {
3035 for (unsigned I = 0; I != *NumExpansions; ++I) {
3036 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
3037 TypeSourceInfo *NewDI = SemaRef.SubstType(Pattern, TemplateArgs,
3038 D->getLocation(),
3039 D->getDeclName());
3040 if (!NewDI)
3041 return nullptr;
3042
3043 QualType NewT =
3045 if (NewT.isNull())
3046 return nullptr;
3047
3048 ExpandedParameterPackTypesAsWritten.push_back(NewDI);
3049 ExpandedParameterPackTypes.push_back(NewT);
3050 }
3051
3052 // Note that we have an expanded parameter pack. The "type" of this
3053 // expanded parameter pack is the original expansion type, but callers
3054 // will end up using the expanded parameter pack types for type-checking.
3055 IsExpandedParameterPack = true;
3056 DI = D->getTypeSourceInfo();
3057 T = DI->getType();
3058 } else {
3059 // We cannot fully expand the pack expansion now, so substitute into the
3060 // pattern and create a new pack expansion type.
3061 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
3062 TypeSourceInfo *NewPattern = SemaRef.SubstType(Pattern, TemplateArgs,
3063 D->getLocation(),
3064 D->getDeclName());
3065 if (!NewPattern)
3066 return nullptr;
3067
3068 SemaRef.CheckNonTypeTemplateParameterType(NewPattern, D->getLocation());
3069 DI = SemaRef.CheckPackExpansion(NewPattern, Expansion.getEllipsisLoc(),
3070 NumExpansions);
3071 if (!DI)
3072 return nullptr;
3073
3074 T = DI->getType();
3075 }
3076 } else {
3077 // Simple case: substitution into a parameter that is not a parameter pack.
3078 DI = SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs,
3079 D->getLocation(), D->getDeclName());
3080 if (!DI)
3081 return nullptr;
3082
3083 // Check that this type is acceptable for a non-type template parameter.
3085 if (T.isNull()) {
3086 T = SemaRef.Context.IntTy;
3087 Invalid = true;
3088 }
3089 }
3090
3092 if (IsExpandedParameterPack)
3094 SemaRef.Context, Owner, D->getInnerLocStart(), D->getLocation(),
3095 D->getDepth() - TemplateArgs.getNumSubstitutedLevels(),
3096 D->getPosition(), D->getIdentifier(), T, DI, ExpandedParameterPackTypes,
3097 ExpandedParameterPackTypesAsWritten);
3098 else
3100 SemaRef.Context, Owner, D->getInnerLocStart(), D->getLocation(),
3101 D->getDepth() - TemplateArgs.getNumSubstitutedLevels(),
3102 D->getPosition(), D->getIdentifier(), T, D->isParameterPack(), DI);
3103
3104 if (AutoTypeLoc AutoLoc = DI->getTypeLoc().getContainedAutoTypeLoc())
3105 if (AutoLoc.isConstrained()) {
3106 SourceLocation EllipsisLoc;
3107 if (IsExpandedParameterPack)
3108 EllipsisLoc =
3109 DI->getTypeLoc().getAs<PackExpansionTypeLoc>().getEllipsisLoc();
3110 else if (auto *Constraint = dyn_cast_if_present<CXXFoldExpr>(
3112 EllipsisLoc = Constraint->getEllipsisLoc();
3113 // Note: We attach the uninstantiated constriant here, so that it can be
3114 // instantiated relative to the top level, like all our other
3115 // constraints.
3116 if (SemaRef.AttachTypeConstraint(AutoLoc, /*NewConstrainedParm=*/Param,
3117 /*OrigConstrainedParm=*/D, EllipsisLoc))
3118 Invalid = true;
3119 }
3120
3121 Param->setAccess(AS_public);
3122 Param->setImplicit(D->isImplicit());
3123 if (Invalid)
3124 Param->setInvalidDecl();
3125
3127 EnterExpressionEvaluationContext ConstantEvaluated(
3130 if (!SemaRef.SubstTemplateArgument(D->getDefaultArgument(), TemplateArgs,
3131 Result))
3132 Param->setDefaultArgument(SemaRef.Context, Result);
3133 }
3134
3135 // Introduce this template parameter's instantiation into the instantiation
3136 // scope.
3138 return Param;
3139}
3140
3142 Sema &S,
3143 TemplateParameterList *Params,
3145 for (const auto &P : *Params) {
3146 if (P->isTemplateParameterPack())
3147 continue;
3148 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P))
3149 S.collectUnexpandedParameterPacks(NTTP->getTypeSourceInfo()->getTypeLoc(),
3150 Unexpanded);
3151 if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(P))
3152 collectUnexpandedParameterPacks(S, TTP->getTemplateParameters(),
3153 Unexpanded);
3154 }
3155}
3156
3157Decl *
3158TemplateDeclInstantiator::VisitTemplateTemplateParmDecl(
3160 // Instantiate the template parameter list of the template template parameter.
3162 TemplateParameterList *InstParams;
3164
3165 bool IsExpandedParameterPack = false;
3166
3167 if (D->isExpandedParameterPack()) {
3168 // The template template parameter pack is an already-expanded pack
3169 // expansion of template parameters. Substitute into each of the expanded
3170 // parameters.
3171 ExpandedParams.reserve(D->getNumExpansionTemplateParameters());
3172 for (unsigned I = 0, N = D->getNumExpansionTemplateParameters();
3173 I != N; ++I) {
3175 TemplateParameterList *Expansion =
3177 if (!Expansion)
3178 return nullptr;
3179 ExpandedParams.push_back(Expansion);
3180 }
3181
3182 IsExpandedParameterPack = true;
3183 InstParams = TempParams;
3184 } else if (D->isPackExpansion()) {
3185 // The template template parameter pack expands to a pack of template
3186 // template parameters. Determine whether we need to expand this parameter
3187 // pack into separate parameters.
3190 Unexpanded);
3191
3192 // Determine whether the set of unexpanded parameter packs can and should
3193 // be expanded.
3194 bool Expand = true;
3195 bool RetainExpansion = false;
3196 std::optional<unsigned> NumExpansions;
3198 TempParams->getSourceRange(),
3199 Unexpanded,
3200 TemplateArgs,
3201 Expand, RetainExpansion,
3202 NumExpansions))
3203 return nullptr;
3204
3205 if (Expand) {
3206 for (unsigned I = 0; I != *NumExpansions; ++I) {
3207 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
3209 TemplateParameterList *Expansion = SubstTemplateParams(TempParams);
3210 if (!Expansion)
3211 return nullptr;
3212 ExpandedParams.push_back(Expansion);
3213 }
3214
3215 // Note that we have an expanded parameter pack. The "type" of this
3216 // expanded parameter pack is the original expansion type, but callers
3217 // will end up using the expanded parameter pack types for type-checking.
3218 IsExpandedParameterPack = true;
3219 InstParams = TempParams;
3220 } else {
3221 // We cannot fully expand the pack expansion now, so just substitute
3222 // into the pattern.
3223 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
3224
3226 InstParams = SubstTemplateParams(TempParams);
3227 if (!InstParams)
3228 return nullptr;
3229 }
3230 } else {
3231 // Perform the actual substitution of template parameters within a new,
3232 // local instantiation scope.
3234 InstParams = SubstTemplateParams(TempParams);
3235 if (!InstParams)
3236 return nullptr;
3237 }
3238
3239 // Build the template template parameter.
3241 if (IsExpandedParameterPack)
3243 SemaRef.Context, Owner, D->getLocation(),
3244 D->getDepth() - TemplateArgs.getNumSubstitutedLevels(),
3246 InstParams, ExpandedParams);
3247 else
3249 SemaRef.Context, Owner, D->getLocation(),
3250 D->getDepth() - TemplateArgs.getNumSubstitutedLevels(),
3251 D->getPosition(), D->isParameterPack(), D->getIdentifier(),
3252 D->wasDeclaredWithTypename(), InstParams);
3254 NestedNameSpecifierLoc QualifierLoc =
3256 QualifierLoc =
3257 SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgs);
3258 TemplateName TName = SemaRef.SubstTemplateName(
3259 QualifierLoc, D->getDefaultArgument().getArgument().getAsTemplate(),
3260 D->getDefaultArgument().getTemplateNameLoc(), TemplateArgs);
3261 if (!TName.isNull())
3262 Param->setDefaultArgument(
3263 SemaRef.Context,
3267 }
3268 Param->setAccess(AS_public);
3269 Param->setImplicit(D->isImplicit());
3270
3271 // Introduce this template parameter's instantiation into the instantiation
3272 // scope.
3274
3275 return Param;
3276}
3277
3278Decl *TemplateDeclInstantiator::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
3279 // Using directives are never dependent (and never contain any types or
3280 // expressions), so they require no explicit instantiation work.
3281
3282 UsingDirectiveDecl *Inst
3283 = UsingDirectiveDecl::Create(SemaRef.Context, Owner, D->getLocation(),
3285 D->getQualifierLoc(),
3286 D->getIdentLocation(),
3288 D->getCommonAncestor());
3289
3290 // Add the using directive to its declaration context
3291 // only if this is not a function or method.
3292 if (!Owner->isFunctionOrMethod())
3293 Owner->addDecl(Inst);
3294
3295 return Inst;
3296}
3297
3299 BaseUsingDecl *Inst,
3300 LookupResult *Lookup) {
3301
3302 bool isFunctionScope = Owner->isFunctionOrMethod();
3303
3304 for (auto *Shadow : D->shadows()) {
3305 // FIXME: UsingShadowDecl doesn't preserve its immediate target, so
3306 // reconstruct it in the case where it matters. Hm, can we extract it from
3307 // the DeclSpec when parsing and save it in the UsingDecl itself?
3308 NamedDecl *OldTarget = Shadow->getTargetDecl();
3309 if (auto *CUSD = dyn_cast<ConstructorUsingShadowDecl>(Shadow))
3310 if (auto *BaseShadow = CUSD->getNominatedBaseClassShadowDecl())
3311 OldTarget = BaseShadow;
3312
3313 NamedDecl *InstTarget = nullptr;
3314 if (auto *EmptyD =
3315 dyn_cast<UnresolvedUsingIfExistsDecl>(Shadow->getTargetDecl())) {
3317 SemaRef.Context, Owner, EmptyD->getLocation(), EmptyD->getDeclName());
3318 } else {
3319 InstTarget = cast_or_null<NamedDecl>(SemaRef.FindInstantiatedDecl(
3320 Shadow->getLocation(), OldTarget, TemplateArgs));
3321 }
3322 if (!InstTarget)
3323 return nullptr;
3324
3325 UsingShadowDecl *PrevDecl = nullptr;
3326 if (Lookup &&
3327 SemaRef.CheckUsingShadowDecl(Inst, InstTarget, *Lookup, PrevDecl))
3328 continue;
3329
3330 if (UsingShadowDecl *OldPrev = getPreviousDeclForInstantiation(Shadow))
3331 PrevDecl = cast_or_null<UsingShadowDecl>(SemaRef.FindInstantiatedDecl(
3332 Shadow->getLocation(), OldPrev, TemplateArgs));
3333
3334 UsingShadowDecl *InstShadow = SemaRef.BuildUsingShadowDecl(
3335 /*Scope*/ nullptr, Inst, InstTarget, PrevDecl);
3336 SemaRef.Context.setInstantiatedFromUsingShadowDecl(InstShadow, Shadow);
3337
3338 if (isFunctionScope)
3339 SemaRef.CurrentInstantiationScope->InstantiatedLocal(Shadow, InstShadow);
3340 }
3341
3342 return Inst;
3343}
3344
3345Decl *TemplateDeclInstantiator::VisitUsingDecl(UsingDecl *D) {
3346
3347 // The nested name specifier may be dependent, for example
3348 // template <typename T> struct t {
3349 // struct s1 { T f1(); };
3350 // struct s2 : s1 { using s1::f1; };
3351 // };
3352 // template struct t<int>;
3353 // Here, in using s1::f1, s1 refers to t<T>::s1;
3354 // we need to substitute for t<int>::s1.
3355 NestedNameSpecifierLoc QualifierLoc
3357 TemplateArgs);
3358 if (!QualifierLoc)
3359 return nullptr;
3360
3361 // For an inheriting constructor declaration, the name of the using
3362 // declaration is the name of a constructor in this class, not in the
3363 // base class.
3364 DeclarationNameInfo NameInfo = D->getNameInfo();
3366 if (auto *RD = dyn_cast<CXXRecordDecl>(SemaRef.CurContext))
3368 SemaRef.Context.getCanonicalType(SemaRef.Context.getRecordType(RD))));
3369
3370 // We only need to do redeclaration lookups if we're in a class scope (in
3371 // fact, it's not really even possible in non-class scopes).
3372 bool CheckRedeclaration = Owner->isRecord();
3373 LookupResult Prev(SemaRef, NameInfo, Sema::LookupUsingDeclName,
3374 RedeclarationKind::ForVisibleRedeclaration);
3375
3376 UsingDecl *NewUD = UsingDecl::Create(SemaRef.Context, Owner,
3377 D->getUsingLoc(),
3378 QualifierLoc,
3379 NameInfo,
3380 D->hasTypename());
3381
3382 CXXScopeSpec SS;
3383 SS.Adopt(QualifierLoc);
3384 if (CheckRedeclaration) {
3385 Prev.setHideTags(false);
3386 SemaRef.LookupQualifiedName(Prev, Owner);
3387
3388 // Check for invalid redeclarations.
3390 D->hasTypename(), SS,
3391 D->getLocation(), Prev))
3392 NewUD->setInvalidDecl();
3393 }
3394
3395 if (!NewUD->isInvalidDecl() &&
3396 SemaRef.CheckUsingDeclQualifier(D->getUsingLoc(), D->hasTypename(), SS,
3397 NameInfo, D->getLocation(), nullptr, D))
3398 NewUD->setInvalidDecl();
3399
3400 SemaRef.Context.setInstantiatedFromUsingDecl(NewUD, D);
3401 NewUD->setAccess(D->getAccess());
3402 Owner->addDecl(NewUD);
3403
3404 // Don't process the shadow decls for an invalid decl.
3405 if (NewUD->isInvalidDecl())
3406 return NewUD;
3407
3408 // If the using scope was dependent, or we had dependent bases, we need to
3409 // recheck the inheritance
3412
3413 return VisitBaseUsingDecls(D, NewUD, CheckRedeclaration ? &Prev : nullptr);
3414}
3415
3416Decl *TemplateDeclInstantiator::VisitUsingEnumDecl(UsingEnumDecl *D) {
3417 // Cannot be a dependent type, but still could be an instantiation
3418 EnumDecl *EnumD = cast_or_null<EnumDecl>(SemaRef.FindInstantiatedDecl(
3419 D->getLocation(), D->getEnumDecl(), TemplateArgs));
3420
3421 if (SemaRef.RequireCompleteEnumDecl(EnumD, EnumD->getLocation()))
3422 return nullptr;
3423
3424 TypeSourceInfo *TSI = SemaRef.SubstType(D->getEnumType(), TemplateArgs,
3425 D->getLocation(), D->getDeclName());
3426 UsingEnumDecl *NewUD =
3427 UsingEnumDecl::Create(SemaRef.Context, Owner, D->getUsingLoc(),
3428 D->getEnumLoc(), D->getLocation(), TSI);
3429
3430 SemaRef.Context.setInstantiatedFromUsingEnumDecl(NewUD, D);
3431 NewUD->setAccess(D->getAccess());
3432 Owner->addDecl(NewUD);
3433
3434 // Don't process the shadow decls for an invalid decl.
3435 if (NewUD->isInvalidDecl())
3436 return NewUD;
3437
3438 // We don't have to recheck for duplication of the UsingEnumDecl itself, as it
3439 // cannot be dependent, and will therefore have been checked during template
3440 // definition.
3441
3442 return VisitBaseUsingDecls(D, NewUD, nullptr);
3443}
3444
3445Decl *TemplateDeclInstantiator::VisitUsingShadowDecl(UsingShadowDecl *D) {
3446 // Ignore these; we handle them in bulk when processing the UsingDecl.
3447 return nullptr;
3448}
3449
3450Decl *TemplateDeclInstantiator::VisitConstructorUsingShadowDecl(
3452 // Ignore these; we handle them in bulk when processing the UsingDecl.
3453 return nullptr;
3454}
3455
3456template <typename T>
3457Decl *TemplateDeclInstantiator::instantiateUnresolvedUsingDecl(
3458 T *D, bool InstantiatingPackElement) {
3459 // If this is a pack expansion, expand it now.
3460 if (D->isPackExpansion() && !InstantiatingPackElement) {
3462 SemaRef.collectUnexpandedParameterPacks(D->getQualifierLoc(), Unexpanded);
3463 SemaRef.collectUnexpandedParameterPacks(D->getNameInfo(), Unexpanded);
3464
3465 // Determine whether the set of unexpanded parameter packs can and should
3466 // be expanded.
3467 bool Expand = true;
3468 bool RetainExpansion = false;
3469 std::optional<unsigned> NumExpansions;
3471 D->getEllipsisLoc(), D->getSourceRange(), Unexpanded, TemplateArgs,
3472 Expand, RetainExpansion, NumExpansions))
3473 return nullptr;
3474
3475 // This declaration cannot appear within a function template signature,
3476 // so we can't have a partial argument list for a parameter pack.
3477 assert(!RetainExpansion &&
3478 "should never need to retain an expansion for UsingPackDecl");
3479
3480 if (!Expand) {
3481 // We cannot fully expand the pack expansion now, so substitute into the
3482 // pattern and create a new pack expansion.
3483 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
3484 return instantiateUnresolvedUsingDecl(D, true);
3485 }
3486
3487 // Within a function, we don't have any normal way to check for conflicts
3488 // between shadow declarations from different using declarations in the
3489 // same pack expansion, but this is always ill-formed because all expansions
3490 // must produce (conflicting) enumerators.
3491 //
3492 // Sadly we can't just reject this in the template definition because it
3493 // could be valid if the pack is empty or has exactly one expansion.
3494 if (D->getDeclContext()->isFunctionOrMethod() && *NumExpansions > 1) {
3495 SemaRef.Diag(D->getEllipsisLoc(),
3496 diag::err_using_decl_redeclaration_expansion);
3497 return nullptr;
3498 }
3499
3500 // Instantiate the slices of this pack and build a UsingPackDecl.
3501 SmallVector<NamedDecl*, 8> Expansions;
3502 for (unsigned I = 0; I != *NumExpansions; ++I) {
3503 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
3504 Decl *Slice = instantiateUnresolvedUsingDecl(D, true);
3505 if (!Slice)
3506 return nullptr;
3507 // Note that we can still get unresolved using declarations here, if we
3508 // had arguments for all packs but the pattern also contained other
3509 // template arguments (this only happens during partial substitution, eg
3510 // into the body of a generic lambda in a function template).
3511 Expansions.push_back(cast<NamedDecl>(Slice));
3512 }
3513
3514 auto *NewD = SemaRef.BuildUsingPackDecl(D, Expansions);
3515 if (isDeclWithinFunction(D))
3517 return NewD;
3518 }
3519
3520 UnresolvedUsingTypenameDecl *TD = dyn_cast<UnresolvedUsingTypenameDecl>(D);
3521 SourceLocation TypenameLoc = TD ? TD->getTypenameLoc() : SourceLocation();
3522
3523 NestedNameSpecifierLoc QualifierLoc
3524 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
3525 TemplateArgs);
3526 if (!QualifierLoc)
3527 return nullptr;
3528
3529 CXXScopeSpec SS;
3530 SS.Adopt(QualifierLoc);
3531
3532 DeclarationNameInfo NameInfo
3533 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
3534
3535 // Produce a pack expansion only if we're not instantiating a particular
3536 // slice of a pack expansion.
3537 bool InstantiatingSlice = D->getEllipsisLoc().isValid() &&
3538 SemaRef.ArgumentPackSubstitutionIndex != -1;
3539 SourceLocation EllipsisLoc =
3540 InstantiatingSlice ? SourceLocation() : D->getEllipsisLoc();
3541
3542 bool IsUsingIfExists = D->template hasAttr<UsingIfExistsAttr>();
3543 NamedDecl *UD = SemaRef.BuildUsingDeclaration(
3544 /*Scope*/ nullptr, D->getAccess(), D->getUsingLoc(),
3545 /*HasTypename*/ TD, TypenameLoc, SS, NameInfo, EllipsisLoc,
3547 /*IsInstantiation*/ true, IsUsingIfExists);
3548 if (UD) {
3549 SemaRef.InstantiateAttrs(TemplateArgs, D, UD);
3551 }
3552
3553 return UD;
3554}
3555
3556Decl *TemplateDeclInstantiator::VisitUnresolvedUsingTypenameDecl(
3558 return instantiateUnresolvedUsingDecl(D);
3559}
3560
3561Decl *TemplateDeclInstantiator::VisitUnresolvedUsingValueDecl(
3563 return instantiateUnresolvedUsingDecl(D);
3564}
3565
3566Decl *TemplateDeclInstantiator::VisitUnresolvedUsingIfExistsDecl(
3568 llvm_unreachable("referring to unresolved decl out of UsingShadowDecl");
3569}
3570
3571Decl *TemplateDeclInstantiator::VisitUsingPackDecl(UsingPackDecl *D) {
3572 SmallVector<NamedDecl*, 8> Expansions;
3573 for (auto *UD : D->expansions()) {
3574 if (NamedDecl *NewUD =
3575 SemaRef.FindInstantiatedDecl(D->getLocation(), UD, TemplateArgs))
3576 Expansions.push_back(NewUD);
3577 else
3578 return nullptr;
3579 }
3580
3581 auto *NewD = SemaRef.BuildUsingPackDecl(D, Expansions);
3582 if (isDeclWithinFunction(D))
3584 return NewD;
3585}
3586
3587Decl *TemplateDeclInstantiator::VisitOMPThreadPrivateDecl(
3590 for (auto *I : D->varlists()) {
3591 Expr *Var = SemaRef.SubstExpr(I, TemplateArgs).get();
3592 assert(isa<DeclRefExpr>(Var) && "threadprivate arg is not a DeclRefExpr");
3593 Vars.push_back(Var);
3594 }
3595
3597 SemaRef.OpenMP().CheckOMPThreadPrivateDecl(D->getLocation(), Vars);
3598
3599 TD->setAccess(AS_public);
3600 Owner->addDecl(TD);
3601
3602 return TD;
3603}
3604
3605Decl *TemplateDeclInstantiator::VisitOMPAllocateDecl(OMPAllocateDecl *D) {
3607 for (auto *I : D->varlists()) {
3608 Expr *Var = SemaRef.SubstExpr(I, TemplateArgs).get();
3609 assert(isa<DeclRefExpr>(Var) && "allocate arg is not a DeclRefExpr");
3610 Vars.push_back(Var);
3611 }
3613 // Copy map clauses from the original mapper.
3614 for (OMPClause *C : D->clauselists()) {
3615 OMPClause *IC = nullptr;
3616 if (auto *AC = dyn_cast<OMPAllocatorClause>(C)) {
3617 ExprResult NewE = SemaRef.SubstExpr(AC->getAllocator(), TemplateArgs);
3618 if (!NewE.isUsable())
3619 continue;
3620 IC = SemaRef.OpenMP().ActOnOpenMPAllocatorClause(
3621 NewE.get(), AC->getBeginLoc(), AC->getLParenLoc(), AC->getEndLoc());
3622 } else if (auto *AC = dyn_cast<OMPAlignClause>(C)) {
3623 ExprResult NewE = SemaRef.SubstExpr(AC->getAlignment(), TemplateArgs);
3624 if (!NewE.isUsable())
3625 continue;
3626 IC = SemaRef.OpenMP().ActOnOpenMPAlignClause(
3627 NewE.get(), AC->getBeginLoc(), AC->getLParenLoc(), AC->getEndLoc());
3628 // If align clause value ends up being invalid, this can end up null.
3629 if (!IC)
3630 continue;
3631 }
3632 Clauses.push_back(IC);
3633 }
3634
3636 D->getLocation(), Vars, Clauses, Owner);
3637 if (Res.get().isNull())
3638 return nullptr;
3639 return Res.get().getSingleDecl();
3640}
3641
3642Decl *TemplateDeclInstantiator::VisitOMPRequiresDecl(OMPRequiresDecl *D) {
3643 llvm_unreachable(
3644 "Requires directive cannot be instantiated within a dependent context");
3645}
3646
3647Decl *TemplateDeclInstantiator::VisitOMPDeclareReductionDecl(
3649 // Instantiate type and check if it is allowed.
3650 const bool RequiresInstantiation =
3651 D->getType()->isDependentType() ||
3654 QualType SubstReductionType;
3655 if (RequiresInstantiation) {
3656 SubstReductionType = SemaRef.OpenMP().ActOnOpenMPDeclareReductionType(
3657 D->getLocation(),
3659 D->getType(), TemplateArgs, D->getLocation(), DeclarationName())));
3660 } else {
3661 SubstReductionType = D->getType();
3662 }
3663 if (SubstReductionType.isNull())
3664 return nullptr;
3665 Expr *Combiner = D->getCombiner();
3666 Expr *Init = D->getInitializer();
3667 bool IsCorrect = true;
3668 // Create instantiated copy.
3669 std::pair<QualType, SourceLocation> ReductionTypes[] = {
3670 std::make_pair(SubstReductionType, D->getLocation())};
3671 auto *PrevDeclInScope = D->getPrevDeclInScope();
3672 if (PrevDeclInScope && !PrevDeclInScope->isInvalidDecl()) {
3673 PrevDeclInScope = cast<OMPDeclareReductionDecl>(
3674 SemaRef.CurrentInstantiationScope->findInstantiationOf(PrevDeclInScope)
3675 ->get<Decl *>());
3676 }
3678 /*S=*/nullptr, Owner, D->getDeclName(), ReductionTypes, D->getAccess(),
3679 PrevDeclInScope);
3680 auto *NewDRD = cast<OMPDeclareReductionDecl>(DRD.get().getSingleDecl());
3681 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewDRD);
3682 Expr *SubstCombiner = nullptr;
3683 Expr *SubstInitializer = nullptr;
3684 // Combiners instantiation sequence.
3685 if (Combiner) {
3687 /*S=*/nullptr, NewDRD);
3689 cast<DeclRefExpr>(D->getCombinerIn())->getDecl(),
3690 cast<DeclRefExpr>(NewDRD->getCombinerIn())->getDecl());
3692 cast<DeclRefExpr>(D->getCombinerOut())->getDecl(),
3693 cast<DeclRefExpr>(NewDRD->getCombinerOut())->getDecl());
3694 auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(Owner);
3695 Sema::CXXThisScopeRAII ThisScope(SemaRef, ThisContext, Qualifiers(),
3696 ThisContext);
3697 SubstCombiner = SemaRef.SubstExpr(Combiner, TemplateArgs).get();
3699 SubstCombiner);
3700 }
3701 // Initializers instantiation sequence.
3702 if (Init) {
3703 VarDecl *OmpPrivParm =
3705 /*S=*/nullptr, NewDRD);
3707 cast<DeclRefExpr>(D->getInitOrig())->getDecl(),
3708 cast<DeclRefExpr>(NewDRD->getInitOrig())->getDecl());
3710 cast<DeclRefExpr>(D->getInitPriv())->getDecl(),
3711 cast<DeclRefExpr>(NewDRD->getInitPriv())->getDecl());
3713 SubstInitializer = SemaRef.SubstExpr(Init, TemplateArgs).get();
3714 } else {
3715 auto *OldPrivParm =
3716 cast<VarDecl>(cast<DeclRefExpr>(D->getInitPriv())->getDecl());
3717 IsCorrect = IsCorrect && OldPrivParm->hasInit();
3718 if (IsCorrect)
3719 SemaRef.InstantiateVariableInitializer(OmpPrivParm, OldPrivParm,
3720 TemplateArgs);
3721 }
3723 NewDRD, SubstInitializer, OmpPrivParm);
3724 }
3725 IsCorrect = IsCorrect && SubstCombiner &&
3726 (!Init ||
3728 SubstInitializer) ||
3730 !SubstInitializer));
3731
3733 /*S=*/nullptr, DRD, IsCorrect && !D->isInvalidDecl());
3734
3735 return NewDRD;
3736}
3737
3738Decl *
3739TemplateDeclInstantiator::VisitOMPDeclareMapperDecl(OMPDeclareMapperDecl *D) {
3740 // Instantiate type and check if it is allowed.
3741 const bool RequiresInstantiation =
3742 D->getType()->isDependentType() ||
3745 QualType SubstMapperTy;
3746 DeclarationName VN = D->getVarName();
3747 if (RequiresInstantiation) {
3748 SubstMapperTy = SemaRef.OpenMP().ActOnOpenMPDeclareMapperType(
3749 D->getLocation(),
3750 ParsedType::make(SemaRef.SubstType(D->getType(), TemplateArgs,
3751 D->getLocation(), VN)));
3752 } else {
3753 SubstMapperTy = D->getType();
3754 }
3755 if (SubstMapperTy.isNull())
3756 return nullptr;
3757 // Create an instantiated copy of mapper.
3758 auto *PrevDeclInScope = D->getPrevDeclInScope();
3759 if (PrevDeclInScope && !PrevDeclInScope->isInvalidDecl()) {
3760 PrevDeclInScope = cast<OMPDeclareMapperDecl>(
3761 SemaRef.CurrentInstantiationScope->findInstantiationOf(PrevDeclInScope)
3762 ->get<Decl *>());
3763 }
3764 bool IsCorrect = true;
3766 // Instantiate the mapper variable.
3767 DeclarationNameInfo DirName;
3768 SemaRef.OpenMP().StartOpenMPDSABlock(llvm::omp::OMPD_declare_mapper, DirName,
3769 /*S=*/nullptr,
3770 (*D->clauselist_begin())->getBeginLoc());
3771 ExprResult MapperVarRef =
3773 /*S=*/nullptr, SubstMapperTy, D->getLocation(), VN);
3775 cast<DeclRefExpr>(D->getMapperVarRef())->getDecl(),
3776 cast<DeclRefExpr>(MapperVarRef.get())->getDecl());
3777 auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(Owner);
3778 Sema::CXXThisScopeRAII ThisScope(SemaRef, ThisContext, Qualifiers(),
3779 ThisContext);
3780 // Instantiate map clauses.
3781 for (OMPClause *C : D->clauselists()) {
3782 auto *OldC = cast<OMPMapClause>(C);
3783 SmallVector<Expr *, 4> NewVars;
3784 for (Expr *OE : OldC->varlists()) {
3785 Expr *NE = SemaRef.SubstExpr(OE, TemplateArgs).get();
3786 if (!NE) {
3787 IsCorrect = false;
3788 break;
3789 }
3790 NewVars.push_back(NE);
3791 }
3792 if (!IsCorrect)
3793 break;
3794 NestedNameSpecifierLoc NewQualifierLoc =
3795 SemaRef.SubstNestedNameSpecifierLoc(OldC->getMapperQualifierLoc(),
3796 TemplateArgs);
3797 CXXScopeSpec SS;
3798 SS.Adopt(NewQualifierLoc);
3799 DeclarationNameInfo NewNameInfo =
3800 SemaRef.SubstDeclarationNameInfo(OldC->getMapperIdInfo(), TemplateArgs);
3801 OMPVarListLocTy Locs(OldC->getBeginLoc(), OldC->getLParenLoc(),
3802 OldC->getEndLoc());
3803 OMPClause *NewC = SemaRef.OpenMP().ActOnOpenMPMapClause(
3804 OldC->getIteratorModifier(), OldC->getMapTypeModifiers(),
3805 OldC->getMapTypeModifiersLoc(), SS, NewNameInfo, OldC->getMapType(),
3806 OldC->isImplicitMapType(), OldC->getMapLoc(), OldC->getColonLoc(),
3807 NewVars, Locs);
3808 Clauses.push_back(NewC);
3809 }
3810 SemaRef.OpenMP().EndOpenMPDSABlock(nullptr);
3811 if (!IsCorrect)
3812 return nullptr;
3814 /*S=*/nullptr, Owner, D->getDeclName(), SubstMapperTy, D->getLocation(),
3815 VN, D->getAccess(), MapperVarRef.get(), Clauses, PrevDeclInScope);
3816 Decl *NewDMD = DG.get().getSingleDecl();
3817 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewDMD);
3818 return NewDMD;
3819}
3820
3821Decl *TemplateDeclInstantiator::VisitOMPCapturedExprDecl(
3822 OMPCapturedExprDecl * /*D*/) {
3823 llvm_unreachable("Should not be met in templates");
3824}
3825
3827 return VisitFunctionDecl(D, nullptr);
3828}
3829
3830Decl *
3831TemplateDeclInstantiator::VisitCXXDeductionGuideDecl(CXXDeductionGuideDecl *D) {
3832 Decl *Inst = VisitFunctionDecl(D, nullptr);
3833 if (Inst && !D->getDescribedFunctionTemplate())
3834 Owner->addDecl(Inst);
3835 return Inst;
3836}
3837
3839 return VisitCXXMethodDecl(D, nullptr);
3840}
3841
3842Decl *TemplateDeclInstantiator::VisitRecordDecl(RecordDecl *D) {
3843 llvm_unreachable("There are only CXXRecordDecls in C++");
3844}
3845
3846Decl *
3847TemplateDeclInstantiator::VisitClassTemplateSpecializationDecl(
3849 // As a MS extension, we permit class-scope explicit specialization
3850 // of member class templates.
3851 ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
3852 assert(ClassTemplate->getDeclContext()->isRecord() &&
3854 "can only instantiate an explicit specialization "
3855 "for a member class template");
3856
3857 // Lookup the already-instantiated declaration in the instantiation
3858 // of the class template.
3859 ClassTemplateDecl *InstClassTemplate =
3860 cast_or_null<ClassTemplateDecl>(SemaRef.FindInstantiatedDecl(
3861 D->getLocation(), ClassTemplate, TemplateArgs));
3862 if (!InstClassTemplate)
3863 return nullptr;
3864
3865 // Substitute into the template arguments of the class template explicit
3866 // specialization.
3867 TemplateArgumentListInfo InstTemplateArgs;
3868 if (const ASTTemplateArgumentListInfo *TemplateArgsInfo =
3870 InstTemplateArgs.setLAngleLoc(TemplateArgsInfo->getLAngleLoc());
3871 InstTemplateArgs.setRAngleLoc(TemplateArgsInfo->getRAngleLoc());
3872
3873 if (SemaRef.SubstTemplateArguments(TemplateArgsInfo->arguments(),
3874 TemplateArgs, InstTemplateArgs))
3875 return nullptr;
3876 }
3877
3878 // Check that the template argument list is well-formed for this
3879 // class template.
3880 SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
3881 if (SemaRef.CheckTemplateArgumentList(InstClassTemplate, D->getLocation(),
3882 InstTemplateArgs, false,
3883 SugaredConverted, CanonicalConverted,
3884 /*UpdateArgsWithConversions=*/true))
3885 return nullptr;
3886
3887 // Figure out where to insert this class template explicit specialization
3888 // in the member template's set of class template explicit specializations.
3889 void *InsertPos = nullptr;
3891 InstClassTemplate->findSpecialization(CanonicalConverted, InsertPos);
3892
3893 // Check whether we've already seen a conflicting instantiation of this
3894 // declaration (for instance, if there was a prior implicit instantiation).
3895 bool Ignored;
3896 if (PrevDecl &&
3899 PrevDecl,
3900 PrevDecl->getSpecializationKind(),
3901 PrevDecl->getPointOfInstantiation(),
3902 Ignored))
3903 return nullptr;
3904
3905 // If PrevDecl was a definition and D is also a definition, diagnose.
3906 // This happens in cases like:
3907 //
3908 // template<typename T, typename U>
3909 // struct Outer {
3910 // template<typename X> struct Inner;
3911 // template<> struct Inner<T> {};
3912 // template<> struct Inner<U> {};
3913 // };
3914 //
3915 // Outer<int, int> outer; // error: the explicit specializations of Inner
3916 // // have the same signature.
3917 if (PrevDecl && PrevDecl->getDefinition() &&
3919 SemaRef.Diag(D->getLocation(), diag::err_redefinition) << PrevDecl;
3920 SemaRef.Diag(PrevDecl->getDefinition()->getLocation(),
3921 diag::note_previous_definition);
3922 return nullptr;
3923 }
3924
3925 // Create the class template partial specialization declaration.
3928 SemaRef.Context, D->getTagKind(), Owner, D->getBeginLoc(),
3929 D->getLocation(), InstClassTemplate, CanonicalConverted, PrevDecl);
3930 InstD->setTemplateArgsAsWritten(InstTemplateArgs);
3931
3932 // Add this partial specialization to the set of class template partial
3933 // specializations.
3934 if (!PrevDecl)
3935 InstClassTemplate->AddSpecialization(InstD, InsertPos);
3936
3937 // Substitute the nested name specifier, if any.
3938 if (SubstQualifier(D, InstD))
3939 return nullptr;
3940
3941 InstD->setAccess(D->getAccess());
3946
3947 Owner->addDecl(InstD);
3948
3949 // Instantiate the members of the class-scope explicit specialization eagerly.
3950 // We don't have support for lazy instantiation of an explicit specialization
3951 // yet, and MSVC eagerly instantiates in this case.
3952 // FIXME: This is wrong in standard C++.
3954 SemaRef.InstantiateClass(D->getLocation(), InstD, D, TemplateArgs,
3956 /*Complain=*/true))
3957 return nullptr;
3958
3959 return InstD;
3960}
3961
3964
3965 TemplateArgumentListInfo VarTemplateArgsInfo;
3966 VarTemplateDecl *VarTemplate = D->getSpecializedTemplate();
3967 assert(VarTemplate &&
3968 "A template specialization without specialized template?");
3969
3970 VarTemplateDecl *InstVarTemplate =
3971 cast_or_null<VarTemplateDecl>(SemaRef.FindInstantiatedDecl(
3972 D->getLocation(), VarTemplate, TemplateArgs));
3973 if (!InstVarTemplate)
3974 return nullptr;
3975
3976 // Substitute the current template arguments.
3977 if (const ASTTemplateArgumentListInfo *TemplateArgsInfo =
3979 VarTemplateArgsInfo.setLAngleLoc(TemplateArgsInfo->getLAngleLoc());
3980 VarTemplateArgsInfo.setRAngleLoc(TemplateArgsInfo->getRAngleLoc());
3981
3982 if (SemaRef.SubstTemplateArguments(TemplateArgsInfo->arguments(),
3983 TemplateArgs, VarTemplateArgsInfo))
3984 return nullptr;
3985 }
3986
3987 // Check that the template argument list is well-formed for this template.
3988 SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
3989 if (SemaRef.CheckTemplateArgumentList(InstVarTemplate, D->getLocation(),
3990 VarTemplateArgsInfo, false,
3991 SugaredConverted, CanonicalConverted,
3992 /*UpdateArgsWithConversions=*/true))
3993 return nullptr;
3994
3995 // Check whether we've already seen a declaration of this specialization.
3996 void *InsertPos = nullptr;
3998 InstVarTemplate->findSpecialization(CanonicalConverted, InsertPos);
3999
4000 // Check whether we've already seen a conflicting instantiation of this
4001 // declaration (for instance, if there was a prior implicit instantiation).
4002 bool Ignored;
4003 if (PrevDecl && SemaRef.CheckSpecializationInstantiationRedecl(
4004 D->getLocation(), D->getSpecializationKind(), PrevDecl,
4005 PrevDecl->getSpecializationKind(),
4006 PrevDecl->getPointOfInstantiation(), Ignored))
4007 return nullptr;
4008
4010 InstVarTemplate, D, VarTemplateArgsInfo, CanonicalConverted, PrevDecl);
4011}
4012
4014 VarTemplateDecl *VarTemplate, VarDecl *D,
4015 const TemplateArgumentListInfo &TemplateArgsInfo,
4018
4019 // Do substitution on the type of the declaration
4020 TypeSourceInfo *DI =
4021 SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs,
4022 D->getTypeSpecStartLoc(), D->getDeclName());
4023 if (!DI)
4024 return nullptr;
4025
4026 if (DI->getType()->isFunctionType()) {
4027 SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function)
4028 << D->isStaticDataMember() << DI->getType();
4029 return nullptr;
4030 }
4031
4032 // Build the instantiated declaration
4034 SemaRef.Context, Owner, D->getInnerLocStart(), D->getLocation(),
4035 VarTemplate, DI->getType(), DI, D->getStorageClass(), Converted);
4036 Var->setTemplateArgsAsWritten(TemplateArgsInfo);
4037 if (!PrevDecl) {
4038 void *InsertPos = nullptr;
4039 VarTemplate->findSpecialization(Converted, InsertPos);
4040 VarTemplate->AddSpecialization(Var, InsertPos);
4041 }
4042
4043 if (SemaRef.getLangOpts().OpenCL)
4044 SemaRef.deduceOpenCLAddressSpace(Var);
4045
4046 // Substitute the nested name specifier, if any.
4047 if (SubstQualifier(D, Var))
4048 return nullptr;
4049
4050 SemaRef.BuildVariableInstantiation(Var, D, TemplateArgs, LateAttrs, Owner,
4051 StartingScope, false, PrevDecl);
4052
4053 return Var;
4054}
4055
4056Decl *TemplateDeclInstantiator::VisitObjCAtDefsFieldDecl(ObjCAtDefsFieldDecl *D) {
4057 llvm_unreachable("@defs is not supported in Objective-C++");
4058}
4059
4060Decl *TemplateDeclInstantiator::VisitFriendTemplateDecl(FriendTemplateDecl *D) {
4061 // FIXME: We need to be able to instantiate FriendTemplateDecls.
4062 unsigned DiagID = SemaRef.getDiagnostics().getCustomDiagID(
4064 "cannot instantiate %0 yet");
4065 SemaRef.Diag(D->getLocation(), DiagID)
4066 << D->getDeclKindName();
4067
4068 return nullptr;
4069}
4070
4071Decl *TemplateDeclInstantiator::VisitConceptDecl(ConceptDecl *D) {
4072 llvm_unreachable("Concept definitions cannot reside inside a template");
4073}
4074
4075Decl *TemplateDeclInstantiator::VisitImplicitConceptSpecializationDecl(
4077 llvm_unreachable("Concept specializations cannot reside inside a template");
4078}
4079
4080Decl *
4081TemplateDeclInstantiator::VisitRequiresExprBodyDecl(RequiresExprBodyDecl *D) {
4083 D->getBeginLoc());
4084}
4085
4087 llvm_unreachable("Unexpected decl");
4088}
4089
4091 const MultiLevelTemplateArgumentList &TemplateArgs) {
4092 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
4093 if (D->isInvalidDecl())
4094 return nullptr;
4095
4096 Decl *SubstD;
4098 SubstD = Instantiator.Visit(D);
4099 });
4100 return SubstD;
4101}
4102
4104 FunctionDecl *Orig, QualType &T,
4105 TypeSourceInfo *&TInfo,
4106 DeclarationNameInfo &NameInfo) {
4108
4109 // C++2a [class.compare.default]p3:
4110 // the return type is replaced with bool
4111 auto *FPT = T->castAs<FunctionProtoType>();
4112 T = SemaRef.Context.getFunctionType(
4113 SemaRef.Context.BoolTy, FPT->getParamTypes(), FPT->getExtProtoInfo());
4114
4115 // Update the return type in the source info too. The most straightforward
4116 // way is to create new TypeSourceInfo for the new type. Use the location of
4117 // the '= default' as the location of the new type.
4118 //
4119 // FIXME: Set the correct return type when we initially transform the type,
4120 // rather than delaying it to now.
4121 TypeSourceInfo *NewTInfo =
4122 SemaRef.Context.getTrivialTypeSourceInfo(T, Orig->getEndLoc());
4123 auto OldLoc = TInfo->getTypeLoc().getAsAdjusted<FunctionProtoTypeLoc>();
4124 assert(OldLoc && "type of function is not a function type?");
4125 auto NewLoc = NewTInfo->getTypeLoc().castAs<FunctionProtoTypeLoc>();
4126 for (unsigned I = 0, N = OldLoc.getNumParams(); I != N; ++I)
4127 NewLoc.setParam(I, OldLoc.getParam(I));
4128 TInfo = NewTInfo;
4129
4130 // and the declarator-id is replaced with operator==
4131 NameInfo.setName(
4132 SemaRef.Context.DeclarationNames.getCXXOperatorName(OO_EqualEqual));
4133}
4134
4136 FunctionDecl *Spaceship) {
4137 if (Spaceship->isInvalidDecl())
4138 return nullptr;
4139
4140 // C++2a [class.compare.default]p3:
4141 // an == operator function is declared implicitly [...] with the same
4142 // access and function-definition and in the same class scope as the
4143 // three-way comparison operator function
4144 MultiLevelTemplateArgumentList NoTemplateArgs;
4146 NoTemplateArgs.addOuterRetainedLevels(RD->getTemplateDepth());
4147 TemplateDeclInstantiator Instantiator(*this, RD, NoTemplateArgs);
4148 Decl *R;
4149 if (auto *MD = dyn_cast<CXXMethodDecl>(Spaceship)) {
4150 R = Instantiator.VisitCXXMethodDecl(
4151 MD, /*TemplateParams=*/nullptr,
4153 } else {
4154 assert(Spaceship->getFriendObjectKind() &&
4155 "defaulted spaceship is neither a member nor a friend");
4156
4157 R = Instantiator.VisitFunctionDecl(
4158 Spaceship, /*TemplateParams=*/nullptr,
4160 if (!R)
4161 return nullptr;
4162
4163 FriendDecl *FD =
4164 FriendDecl::Create(Context, RD, Spaceship->getLocation(),
4165 cast<NamedDecl>(R), Spaceship->getBeginLoc());
4166 FD->setAccess(AS_public);
4167 RD->addDecl(FD);
4168 }
4169 return cast_or_null<FunctionDecl>(R);
4170}
4171
4172/// Instantiates a nested template parameter list in the current
4173/// instantiation context.
4174///
4175/// \param L The parameter list to instantiate
4176///
4177/// \returns NULL if there was an error
4180 // Get errors for all the parameters before bailing out.
4181 bool Invalid = false;
4182
4183 unsigned N = L->size();
4184 typedef SmallVector<NamedDecl *, 8> ParamVector;
4185 ParamVector Params;
4186 Params.reserve(N);
4187 for (auto &P : *L) {
4188 NamedDecl *D = cast_or_null<NamedDecl>(Visit(P));
4189 Params.push_back(D);
4190 Invalid = Invalid || !D || D->isInvalidDecl();
4191 }
4192
4193 // Clean up if we had an error.
4194 if (Invalid)
4195 return nullptr;
4196
4197 Expr *InstRequiresClause = L->getRequiresClause();
4198
4201 L->getLAngleLoc(), Params,
4202 L->getRAngleLoc(), InstRequiresClause);
4203 return InstL;
4204}
4205
4208 const MultiLevelTemplateArgumentList &TemplateArgs,
4209 bool EvaluateConstraints) {
4210 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
4211 Instantiator.setEvaluateConstraints(EvaluateConstraints);
4212 return Instantiator.SubstTemplateParams(Params);
4213}
4214
4215/// Instantiate the declaration of a class template partial
4216/// specialization.
4217///
4218/// \param ClassTemplate the (instantiated) class template that is partially
4219// specialized by the instantiation of \p PartialSpec.
4220///
4221/// \param PartialSpec the (uninstantiated) class template partial
4222/// specialization that we are instantiating.
4223///
4224/// \returns The instantiated partial specialization, if successful; otherwise,
4225/// NULL to indicate an error.
4228 ClassTemplateDecl *ClassTemplate,
4230 // Create a local instantiation scope for this class template partial
4231 // specialization, which will contain the instantiations of the template
4232 // parameters.
4234
4235 // Substitute into the template parameters of the class template partial
4236 // specialization.
4237 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
4238 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
4239 if (!InstParams)
4240 return nullptr;
4241
4242 // Substitute into the template arguments of the class template partial
4243 // specialization.
4244 const ASTTemplateArgumentListInfo *TemplArgInfo
4245 = PartialSpec->getTemplateArgsAsWritten();
4246 TemplateArgumentListInfo InstTemplateArgs(TemplArgInfo->LAngleLoc,
4247 TemplArgInfo->RAngleLoc);
4248 if (SemaRef.SubstTemplateArguments(TemplArgInfo->arguments(), TemplateArgs,
4249 InstTemplateArgs))
4250 return nullptr;
4251
4252 // Check that the template argument list is well-formed for this
4253 // class template.
4254 SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
4255 if (SemaRef.CheckTemplateArgumentList(
4256 ClassTemplate, PartialSpec->getLocation(), InstTemplateArgs,
4257 /*PartialTemplateArgs=*/false, SugaredConverted, CanonicalConverted))
4258 return nullptr;
4259
4260 // Check these arguments are valid for a template partial specialization.
4262 PartialSpec->getLocation(), ClassTemplate, InstTemplateArgs.size(),
4263 CanonicalConverted))
4264 return nullptr;
4265
4266 // Figure out where to insert this class template partial specialization
4267 // in the member template's set of class template partial specializations.
4268 void *InsertPos = nullptr;
4270 ClassTemplate->findPartialSpecialization(CanonicalConverted, InstParams,
4271 InsertPos);
4272
4273 // Build the canonical type that describes the converted template
4274 // arguments of the class template partial specialization.
4276 TemplateName(ClassTemplate), CanonicalConverted);
4277
4278 // Create the class template partial specialization declaration.
4281 SemaRef.Context, PartialSpec->getTagKind(), Owner,
4282 PartialSpec->getBeginLoc(), PartialSpec->getLocation(), InstParams,
4283 ClassTemplate, CanonicalConverted, CanonType,
4284 /*PrevDecl=*/nullptr);
4285
4286 InstPartialSpec->setTemplateArgsAsWritten(InstTemplateArgs);
4287
4288 // Substitute the nested name specifier, if any.
4289 if (SubstQualifier(PartialSpec, InstPartialSpec))
4290 return nullptr;
4291
4292 InstPartialSpec->setInstantiatedFromMember(PartialSpec);
4293
4294 if (PrevDecl) {
4295 // We've already seen a partial specialization with the same template
4296 // parameters and template arguments. This can happen, for example, when
4297 // substituting the outer template arguments ends up causing two
4298 // class template partial specializations of a member class template
4299 // to have identical forms, e.g.,
4300 //
4301 // template<typename T, typename U>
4302 // struct Outer {
4303 // template<typename X, typename Y> struct Inner;
4304 // template<typename Y> struct Inner<T, Y>;
4305 // template<typename Y> struct Inner<U, Y>;
4306 // };
4307 //
4308 // Outer<int, int> outer; // error: the partial specializations of Inner
4309 // // have the same signature.
4310 SemaRef.Diag(InstPartialSpec->getLocation(),
4311 diag::err_partial_spec_redeclared)
4312 << InstPartialSpec;
4313 SemaRef.Diag(PrevDecl->getLocation(), diag::note_prev_partial_spec_here)
4314 << SemaRef.Context.getTypeDeclType(PrevDecl);
4315 return nullptr;
4316 }
4317
4318 // Check the completed partial specialization.
4319 SemaRef.CheckTemplatePartialSpecialization(InstPartialSpec);
4320
4321 // Add this partial specialization to the set of class template partial
4322 // specializations.
4323 ClassTemplate->AddPartialSpecialization(InstPartialSpec,
4324 /*InsertPos=*/nullptr);
4325 return InstPartialSpec;
4326}
4327
4328/// Instantiate the declaration of a variable template partial
4329/// specialization.
4330///
4331/// \param VarTemplate the (instantiated) variable template that is partially
4332/// specialized by the instantiation of \p PartialSpec.
4333///
4334/// \param PartialSpec the (uninstantiated) variable template partial
4335/// specialization that we are instantiating.
4336///
4337/// \returns The instantiated partial specialization, if successful; otherwise,
4338/// NULL to indicate an error.
4341 VarTemplateDecl *VarTemplate,
4343 // Create a local instantiation scope for this variable template partial
4344 // specialization, which will contain the instantiations of the template
4345 // parameters.
4347
4348 // Substitute into the template parameters of the variable template partial
4349 // specialization.
4350 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
4351 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
4352 if (!InstParams)
4353 return nullptr;
4354
4355 // Substitute into the template arguments of the variable template partial
4356 // specialization.
4357 const ASTTemplateArgumentListInfo *TemplArgInfo
4358 = PartialSpec->getTemplateArgsAsWritten();
4359 TemplateArgumentListInfo InstTemplateArgs(TemplArgInfo->LAngleLoc,
4360 TemplArgInfo->RAngleLoc);
4361 if (SemaRef.SubstTemplateArguments(TemplArgInfo->arguments(), TemplateArgs,
4362 InstTemplateArgs))
4363 return nullptr;
4364
4365 // Check that the template argument list is well-formed for this
4366 // class template.
4367 SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
4368 if (SemaRef.CheckTemplateArgumentList(
4369 VarTemplate, PartialSpec->getLocation(), InstTemplateArgs,
4370 /*PartialTemplateArgs=*/false, SugaredConverted, CanonicalConverted))
4371 return nullptr;
4372
4373 // Check these arguments are valid for a template partial specialization.
4375 PartialSpec->getLocation(), VarTemplate, InstTemplateArgs.size(),
4376 CanonicalConverted))
4377 return nullptr;
4378
4379 // Figure out where to insert this variable template partial specialization
4380 // in the member template's set of variable template partial specializations.
4381 void *InsertPos = nullptr;
4383 VarTemplate->findPartialSpecialization(CanonicalConverted, InstParams,
4384 InsertPos);
4385
4386 // Do substitution on the type of the declaration
4387 TypeSourceInfo *DI = SemaRef.SubstType(
4388 PartialSpec->getTypeSourceInfo(), TemplateArgs,
4389 PartialSpec->getTypeSpecStartLoc(), PartialSpec->getDeclName());
4390 if (!DI)
4391 return nullptr;
4392
4393 if (DI->getType()->isFunctionType()) {
4394 SemaRef.Diag(PartialSpec->getLocation(),
4395 diag::err_variable_instantiates_to_function)
4396 << PartialSpec->isStaticDataMember() << DI->getType();
4397 return nullptr;
4398 }
4399
4400 // Create the variable template partial specialization declaration.
4401 VarTemplatePartialSpecializationDecl *InstPartialSpec =
4403 SemaRef.Context, Owner, PartialSpec->getInnerLocStart(),
4404 PartialSpec->getLocation(), InstParams, VarTemplate, DI->getType(),
4405 DI, PartialSpec->getStorageClass(), CanonicalConverted);
4406
4407 InstPartialSpec->setTemplateArgsAsWritten(InstTemplateArgs);
4408
4409 // Substitute the nested name specifier, if any.
4410 if (SubstQualifier(PartialSpec, InstPartialSpec))
4411 return nullptr;
4412
4413 InstPartialSpec->setInstantiatedFromMember(PartialSpec);
4414
4415 if (PrevDecl) {
4416 // We've already seen a partial specialization with the same template
4417 // parameters and template arguments. This can happen, for example, when
4418 // substituting the outer template arguments ends up causing two
4419 // variable template partial specializations of a member variable template
4420 // to have identical forms, e.g.,
4421 //
4422 // template<typename T, typename U>
4423 // struct Outer {
4424 // template<typename X, typename Y> pair<X,Y> p;
4425 // template<typename Y> pair<T, Y> p;
4426 // template<typename Y> pair<U, Y> p;
4427 // };
4428 //
4429 // Outer<int, int> outer; // error: the partial specializations of Inner
4430 // // have the same signature.
4431 SemaRef.Diag(PartialSpec->getLocation(),
4432 diag::err_var_partial_spec_redeclared)
4433 << InstPartialSpec;
4434 SemaRef.Diag(PrevDecl->getLocation(),
4435 diag::note_var_prev_partial_spec_here);
4436 return nullptr;
4437 }
4438 // Check the completed partial specialization.
4439 SemaRef.CheckTemplatePartialSpecialization(InstPartialSpec);
4440
4441 // Add this partial specialization to the set of variable template partial
4442 // specializations. The instantiation of the initializer is not necessary.
4443 VarTemplate->AddPartialSpecialization(InstPartialSpec, /*InsertPos=*/nullptr);
4444
4445 SemaRef.BuildVariableInstantiation(InstPartialSpec, PartialSpec, TemplateArgs,
4446 LateAttrs, Owner, StartingScope);
4447
4448 return InstPartialSpec;
4449}
4450
4454 TypeSourceInfo *OldTInfo = D->getTypeSourceInfo();
4455 assert(OldTInfo && "substituting function without type source info");
4456 assert(Params.empty() && "parameter vector is non-empty at start");
4457
4458 CXXRecordDecl *ThisContext = nullptr;
4459 Qualifiers ThisTypeQuals;
4460 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
4461 ThisContext = cast<CXXRecordDecl>(Owner);
4462 ThisTypeQuals = Method->getFunctionObjectParameterType().getQualifiers();
4463 }
4464
4465 TypeSourceInfo *NewTInfo = SemaRef.SubstFunctionDeclType(
4466 OldTInfo, TemplateArgs, D->getTypeSpecStartLoc(), D->getDeclName(),
4467 ThisContext, ThisTypeQuals, EvaluateConstraints);
4468 if (!NewTInfo)
4469 return nullptr;
4470
4471 TypeLoc OldTL = OldTInfo->getTypeLoc().IgnoreParens();
4472 if (FunctionProtoTypeLoc OldProtoLoc = OldTL.getAs<FunctionProtoTypeLoc>()) {
4473 if (NewTInfo != OldTInfo) {
4474 // Get parameters from the new type info.
4475 TypeLoc NewTL = NewTInfo->getTypeLoc().IgnoreParens();
4476 FunctionProtoTypeLoc NewProtoLoc = NewTL.castAs<FunctionProtoTypeLoc>();
4477 unsigned NewIdx = 0;
4478 for (unsigned OldIdx = 0, NumOldParams = OldProtoLoc.getNumParams();
4479 OldIdx != NumOldParams; ++OldIdx) {
4480 ParmVarDecl *OldParam = OldProtoLoc.getParam(OldIdx);
4481 if (!OldParam)
4482 return nullptr;
4483
4485
4486 std::optional<unsigned> NumArgumentsInExpansion;
4487 if (OldParam->isParameterPack())
4488 NumArgumentsInExpansion =
4489 SemaRef.getNumArgumentsInExpansion(OldParam->getType(),
4490 TemplateArgs);
4491 if (!NumArgumentsInExpansion) {
4492 // Simple case: normal parameter, or a parameter pack that's
4493 // instantiated to a (still-dependent) parameter pack.
4494 ParmVarDecl *NewParam = NewProtoLoc.getParam(NewIdx++);
4495 Params.push_back(NewParam);
4496 Scope->InstantiatedLocal(OldParam, NewParam);
4497 } else {
4498 // Parameter pack expansion: make the instantiation an argument pack.
4499 Scope->MakeInstantiatedLocalArgPack(OldParam);
4500 for (unsigned I = 0; I != *NumArgumentsInExpansion; ++I) {
4501 ParmVarDecl *NewParam = NewProtoLoc.getParam(NewIdx++);
4502 Params.push_back(NewParam);
4503 Scope->InstantiatedLocalPackArg(OldParam, NewParam);
4504 }
4505 }
4506 }
4507 } else {
4508 // The function type itself was not dependent and therefore no
4509 // substitution occurred. However, we still need to instantiate
4510 // the function parameters themselves.
4511 const FunctionProtoType *OldProto =
4512 cast<FunctionProtoType>(OldProtoLoc.getType());
4513 for (unsigned i = 0, i_end = OldProtoLoc.getNumParams(); i != i_end;
4514 ++i) {
4515 ParmVarDecl *OldParam = OldProtoLoc.getParam(i);
4516 if (!OldParam) {
4517 Params.push_back(SemaRef.BuildParmVarDeclForTypedef(
4518 D, D->getLocation(), OldProto->getParamType(i)));
4519 continue;
4520 }
4521
4522 ParmVarDecl *Parm =
4523 cast_or_null<ParmVarDecl>(VisitParmVarDecl(OldParam));
4524 if (!Parm)
4525 return nullptr;
4526 Params.push_back(Parm);
4527 }
4528 }
4529 } else {
4530 // If the type of this function, after ignoring parentheses, is not
4531 // *directly* a function type, then we're instantiating a function that
4532 // was declared via a typedef or with attributes, e.g.,
4533 //
4534 // typedef int functype(int, int);
4535 // functype func;
4536 // int __cdecl meth(int, int);
4537 //
4538 // In this case, we'll just go instantiate the ParmVarDecls that we
4539 // synthesized in the method declaration.
4540 SmallVector<QualType, 4> ParamTypes;
4541 Sema::ExtParameterInfoBuilder ExtParamInfos;
4542 if (SemaRef.SubstParmTypes(D->getLocation(), D->parameters(), nullptr,
4543 TemplateArgs, ParamTypes, &Params,
4544 ExtParamInfos))
4545 return nullptr;
4546 }
4547
4548 return NewTInfo;
4549}
4550
4551/// Introduce the instantiated local variables into the local
4552/// instantiation scope.
4553void Sema::addInstantiatedLocalVarsToScope(FunctionDecl *Function,
4554 const FunctionDecl *PatternDecl,
4556 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(getFunctionScopes().back());
4557
4558 for (auto *decl : PatternDecl->decls()) {
4559 if (!isa<VarDecl>(decl) || isa<ParmVarDecl>(decl))
4560 continue;
4561
4562 VarDecl *VD = cast<VarDecl>(decl);
4563 IdentifierInfo *II = VD->getIdentifier();
4564
4565 auto it = llvm::find_if(Function->decls(), [&](Decl *inst) {
4566 VarDecl *InstVD = dyn_cast<VarDecl>(inst);
4567 return InstVD && InstVD->isLocalVarDecl() &&
4568 InstVD->getIdentifier() == II;
4569 });
4570
4571 if (it == Function->decls().end())
4572 continue;
4573
4574 Scope.InstantiatedLocal(VD, *it);
4575 LSI->addCapture(cast<VarDecl>(*it), /*isBlock=*/false, /*isByref=*/false,
4576 /*isNested=*/false, VD->getLocation(), SourceLocation(),
4577 VD->getType(), /*Invalid=*/false);
4578 }
4579}
4580
4581/// Introduce the instantiated function parameters into the local
4582/// instantiation scope, and set the parameter names to those used
4583/// in the template.
4584bool Sema::addInstantiatedParametersToScope(
4585 FunctionDecl *Function, const FunctionDecl *PatternDecl,
4587 const MultiLevelTemplateArgumentList &TemplateArgs) {
4588 unsigned FParamIdx = 0;
4589 for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I) {
4590 const ParmVarDecl *PatternParam = PatternDecl->getParamDecl(I);
4591 if (!PatternParam->isParameterPack()) {
4592 // Simple case: not a parameter pack.
4593 assert(FParamIdx < Function->getNumParams());
4594 ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
4595 FunctionParam->setDeclName(PatternParam->getDeclName());
4596 // If the parameter's type is not dependent, update it to match the type
4597 // in the pattern. They can differ in top-level cv-qualifiers, and we want
4598 // the pattern's type here. If the type is dependent, they can't differ,
4599 // per core issue 1668. Substitute into the type from the pattern, in case
4600 // it's instantiation-dependent.
4601 // FIXME: Updating the type to work around this is at best fragile.
4602 if (!PatternDecl->getType()->isDependentType()) {
4603 QualType T = SubstType(PatternParam->getType(), TemplateArgs,
4604 FunctionParam->getLocation(),
4605 FunctionParam->getDeclName());
4606 if (T.isNull())
4607 return true;
4608 FunctionParam->setType(T);
4609 }
4610
4611 Scope.InstantiatedLocal(PatternParam, FunctionParam);
4612 ++FParamIdx;
4613 continue;
4614 }
4615
4616 // Expand the parameter pack.
4617 Scope.MakeInstantiatedLocalArgPack(PatternParam);
4618 std::optional<unsigned> NumArgumentsInExpansion =
4619 getNumArgumentsInExpansion(PatternParam->getType(), TemplateArgs);
4620 if (NumArgumentsInExpansion) {
4621 QualType PatternType =
4622 PatternParam->getType()->castAs<PackExpansionType>()->getPattern();
4623 for (unsigned Arg = 0; Arg < *NumArgumentsInExpansion; ++Arg) {
4624 ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
4625 FunctionParam->setDeclName(PatternParam->getDeclName());
4626 if (!PatternDecl->getType()->isDependentType()) {
4627 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, Arg);
4628 QualType T =
4629 SubstType(PatternType, TemplateArgs, FunctionParam->getLocation(),
4630 FunctionParam->getDeclName());
4631 if (T.isNull())
4632 return true;
4633 FunctionParam->setType(T);
4634 }
4635
4636 Scope.InstantiatedLocalPackArg(PatternParam, FunctionParam);
4637 ++FParamIdx;
4638 }
4639 }
4640 }
4641
4642 return false;
4643}
4644
4646 ParmVarDecl *Param) {
4647 assert(Param->hasUninstantiatedDefaultArg());
4648
4649 // Instantiate the expression.
4650 //
4651 // FIXME: Pass in a correct Pattern argument, otherwise
4652 // getTemplateInstantiationArgs uses the lexical context of FD, e.g.
4653 //
4654 // template<typename T>
4655 // struct A {
4656 // static int FooImpl();
4657 //
4658 // template<typename Tp>
4659 // // bug: default argument A<T>::FooImpl() is evaluated with 2-level
4660 // // template argument list [[T], [Tp]], should be [[Tp]].
4661 // friend A<Tp> Foo(int a);
4662 // };
4663 //
4664 // template<typename T>
4665 // A<T> Foo(int a = A<T>::FooImpl());
4666 MultiLevelTemplateArgumentList TemplateArgs =
4668 /*Final=*/false, /*Innermost=*/std::nullopt,
4669 /*RelativeToPrimary=*/true);
4670
4671 if (SubstDefaultArgument(CallLoc, Param, TemplateArgs, /*ForCallExpr*/ true))
4672 return true;
4673
4675 L->DefaultArgumentInstantiated(Param);
4676
4677 return false;
4678}
4679
4681 FunctionDecl *Decl) {
4682 const FunctionProtoType *Proto = Decl->getType()->castAs<FunctionProtoType>();
4684 return;
4685
4686 InstantiatingTemplate Inst(*this, PointOfInstantiation, Decl,
4688 if (Inst.isInvalid()) {
4689 // We hit the instantiation depth limit. Clear the exception specification
4690 // so that our callers don't have to cope with EST_Uninstantiated.
4692 return;
4693 }
4694 if (Inst.isAlreadyInstantiating()) {
4695 // This exception specification indirectly depends on itself. Reject.
4696 // FIXME: Corresponding rule in the standard?
4697 Diag(PointOfInstantiation, diag::err_exception_spec_cycle) << Decl;
4699 return;
4700 }
4701
4702 // Enter the scope of this instantiation. We don't use
4703 // PushDeclContext because we don't have a scope.
4704 Sema::ContextRAII savedContext(*this, Decl);
4706
4707 MultiLevelTemplateArgumentList TemplateArgs =
4709 /*Final=*/false, /*Innermost=*/std::nullopt,
4710 /*RelativeToPrimary*/ true);
4711
4712 // FIXME: We can't use getTemplateInstantiationPattern(false) in general
4713 // here, because for a non-defining friend declaration in a class template,
4714 // we don't store enough information to map back to the friend declaration in
4715 // the template.
4716 FunctionDecl *Template = Proto->getExceptionSpecTemplate();
4717 if (addInstantiatedParametersToScope(Decl, Template, Scope, TemplateArgs)) {
4719 return;
4720 }
4721
4723 TemplateArgs);
4724}
4725
4726/// Initializes the common fields of an instantiation function
4727/// declaration (New) from the corresponding fields of its template (Tmpl).
4728///
4729/// \returns true if there was an error
4730bool
4732 FunctionDecl *Tmpl) {
4733 New->setImplicit(Tmpl->isImplicit());
4734
4735 // Forward the mangling number from the template to the instantiated decl.
4736 SemaRef.Context.setManglingNumber(New,
4737 SemaRef.Context.getManglingNumber(Tmpl));
4738
4739 // If we are performing substituting explicitly-specified template arguments
4740 // or deduced template arguments into a function template and we reach this
4741 // point, we are now past the point where SFINAE applies and have committed
4742 // to keeping the new function template specialization. We therefore
4743 // convert the active template instantiation for the function template
4744 // into a template instantiation for this specific function template
4745 // specialization, which is not a SFINAE context, so that we diagnose any
4746 // further errors in the declaration itself.
4747 //
4748 // FIXME: This is a hack.
4749 typedef Sema::CodeSynthesisContext ActiveInstType;
4750 ActiveInstType &ActiveInst = SemaRef.CodeSynthesisContexts.back();
4751 if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution ||
4752 ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) {
4753 if (isa<FunctionTemplateDecl>(ActiveInst.Entity)) {
4754 SemaRef.InstantiatingSpecializations.erase(
4755 {ActiveInst.Entity->getCanonicalDecl(), ActiveInst.Kind});
4756 atTemplateEnd(SemaRef.TemplateInstCallbacks, SemaRef, ActiveInst);
4757 ActiveInst.Kind = ActiveInstType::TemplateInstantiation;
4758 ActiveInst.Entity = New;
4759 atTemplateBegin(SemaRef.TemplateInstCallbacks, SemaRef, ActiveInst);
4760 }
4761 }
4762
4763 const FunctionProtoType *Proto = Tmpl->getType()->getAs<FunctionProtoType>();
4764 assert(Proto && "Function template without prototype?");
4765
4766 if (Proto->hasExceptionSpec() || Proto->getNoReturnAttr()) {
4768
4769 // DR1330: In C++11, defer instantiation of a non-trivial
4770 // exception specification.
4771 // DR1484: Local classes and their members are instantiated along with the
4772 // containing function.
4773 if (SemaRef.getLangOpts().CPlusPlus11 &&
4774 EPI.ExceptionSpec.Type != EST_None &&
4778 FunctionDecl *ExceptionSpecTemplate = Tmpl;
4780 ExceptionSpecTemplate = EPI.ExceptionSpec.SourceTemplate;
4783 NewEST = EST_Unevaluated;
4784
4785 // Mark the function has having an uninstantiated exception specification.
4786 const FunctionProtoType *NewProto
4787 = New->getType()->getAs<FunctionProtoType>();
4788 assert(NewProto && "Template instantiation without function prototype?");
4789 EPI = NewProto->getExtProtoInfo();
4790 EPI.ExceptionSpec.Type = NewEST;
4791 EPI.ExceptionSpec.SourceDecl = New;
4792 EPI.ExceptionSpec.SourceTemplate = ExceptionSpecTemplate;
4793 New->setType(SemaRef.Context.getFunctionType(
4794 NewProto->getReturnType(), NewProto->getParamTypes(), EPI));
4795 } else {
4796 Sema::ContextRAII SwitchContext(SemaRef, New);
4797 SemaRef.SubstExceptionSpec(New, Proto, TemplateArgs);
4798 }
4799 }
4800
4801 // Get the definition. Leaves the variable unchanged if undefined.
4802 const FunctionDecl *Definition = Tmpl;
4803 Tmpl->isDefined(Definition);
4804
4805 SemaRef.InstantiateAttrs(TemplateArgs, Definition, New,
4806 LateAttrs, StartingScope);
4807
4808 return false;
4809}
4810
4811/// Initializes common fields of an instantiated method
4812/// declaration (New) from the corresponding fields of its template
4813/// (Tmpl).
4814///
4815/// \returns true if there was an error
4816bool
4818 CXXMethodDecl *Tmpl) {
4819 if (InitFunctionInstantiation(New, Tmpl))
4820 return true;
4821
4822 if (isa<CXXDestructorDecl>(New) && SemaRef.getLangOpts().CPlusPlus11)
4823 SemaRef.AdjustDestructorExceptionSpec(cast<CXXDestructorDecl>(New));
4824
4825 New->setAccess(Tmpl->getAccess());
4826 if (Tmpl->isVirtualAsWritten())
4827 New->setVirtualAsWritten(true);
4828
4829 // FIXME: New needs a pointer to Tmpl
4830 return false;
4831}
4832
4834 FunctionDecl *Tmpl) {
4835 // Transfer across any unqualified lookups.
4836 if (auto *DFI = Tmpl->getDefalutedOrDeletedInfo()) {
4838 Lookups.reserve(DFI->getUnqualifiedLookups().size());
4839 bool AnyChanged = false;
4840 for (DeclAccessPair DA : DFI->getUnqualifiedLookups()) {
4841 NamedDecl *D = SemaRef.FindInstantiatedDecl(New->getLocation(),
4842 DA.getDecl(), TemplateArgs);
4843 if (!D)
4844 return true;
4845 AnyChanged |= (D != DA.getDecl());
4846 Lookups.push_back(DeclAccessPair::make(D, DA.getAccess()));
4847 }
4848
4849 // It's unlikely that substitution will change any declarations. Don't
4850 // store an unnecessary copy in that case.
4853 SemaRef.Context, Lookups)
4854 : DFI);
4855 }
4856
4857 SemaRef.SetDeclDefaulted(New, Tmpl->getLocation());
4858 return false;
4859}
4860
4861/// Instantiate (or find existing instantiation of) a function template with a
4862/// given set of template arguments.
4863///
4864/// Usually this should not be used, and template argument deduction should be
4865/// used in its place.
4869 FunctionDecl *FD = FTD->getTemplatedDecl();
4870
4872 InstantiatingTemplate Inst(*this, Loc, FTD, Args->asArray(), CSC, Info);
4873 if (Inst.isInvalid())
4874 return nullptr;
4875
4876 ContextRAII SavedContext(*this, FD);
4877 MultiLevelTemplateArgumentList MArgs(FTD, Args->asArray(),
4878 /*Final=*/false);
4879
4880 return cast_or_null<FunctionDecl>(SubstDecl(FD, FD->getParent(), MArgs));
4881}
4882
4883/// Instantiate the definition of the given function from its
4884/// template.
4885///
4886/// \param PointOfInstantiation the point at which the instantiation was
4887/// required. Note that this is not precisely a "point of instantiation"
4888/// for the function, but it's close.
4889///
4890/// \param Function the already-instantiated declaration of a
4891/// function template specialization or member function of a class template
4892/// specialization.
4893///
4894/// \param Recursive if true, recursively instantiates any functions that
4895/// are required by this instantiation.
4896///
4897/// \param DefinitionRequired if true, then we are performing an explicit
4898/// instantiation where the body of the function is required. Complain if
4899/// there is no such body.
4902 bool Recursive,
4903 bool DefinitionRequired,
4904 bool AtEndOfTU) {
4905 if (Function->isInvalidDecl() || isa<CXXDeductionGuideDecl>(Function))
4906