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