[clangd] Re-land "support outgoing calls in call hierarchy" (#117673)
[llvm-project.git] / clang / lib / Sema / SemaTemplateInstantiateDecl.cpp
blob39f8ece62ed5c2bbed9773ae9f7262aa2b92e5dc
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 //===----------------------------------------------------------------------===/
12 #include "TreeTransform.h"
13 #include "clang/AST/ASTConsumer.h"
14 #include "clang/AST/ASTContext.h"
15 #include "clang/AST/ASTMutationListener.h"
16 #include "clang/AST/DeclTemplate.h"
17 #include "clang/AST/DependentDiagnostic.h"
18 #include "clang/AST/Expr.h"
19 #include "clang/AST/ExprCXX.h"
20 #include "clang/AST/PrettyDeclStackTrace.h"
21 #include "clang/AST/TypeLoc.h"
22 #include "clang/Basic/SourceManager.h"
23 #include "clang/Basic/TargetInfo.h"
24 #include "clang/Sema/EnterExpressionEvaluationContext.h"
25 #include "clang/Sema/Initialization.h"
26 #include "clang/Sema/Lookup.h"
27 #include "clang/Sema/ScopeInfo.h"
28 #include "clang/Sema/SemaAMDGPU.h"
29 #include "clang/Sema/SemaCUDA.h"
30 #include "clang/Sema/SemaHLSL.h"
31 #include "clang/Sema/SemaObjC.h"
32 #include "clang/Sema/SemaOpenMP.h"
33 #include "clang/Sema/SemaSwift.h"
34 #include "clang/Sema/Template.h"
35 #include "clang/Sema/TemplateInstCallback.h"
36 #include "llvm/Support/TimeProfiler.h"
37 #include <optional>
39 using namespace clang;
41 static bool isDeclWithinFunction(const Decl *D) {
42 const DeclContext *DC = D->getDeclContext();
43 if (DC->isFunctionOrMethod())
44 return true;
46 if (DC->isRecord())
47 return cast<CXXRecordDecl>(DC)->isLocalClass();
49 return false;
52 template<typename DeclT>
53 static bool SubstQualifier(Sema &SemaRef, const DeclT *OldDecl, DeclT *NewDecl,
54 const MultiLevelTemplateArgumentList &TemplateArgs) {
55 if (!OldDecl->getQualifierLoc())
56 return false;
58 assert((NewDecl->getFriendObjectKind() ||
59 !OldDecl->getLexicalDeclContext()->isDependentContext()) &&
60 "non-friend with qualified name defined in dependent context");
61 Sema::ContextRAII SavedContext(
62 SemaRef,
63 const_cast<DeclContext *>(NewDecl->getFriendObjectKind()
64 ? NewDecl->getLexicalDeclContext()
65 : OldDecl->getLexicalDeclContext()));
67 NestedNameSpecifierLoc NewQualifierLoc
68 = SemaRef.SubstNestedNameSpecifierLoc(OldDecl->getQualifierLoc(),
69 TemplateArgs);
71 if (!NewQualifierLoc)
72 return true;
74 NewDecl->setQualifierInfo(NewQualifierLoc);
75 return false;
78 bool TemplateDeclInstantiator::SubstQualifier(const DeclaratorDecl *OldDecl,
79 DeclaratorDecl *NewDecl) {
80 return ::SubstQualifier(SemaRef, OldDecl, NewDecl, TemplateArgs);
83 bool TemplateDeclInstantiator::SubstQualifier(const TagDecl *OldDecl,
84 TagDecl *NewDecl) {
85 return ::SubstQualifier(SemaRef, OldDecl, NewDecl, TemplateArgs);
88 // Include attribute instantiation code.
89 #include "clang/Sema/AttrTemplateInstantiate.inc"
91 static void instantiateDependentAlignedAttr(
92 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
93 const AlignedAttr *Aligned, Decl *New, bool IsPackExpansion) {
94 if (Aligned->isAlignmentExpr()) {
95 // The alignment expression is a constant expression.
96 EnterExpressionEvaluationContext Unevaluated(
97 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
98 ExprResult Result = S.SubstExpr(Aligned->getAlignmentExpr(), TemplateArgs);
99 if (!Result.isInvalid())
100 S.AddAlignedAttr(New, *Aligned, Result.getAs<Expr>(), IsPackExpansion);
101 } else {
102 if (TypeSourceInfo *Result =
103 S.SubstType(Aligned->getAlignmentType(), TemplateArgs,
104 Aligned->getLocation(), DeclarationName())) {
105 if (!S.CheckAlignasTypeArgument(Aligned->getSpelling(), Result,
106 Aligned->getLocation(),
107 Result->getTypeLoc().getSourceRange()))
108 S.AddAlignedAttr(New, *Aligned, Result, IsPackExpansion);
113 static void instantiateDependentAlignedAttr(
114 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
115 const AlignedAttr *Aligned, Decl *New) {
116 if (!Aligned->isPackExpansion()) {
117 instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, false);
118 return;
121 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
122 if (Aligned->isAlignmentExpr())
123 S.collectUnexpandedParameterPacks(Aligned->getAlignmentExpr(),
124 Unexpanded);
125 else
126 S.collectUnexpandedParameterPacks(Aligned->getAlignmentType()->getTypeLoc(),
127 Unexpanded);
128 assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
130 // Determine whether we can expand this attribute pack yet.
131 bool Expand = true, RetainExpansion = false;
132 std::optional<unsigned> NumExpansions;
133 // FIXME: Use the actual location of the ellipsis.
134 SourceLocation EllipsisLoc = Aligned->getLocation();
135 if (S.CheckParameterPacksForExpansion(EllipsisLoc, Aligned->getRange(),
136 Unexpanded, TemplateArgs, Expand,
137 RetainExpansion, NumExpansions))
138 return;
140 if (!Expand) {
141 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(S, -1);
142 instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, true);
143 } else {
144 for (unsigned I = 0; I != *NumExpansions; ++I) {
145 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(S, I);
146 instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, false);
151 static void instantiateDependentAssumeAlignedAttr(
152 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
153 const AssumeAlignedAttr *Aligned, Decl *New) {
154 // The alignment expression is a constant expression.
155 EnterExpressionEvaluationContext Unevaluated(
156 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
158 Expr *E, *OE = nullptr;
159 ExprResult Result = S.SubstExpr(Aligned->getAlignment(), TemplateArgs);
160 if (Result.isInvalid())
161 return;
162 E = Result.getAs<Expr>();
164 if (Aligned->getOffset()) {
165 Result = S.SubstExpr(Aligned->getOffset(), TemplateArgs);
166 if (Result.isInvalid())
167 return;
168 OE = Result.getAs<Expr>();
171 S.AddAssumeAlignedAttr(New, *Aligned, E, OE);
174 static void instantiateDependentAlignValueAttr(
175 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
176 const AlignValueAttr *Aligned, Decl *New) {
177 // The alignment expression is a constant expression.
178 EnterExpressionEvaluationContext Unevaluated(
179 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
180 ExprResult Result = S.SubstExpr(Aligned->getAlignment(), TemplateArgs);
181 if (!Result.isInvalid())
182 S.AddAlignValueAttr(New, *Aligned, Result.getAs<Expr>());
185 static void instantiateDependentAllocAlignAttr(
186 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
187 const AllocAlignAttr *Align, Decl *New) {
188 Expr *Param = IntegerLiteral::Create(
189 S.getASTContext(),
190 llvm::APInt(64, Align->getParamIndex().getSourceIndex()),
191 S.getASTContext().UnsignedLongLongTy, Align->getLocation());
192 S.AddAllocAlignAttr(New, *Align, Param);
195 static void instantiateDependentAnnotationAttr(
196 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
197 const AnnotateAttr *Attr, Decl *New) {
198 EnterExpressionEvaluationContext Unevaluated(
199 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
201 // If the attribute has delayed arguments it will have to instantiate those
202 // and handle them as new arguments for the attribute.
203 bool HasDelayedArgs = Attr->delayedArgs_size();
205 ArrayRef<Expr *> ArgsToInstantiate =
206 HasDelayedArgs
207 ? ArrayRef<Expr *>{Attr->delayedArgs_begin(), Attr->delayedArgs_end()}
208 : ArrayRef<Expr *>{Attr->args_begin(), Attr->args_end()};
210 SmallVector<Expr *, 4> Args;
211 if (S.SubstExprs(ArgsToInstantiate,
212 /*IsCall=*/false, TemplateArgs, Args))
213 return;
215 StringRef Str = Attr->getAnnotation();
216 if (HasDelayedArgs) {
217 if (Args.size() < 1) {
218 S.Diag(Attr->getLoc(), diag::err_attribute_too_few_arguments)
219 << Attr << 1;
220 return;
223 if (!S.checkStringLiteralArgumentAttr(*Attr, Args[0], Str))
224 return;
226 llvm::SmallVector<Expr *, 4> ActualArgs;
227 ActualArgs.insert(ActualArgs.begin(), Args.begin() + 1, Args.end());
228 std::swap(Args, ActualArgs);
230 auto *AA = S.CreateAnnotationAttr(*Attr, Str, Args);
231 if (AA) {
232 New->addAttr(AA);
236 static Expr *instantiateDependentFunctionAttrCondition(
237 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
238 const Attr *A, Expr *OldCond, const Decl *Tmpl, FunctionDecl *New) {
239 Expr *Cond = nullptr;
241 Sema::ContextRAII SwitchContext(S, New);
242 EnterExpressionEvaluationContext Unevaluated(
243 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
244 ExprResult Result = S.SubstExpr(OldCond, TemplateArgs);
245 if (Result.isInvalid())
246 return nullptr;
247 Cond = Result.getAs<Expr>();
249 if (!Cond->isTypeDependent()) {
250 ExprResult Converted = S.PerformContextuallyConvertToBool(Cond);
251 if (Converted.isInvalid())
252 return nullptr;
253 Cond = Converted.get();
256 SmallVector<PartialDiagnosticAt, 8> Diags;
257 if (OldCond->isValueDependent() && !Cond->isValueDependent() &&
258 !Expr::isPotentialConstantExprUnevaluated(Cond, New, Diags)) {
259 S.Diag(A->getLocation(), diag::err_attr_cond_never_constant_expr) << A;
260 for (const auto &P : Diags)
261 S.Diag(P.first, P.second);
262 return nullptr;
264 return Cond;
267 static void instantiateDependentEnableIfAttr(
268 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
269 const EnableIfAttr *EIA, const Decl *Tmpl, FunctionDecl *New) {
270 Expr *Cond = instantiateDependentFunctionAttrCondition(
271 S, TemplateArgs, EIA, EIA->getCond(), Tmpl, New);
273 if (Cond)
274 New->addAttr(new (S.getASTContext()) EnableIfAttr(S.getASTContext(), *EIA,
275 Cond, EIA->getMessage()));
278 static void instantiateDependentDiagnoseIfAttr(
279 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
280 const DiagnoseIfAttr *DIA, const Decl *Tmpl, FunctionDecl *New) {
281 Expr *Cond = instantiateDependentFunctionAttrCondition(
282 S, TemplateArgs, DIA, DIA->getCond(), Tmpl, New);
284 if (Cond)
285 New->addAttr(new (S.getASTContext()) DiagnoseIfAttr(
286 S.getASTContext(), *DIA, Cond, DIA->getMessage(),
287 DIA->getDiagnosticType(), DIA->getArgDependent(), New));
290 // Constructs and adds to New a new instance of CUDALaunchBoundsAttr using
291 // template A as the base and arguments from TemplateArgs.
292 static void instantiateDependentCUDALaunchBoundsAttr(
293 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
294 const CUDALaunchBoundsAttr &Attr, Decl *New) {
295 // The alignment expression is a constant expression.
296 EnterExpressionEvaluationContext Unevaluated(
297 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
299 ExprResult Result = S.SubstExpr(Attr.getMaxThreads(), TemplateArgs);
300 if (Result.isInvalid())
301 return;
302 Expr *MaxThreads = Result.getAs<Expr>();
304 Expr *MinBlocks = nullptr;
305 if (Attr.getMinBlocks()) {
306 Result = S.SubstExpr(Attr.getMinBlocks(), TemplateArgs);
307 if (Result.isInvalid())
308 return;
309 MinBlocks = Result.getAs<Expr>();
312 Expr *MaxBlocks = nullptr;
313 if (Attr.getMaxBlocks()) {
314 Result = S.SubstExpr(Attr.getMaxBlocks(), TemplateArgs);
315 if (Result.isInvalid())
316 return;
317 MaxBlocks = Result.getAs<Expr>();
320 S.AddLaunchBoundsAttr(New, Attr, MaxThreads, MinBlocks, MaxBlocks);
323 static void
324 instantiateDependentModeAttr(Sema &S,
325 const MultiLevelTemplateArgumentList &TemplateArgs,
326 const ModeAttr &Attr, Decl *New) {
327 S.AddModeAttr(New, Attr, Attr.getMode(),
328 /*InInstantiation=*/true);
331 /// Instantiation of 'declare simd' attribute and its arguments.
332 static void instantiateOMPDeclareSimdDeclAttr(
333 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
334 const OMPDeclareSimdDeclAttr &Attr, Decl *New) {
335 // Allow 'this' in clauses with varlist.
336 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(New))
337 New = FTD->getTemplatedDecl();
338 auto *FD = cast<FunctionDecl>(New);
339 auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(FD->getDeclContext());
340 SmallVector<Expr *, 4> Uniforms, Aligneds, Alignments, Linears, Steps;
341 SmallVector<unsigned, 4> LinModifiers;
343 auto SubstExpr = [&](Expr *E) -> ExprResult {
344 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
345 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
346 Sema::ContextRAII SavedContext(S, FD);
347 LocalInstantiationScope Local(S);
348 if (FD->getNumParams() > PVD->getFunctionScopeIndex())
349 Local.InstantiatedLocal(
350 PVD, FD->getParamDecl(PVD->getFunctionScopeIndex()));
351 return S.SubstExpr(E, TemplateArgs);
353 Sema::CXXThisScopeRAII ThisScope(S, ThisContext, Qualifiers(),
354 FD->isCXXInstanceMember());
355 return S.SubstExpr(E, TemplateArgs);
358 // Substitute a single OpenMP clause, which is a potentially-evaluated
359 // full-expression.
360 auto Subst = [&](Expr *E) -> ExprResult {
361 EnterExpressionEvaluationContext Evaluated(
362 S, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
363 ExprResult Res = SubstExpr(E);
364 if (Res.isInvalid())
365 return Res;
366 return S.ActOnFinishFullExpr(Res.get(), false);
369 ExprResult Simdlen;
370 if (auto *E = Attr.getSimdlen())
371 Simdlen = Subst(E);
373 if (Attr.uniforms_size() > 0) {
374 for(auto *E : Attr.uniforms()) {
375 ExprResult Inst = Subst(E);
376 if (Inst.isInvalid())
377 continue;
378 Uniforms.push_back(Inst.get());
382 auto AI = Attr.alignments_begin();
383 for (auto *E : Attr.aligneds()) {
384 ExprResult Inst = Subst(E);
385 if (Inst.isInvalid())
386 continue;
387 Aligneds.push_back(Inst.get());
388 Inst = ExprEmpty();
389 if (*AI)
390 Inst = S.SubstExpr(*AI, TemplateArgs);
391 Alignments.push_back(Inst.get());
392 ++AI;
395 auto SI = Attr.steps_begin();
396 for (auto *E : Attr.linears()) {
397 ExprResult Inst = Subst(E);
398 if (Inst.isInvalid())
399 continue;
400 Linears.push_back(Inst.get());
401 Inst = ExprEmpty();
402 if (*SI)
403 Inst = S.SubstExpr(*SI, TemplateArgs);
404 Steps.push_back(Inst.get());
405 ++SI;
407 LinModifiers.append(Attr.modifiers_begin(), Attr.modifiers_end());
408 (void)S.OpenMP().ActOnOpenMPDeclareSimdDirective(
409 S.ConvertDeclToDeclGroup(New), Attr.getBranchState(), Simdlen.get(),
410 Uniforms, Aligneds, Alignments, Linears, LinModifiers, Steps,
411 Attr.getRange());
414 /// Instantiation of 'declare variant' attribute and its arguments.
415 static void instantiateOMPDeclareVariantAttr(
416 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
417 const OMPDeclareVariantAttr &Attr, Decl *New) {
418 // Allow 'this' in clauses with varlist.
419 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(New))
420 New = FTD->getTemplatedDecl();
421 auto *FD = cast<FunctionDecl>(New);
422 auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(FD->getDeclContext());
424 auto &&SubstExpr = [FD, ThisContext, &S, &TemplateArgs](Expr *E) {
425 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
426 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
427 Sema::ContextRAII SavedContext(S, FD);
428 LocalInstantiationScope Local(S);
429 if (FD->getNumParams() > PVD->getFunctionScopeIndex())
430 Local.InstantiatedLocal(
431 PVD, FD->getParamDecl(PVD->getFunctionScopeIndex()));
432 return S.SubstExpr(E, TemplateArgs);
434 Sema::CXXThisScopeRAII ThisScope(S, ThisContext, Qualifiers(),
435 FD->isCXXInstanceMember());
436 return S.SubstExpr(E, TemplateArgs);
439 // Substitute a single OpenMP clause, which is a potentially-evaluated
440 // full-expression.
441 auto &&Subst = [&SubstExpr, &S](Expr *E) {
442 EnterExpressionEvaluationContext Evaluated(
443 S, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
444 ExprResult Res = SubstExpr(E);
445 if (Res.isInvalid())
446 return Res;
447 return S.ActOnFinishFullExpr(Res.get(), false);
450 ExprResult VariantFuncRef;
451 if (Expr *E = Attr.getVariantFuncRef()) {
452 // Do not mark function as is used to prevent its emission if this is the
453 // only place where it is used.
454 EnterExpressionEvaluationContext Unevaluated(
455 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
456 VariantFuncRef = Subst(E);
459 // Copy the template version of the OMPTraitInfo and run substitute on all
460 // score and condition expressiosn.
461 OMPTraitInfo &TI = S.getASTContext().getNewOMPTraitInfo();
462 TI = *Attr.getTraitInfos();
464 // Try to substitute template parameters in score and condition expressions.
465 auto SubstScoreOrConditionExpr = [&S, Subst](Expr *&E, bool) {
466 if (E) {
467 EnterExpressionEvaluationContext Unevaluated(
468 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
469 ExprResult ER = Subst(E);
470 if (ER.isUsable())
471 E = ER.get();
472 else
473 return true;
475 return false;
477 if (TI.anyScoreOrCondition(SubstScoreOrConditionExpr))
478 return;
480 Expr *E = VariantFuncRef.get();
482 // Check function/variant ref for `omp declare variant` but not for `omp
483 // begin declare variant` (which use implicit attributes).
484 std::optional<std::pair<FunctionDecl *, Expr *>> DeclVarData =
485 S.OpenMP().checkOpenMPDeclareVariantFunction(
486 S.ConvertDeclToDeclGroup(New), E, TI, Attr.appendArgs_size(),
487 Attr.getRange());
489 if (!DeclVarData)
490 return;
492 E = DeclVarData->second;
493 FD = DeclVarData->first;
495 if (auto *VariantDRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts())) {
496 if (auto *VariantFD = dyn_cast<FunctionDecl>(VariantDRE->getDecl())) {
497 if (auto *VariantFTD = VariantFD->getDescribedFunctionTemplate()) {
498 if (!VariantFTD->isThisDeclarationADefinition())
499 return;
500 Sema::TentativeAnalysisScope Trap(S);
501 const TemplateArgumentList *TAL = TemplateArgumentList::CreateCopy(
502 S.Context, TemplateArgs.getInnermost());
504 auto *SubstFD = S.InstantiateFunctionDeclaration(VariantFTD, TAL,
505 New->getLocation());
506 if (!SubstFD)
507 return;
508 QualType NewType = S.Context.mergeFunctionTypes(
509 SubstFD->getType(), FD->getType(),
510 /* OfBlockPointer */ false,
511 /* Unqualified */ false, /* AllowCXX */ true);
512 if (NewType.isNull())
513 return;
514 S.InstantiateFunctionDefinition(
515 New->getLocation(), SubstFD, /* Recursive */ true,
516 /* DefinitionRequired */ false, /* AtEndOfTU */ false);
517 SubstFD->setInstantiationIsPending(!SubstFD->isDefined());
518 E = DeclRefExpr::Create(S.Context, NestedNameSpecifierLoc(),
519 SourceLocation(), SubstFD,
520 /* RefersToEnclosingVariableOrCapture */ false,
521 /* NameLoc */ SubstFD->getLocation(),
522 SubstFD->getType(), ExprValueKind::VK_PRValue);
527 SmallVector<Expr *, 8> NothingExprs;
528 SmallVector<Expr *, 8> NeedDevicePtrExprs;
529 SmallVector<OMPInteropInfo, 4> AppendArgs;
531 for (Expr *E : Attr.adjustArgsNothing()) {
532 ExprResult ER = Subst(E);
533 if (ER.isInvalid())
534 continue;
535 NothingExprs.push_back(ER.get());
537 for (Expr *E : Attr.adjustArgsNeedDevicePtr()) {
538 ExprResult ER = Subst(E);
539 if (ER.isInvalid())
540 continue;
541 NeedDevicePtrExprs.push_back(ER.get());
543 for (OMPInteropInfo &II : Attr.appendArgs()) {
544 // When prefer_type is implemented for append_args handle them here too.
545 AppendArgs.emplace_back(II.IsTarget, II.IsTargetSync);
548 S.OpenMP().ActOnOpenMPDeclareVariantDirective(
549 FD, E, TI, NothingExprs, NeedDevicePtrExprs, AppendArgs, SourceLocation(),
550 SourceLocation(), Attr.getRange());
553 static void instantiateDependentAMDGPUFlatWorkGroupSizeAttr(
554 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
555 const AMDGPUFlatWorkGroupSizeAttr &Attr, Decl *New) {
556 // Both min and max expression are constant expressions.
557 EnterExpressionEvaluationContext Unevaluated(
558 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
560 ExprResult Result = S.SubstExpr(Attr.getMin(), TemplateArgs);
561 if (Result.isInvalid())
562 return;
563 Expr *MinExpr = Result.getAs<Expr>();
565 Result = S.SubstExpr(Attr.getMax(), TemplateArgs);
566 if (Result.isInvalid())
567 return;
568 Expr *MaxExpr = Result.getAs<Expr>();
570 S.AMDGPU().addAMDGPUFlatWorkGroupSizeAttr(New, Attr, MinExpr, MaxExpr);
573 ExplicitSpecifier Sema::instantiateExplicitSpecifier(
574 const MultiLevelTemplateArgumentList &TemplateArgs, ExplicitSpecifier ES) {
575 if (!ES.getExpr())
576 return ES;
577 Expr *OldCond = ES.getExpr();
578 Expr *Cond = nullptr;
580 EnterExpressionEvaluationContext Unevaluated(
581 *this, Sema::ExpressionEvaluationContext::ConstantEvaluated);
582 ExprResult SubstResult = SubstExpr(OldCond, TemplateArgs);
583 if (SubstResult.isInvalid()) {
584 return ExplicitSpecifier::Invalid();
586 Cond = SubstResult.get();
588 ExplicitSpecifier Result(Cond, ES.getKind());
589 if (!Cond->isTypeDependent())
590 tryResolveExplicitSpecifier(Result);
591 return Result;
594 static void instantiateDependentAMDGPUWavesPerEUAttr(
595 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
596 const AMDGPUWavesPerEUAttr &Attr, Decl *New) {
597 // Both min and max expression are constant expressions.
598 EnterExpressionEvaluationContext Unevaluated(
599 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
601 ExprResult Result = S.SubstExpr(Attr.getMin(), TemplateArgs);
602 if (Result.isInvalid())
603 return;
604 Expr *MinExpr = Result.getAs<Expr>();
606 Expr *MaxExpr = nullptr;
607 if (auto Max = Attr.getMax()) {
608 Result = S.SubstExpr(Max, TemplateArgs);
609 if (Result.isInvalid())
610 return;
611 MaxExpr = Result.getAs<Expr>();
614 S.AMDGPU().addAMDGPUWavesPerEUAttr(New, Attr, MinExpr, MaxExpr);
617 static void instantiateDependentAMDGPUMaxNumWorkGroupsAttr(
618 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
619 const AMDGPUMaxNumWorkGroupsAttr &Attr, Decl *New) {
620 EnterExpressionEvaluationContext Unevaluated(
621 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
623 ExprResult ResultX = S.SubstExpr(Attr.getMaxNumWorkGroupsX(), TemplateArgs);
624 if (!ResultX.isUsable())
625 return;
626 ExprResult ResultY = S.SubstExpr(Attr.getMaxNumWorkGroupsY(), TemplateArgs);
627 if (!ResultY.isUsable())
628 return;
629 ExprResult ResultZ = S.SubstExpr(Attr.getMaxNumWorkGroupsZ(), TemplateArgs);
630 if (!ResultZ.isUsable())
631 return;
633 Expr *XExpr = ResultX.getAs<Expr>();
634 Expr *YExpr = ResultY.getAs<Expr>();
635 Expr *ZExpr = ResultZ.getAs<Expr>();
637 S.AMDGPU().addAMDGPUMaxNumWorkGroupsAttr(New, Attr, XExpr, YExpr, ZExpr);
640 // This doesn't take any template parameters, but we have a custom action that
641 // needs to happen when the kernel itself is instantiated. We need to run the
642 // ItaniumMangler to mark the names required to name this kernel.
643 static void instantiateDependentSYCLKernelAttr(
644 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
645 const SYCLKernelAttr &Attr, Decl *New) {
646 New->addAttr(Attr.clone(S.getASTContext()));
649 /// Determine whether the attribute A might be relevant to the declaration D.
650 /// If not, we can skip instantiating it. The attribute may or may not have
651 /// been instantiated yet.
652 static bool isRelevantAttr(Sema &S, const Decl *D, const Attr *A) {
653 // 'preferred_name' is only relevant to the matching specialization of the
654 // template.
655 if (const auto *PNA = dyn_cast<PreferredNameAttr>(A)) {
656 QualType T = PNA->getTypedefType();
657 const auto *RD = cast<CXXRecordDecl>(D);
658 if (!T->isDependentType() && !RD->isDependentContext() &&
659 !declaresSameEntity(T->getAsCXXRecordDecl(), RD))
660 return false;
661 for (const auto *ExistingPNA : D->specific_attrs<PreferredNameAttr>())
662 if (S.Context.hasSameType(ExistingPNA->getTypedefType(),
663 PNA->getTypedefType()))
664 return false;
665 return true;
668 if (const auto *BA = dyn_cast<BuiltinAttr>(A)) {
669 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
670 switch (BA->getID()) {
671 case Builtin::BIforward:
672 // Do not treat 'std::forward' as a builtin if it takes an rvalue reference
673 // type and returns an lvalue reference type. The library implementation
674 // will produce an error in this case; don't get in its way.
675 if (FD && FD->getNumParams() >= 1 &&
676 FD->getParamDecl(0)->getType()->isRValueReferenceType() &&
677 FD->getReturnType()->isLValueReferenceType()) {
678 return false;
680 [[fallthrough]];
681 case Builtin::BImove:
682 case Builtin::BImove_if_noexcept:
683 // HACK: Super-old versions of libc++ (3.1 and earlier) provide
684 // std::forward and std::move overloads that sometimes return by value
685 // instead of by reference when building in C++98 mode. Don't treat such
686 // cases as builtins.
687 if (FD && !FD->getReturnType()->isReferenceType())
688 return false;
689 break;
693 return true;
696 static void instantiateDependentHLSLParamModifierAttr(
697 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
698 const HLSLParamModifierAttr *Attr, Decl *New) {
699 ParmVarDecl *P = cast<ParmVarDecl>(New);
700 P->addAttr(Attr->clone(S.getASTContext()));
701 P->setType(S.HLSL().getInoutParameterType(P->getType()));
704 void Sema::InstantiateAttrsForDecl(
705 const MultiLevelTemplateArgumentList &TemplateArgs, const Decl *Tmpl,
706 Decl *New, LateInstantiatedAttrVec *LateAttrs,
707 LocalInstantiationScope *OuterMostScope) {
708 if (NamedDecl *ND = dyn_cast<NamedDecl>(New)) {
709 // FIXME: This function is called multiple times for the same template
710 // specialization. We should only instantiate attributes that were added
711 // since the previous instantiation.
712 for (const auto *TmplAttr : Tmpl->attrs()) {
713 if (!isRelevantAttr(*this, New, TmplAttr))
714 continue;
716 // FIXME: If any of the special case versions from InstantiateAttrs become
717 // applicable to template declaration, we'll need to add them here.
718 CXXThisScopeRAII ThisScope(
719 *this, dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext()),
720 Qualifiers(), ND->isCXXInstanceMember());
722 Attr *NewAttr = sema::instantiateTemplateAttributeForDecl(
723 TmplAttr, Context, *this, TemplateArgs);
724 if (NewAttr && isRelevantAttr(*this, New, NewAttr))
725 New->addAttr(NewAttr);
730 static Sema::RetainOwnershipKind
731 attrToRetainOwnershipKind(const Attr *A) {
732 switch (A->getKind()) {
733 case clang::attr::CFConsumed:
734 return Sema::RetainOwnershipKind::CF;
735 case clang::attr::OSConsumed:
736 return Sema::RetainOwnershipKind::OS;
737 case clang::attr::NSConsumed:
738 return Sema::RetainOwnershipKind::NS;
739 default:
740 llvm_unreachable("Wrong argument supplied");
744 void Sema::InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs,
745 const Decl *Tmpl, Decl *New,
746 LateInstantiatedAttrVec *LateAttrs,
747 LocalInstantiationScope *OuterMostScope) {
748 for (const auto *TmplAttr : Tmpl->attrs()) {
749 if (!isRelevantAttr(*this, New, TmplAttr))
750 continue;
752 // FIXME: This should be generalized to more than just the AlignedAttr.
753 const AlignedAttr *Aligned = dyn_cast<AlignedAttr>(TmplAttr);
754 if (Aligned && Aligned->isAlignmentDependent()) {
755 instantiateDependentAlignedAttr(*this, TemplateArgs, Aligned, New);
756 continue;
759 if (const auto *AssumeAligned = dyn_cast<AssumeAlignedAttr>(TmplAttr)) {
760 instantiateDependentAssumeAlignedAttr(*this, TemplateArgs, AssumeAligned, New);
761 continue;
764 if (const auto *AlignValue = dyn_cast<AlignValueAttr>(TmplAttr)) {
765 instantiateDependentAlignValueAttr(*this, TemplateArgs, AlignValue, New);
766 continue;
769 if (const auto *AllocAlign = dyn_cast<AllocAlignAttr>(TmplAttr)) {
770 instantiateDependentAllocAlignAttr(*this, TemplateArgs, AllocAlign, New);
771 continue;
774 if (const auto *Annotate = dyn_cast<AnnotateAttr>(TmplAttr)) {
775 instantiateDependentAnnotationAttr(*this, TemplateArgs, Annotate, New);
776 continue;
779 if (const auto *EnableIf = dyn_cast<EnableIfAttr>(TmplAttr)) {
780 instantiateDependentEnableIfAttr(*this, TemplateArgs, EnableIf, Tmpl,
781 cast<FunctionDecl>(New));
782 continue;
785 if (const auto *DiagnoseIf = dyn_cast<DiagnoseIfAttr>(TmplAttr)) {
786 instantiateDependentDiagnoseIfAttr(*this, TemplateArgs, DiagnoseIf, Tmpl,
787 cast<FunctionDecl>(New));
788 continue;
791 if (const auto *CUDALaunchBounds =
792 dyn_cast<CUDALaunchBoundsAttr>(TmplAttr)) {
793 instantiateDependentCUDALaunchBoundsAttr(*this, TemplateArgs,
794 *CUDALaunchBounds, New);
795 continue;
798 if (const auto *Mode = dyn_cast<ModeAttr>(TmplAttr)) {
799 instantiateDependentModeAttr(*this, TemplateArgs, *Mode, New);
800 continue;
803 if (const auto *OMPAttr = dyn_cast<OMPDeclareSimdDeclAttr>(TmplAttr)) {
804 instantiateOMPDeclareSimdDeclAttr(*this, TemplateArgs, *OMPAttr, New);
805 continue;
808 if (const auto *OMPAttr = dyn_cast<OMPDeclareVariantAttr>(TmplAttr)) {
809 instantiateOMPDeclareVariantAttr(*this, TemplateArgs, *OMPAttr, New);
810 continue;
813 if (const auto *AMDGPUFlatWorkGroupSize =
814 dyn_cast<AMDGPUFlatWorkGroupSizeAttr>(TmplAttr)) {
815 instantiateDependentAMDGPUFlatWorkGroupSizeAttr(
816 *this, TemplateArgs, *AMDGPUFlatWorkGroupSize, New);
819 if (const auto *AMDGPUFlatWorkGroupSize =
820 dyn_cast<AMDGPUWavesPerEUAttr>(TmplAttr)) {
821 instantiateDependentAMDGPUWavesPerEUAttr(*this, TemplateArgs,
822 *AMDGPUFlatWorkGroupSize, New);
825 if (const auto *AMDGPUMaxNumWorkGroups =
826 dyn_cast<AMDGPUMaxNumWorkGroupsAttr>(TmplAttr)) {
827 instantiateDependentAMDGPUMaxNumWorkGroupsAttr(
828 *this, TemplateArgs, *AMDGPUMaxNumWorkGroups, New);
831 if (const auto *ParamAttr = dyn_cast<HLSLParamModifierAttr>(TmplAttr)) {
832 instantiateDependentHLSLParamModifierAttr(*this, TemplateArgs, ParamAttr,
833 New);
834 continue;
837 // Existing DLL attribute on the instantiation takes precedence.
838 if (TmplAttr->getKind() == attr::DLLExport ||
839 TmplAttr->getKind() == attr::DLLImport) {
840 if (New->hasAttr<DLLExportAttr>() || New->hasAttr<DLLImportAttr>()) {
841 continue;
845 if (const auto *ABIAttr = dyn_cast<ParameterABIAttr>(TmplAttr)) {
846 Swift().AddParameterABIAttr(New, *ABIAttr, ABIAttr->getABI());
847 continue;
850 if (isa<NSConsumedAttr>(TmplAttr) || isa<OSConsumedAttr>(TmplAttr) ||
851 isa<CFConsumedAttr>(TmplAttr)) {
852 ObjC().AddXConsumedAttr(New, *TmplAttr,
853 attrToRetainOwnershipKind(TmplAttr),
854 /*template instantiation=*/true);
855 continue;
858 if (auto *A = dyn_cast<PointerAttr>(TmplAttr)) {
859 if (!New->hasAttr<PointerAttr>())
860 New->addAttr(A->clone(Context));
861 continue;
864 if (auto *A = dyn_cast<OwnerAttr>(TmplAttr)) {
865 if (!New->hasAttr<OwnerAttr>())
866 New->addAttr(A->clone(Context));
867 continue;
870 if (auto *A = dyn_cast<SYCLKernelAttr>(TmplAttr)) {
871 instantiateDependentSYCLKernelAttr(*this, TemplateArgs, *A, New);
872 continue;
875 if (auto *A = dyn_cast<CUDAGridConstantAttr>(TmplAttr)) {
876 if (!New->hasAttr<CUDAGridConstantAttr>())
877 New->addAttr(A->clone(Context));
878 continue;
881 assert(!TmplAttr->isPackExpansion());
882 if (TmplAttr->isLateParsed() && LateAttrs) {
883 // Late parsed attributes must be instantiated and attached after the
884 // enclosing class has been instantiated. See Sema::InstantiateClass.
885 LocalInstantiationScope *Saved = nullptr;
886 if (CurrentInstantiationScope)
887 Saved = CurrentInstantiationScope->cloneScopes(OuterMostScope);
888 LateAttrs->push_back(LateInstantiatedAttribute(TmplAttr, Saved, New));
889 } else {
890 // Allow 'this' within late-parsed attributes.
891 auto *ND = cast<NamedDecl>(New);
892 auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext());
893 CXXThisScopeRAII ThisScope(*this, ThisContext, Qualifiers(),
894 ND->isCXXInstanceMember());
896 Attr *NewAttr = sema::instantiateTemplateAttribute(TmplAttr, Context,
897 *this, TemplateArgs);
898 if (NewAttr && isRelevantAttr(*this, New, TmplAttr))
899 New->addAttr(NewAttr);
904 void Sema::updateAttrsForLateParsedTemplate(const Decl *Pattern, Decl *Inst) {
905 for (const auto *Attr : Pattern->attrs()) {
906 if (auto *A = dyn_cast<StrictFPAttr>(Attr)) {
907 if (!Inst->hasAttr<StrictFPAttr>())
908 Inst->addAttr(A->clone(getASTContext()));
909 continue;
914 void Sema::InstantiateDefaultCtorDefaultArgs(CXXConstructorDecl *Ctor) {
915 assert(Context.getTargetInfo().getCXXABI().isMicrosoft() &&
916 Ctor->isDefaultConstructor());
917 unsigned NumParams = Ctor->getNumParams();
918 if (NumParams == 0)
919 return;
920 DLLExportAttr *Attr = Ctor->getAttr<DLLExportAttr>();
921 if (!Attr)
922 return;
923 for (unsigned I = 0; I != NumParams; ++I) {
924 (void)CheckCXXDefaultArgExpr(Attr->getLocation(), Ctor,
925 Ctor->getParamDecl(I));
926 CleanupVarDeclMarking();
930 /// Get the previous declaration of a declaration for the purposes of template
931 /// instantiation. If this finds a previous declaration, then the previous
932 /// declaration of the instantiation of D should be an instantiation of the
933 /// result of this function.
934 template<typename DeclT>
935 static DeclT *getPreviousDeclForInstantiation(DeclT *D) {
936 DeclT *Result = D->getPreviousDecl();
938 // If the declaration is within a class, and the previous declaration was
939 // merged from a different definition of that class, then we don't have a
940 // previous declaration for the purpose of template instantiation.
941 if (Result && isa<CXXRecordDecl>(D->getDeclContext()) &&
942 D->getLexicalDeclContext() != Result->getLexicalDeclContext())
943 return nullptr;
945 return Result;
948 Decl *
949 TemplateDeclInstantiator::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
950 llvm_unreachable("Translation units cannot be instantiated");
953 Decl *TemplateDeclInstantiator::VisitHLSLBufferDecl(HLSLBufferDecl *Decl) {
954 llvm_unreachable("HLSL buffer declarations cannot be instantiated");
957 Decl *
958 TemplateDeclInstantiator::VisitPragmaCommentDecl(PragmaCommentDecl *D) {
959 llvm_unreachable("pragma comment cannot be instantiated");
962 Decl *TemplateDeclInstantiator::VisitPragmaDetectMismatchDecl(
963 PragmaDetectMismatchDecl *D) {
964 llvm_unreachable("pragma comment cannot be instantiated");
967 Decl *
968 TemplateDeclInstantiator::VisitExternCContextDecl(ExternCContextDecl *D) {
969 llvm_unreachable("extern \"C\" context cannot be instantiated");
972 Decl *TemplateDeclInstantiator::VisitMSGuidDecl(MSGuidDecl *D) {
973 llvm_unreachable("GUID declaration cannot be instantiated");
976 Decl *TemplateDeclInstantiator::VisitUnnamedGlobalConstantDecl(
977 UnnamedGlobalConstantDecl *D) {
978 llvm_unreachable("UnnamedGlobalConstantDecl cannot be instantiated");
981 Decl *TemplateDeclInstantiator::VisitTemplateParamObjectDecl(
982 TemplateParamObjectDecl *D) {
983 llvm_unreachable("template parameter objects cannot be instantiated");
986 Decl *
987 TemplateDeclInstantiator::VisitLabelDecl(LabelDecl *D) {
988 LabelDecl *Inst = LabelDecl::Create(SemaRef.Context, Owner, D->getLocation(),
989 D->getIdentifier());
990 SemaRef.InstantiateAttrs(TemplateArgs, D, Inst, LateAttrs, StartingScope);
991 Owner->addDecl(Inst);
992 return Inst;
995 Decl *
996 TemplateDeclInstantiator::VisitNamespaceDecl(NamespaceDecl *D) {
997 llvm_unreachable("Namespaces cannot be instantiated");
1000 Decl *
1001 TemplateDeclInstantiator::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
1002 NamespaceAliasDecl *Inst
1003 = NamespaceAliasDecl::Create(SemaRef.Context, Owner,
1004 D->getNamespaceLoc(),
1005 D->getAliasLoc(),
1006 D->getIdentifier(),
1007 D->getQualifierLoc(),
1008 D->getTargetNameLoc(),
1009 D->getNamespace());
1010 Owner->addDecl(Inst);
1011 return Inst;
1014 Decl *TemplateDeclInstantiator::InstantiateTypedefNameDecl(TypedefNameDecl *D,
1015 bool IsTypeAlias) {
1016 bool Invalid = false;
1017 TypeSourceInfo *DI = D->getTypeSourceInfo();
1018 if (DI->getType()->isInstantiationDependentType() ||
1019 DI->getType()->isVariablyModifiedType()) {
1020 DI = SemaRef.SubstType(DI, TemplateArgs,
1021 D->getLocation(), D->getDeclName());
1022 if (!DI) {
1023 Invalid = true;
1024 DI = SemaRef.Context.getTrivialTypeSourceInfo(SemaRef.Context.IntTy);
1026 } else {
1027 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
1030 // HACK: 2012-10-23 g++ has a bug where it gets the value kind of ?: wrong.
1031 // libstdc++ relies upon this bug in its implementation of common_type. If we
1032 // happen to be processing that implementation, fake up the g++ ?:
1033 // semantics. See LWG issue 2141 for more information on the bug. The bugs
1034 // are fixed in g++ and libstdc++ 4.9.0 (2014-04-22).
1035 const DecltypeType *DT = DI->getType()->getAs<DecltypeType>();
1036 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D->getDeclContext());
1037 if (DT && RD && isa<ConditionalOperator>(DT->getUnderlyingExpr()) &&
1038 DT->isReferenceType() &&
1039 RD->getEnclosingNamespaceContext() == SemaRef.getStdNamespace() &&
1040 RD->getIdentifier() && RD->getIdentifier()->isStr("common_type") &&
1041 D->getIdentifier() && D->getIdentifier()->isStr("type") &&
1042 SemaRef.getSourceManager().isInSystemHeader(D->getBeginLoc()))
1043 // Fold it to the (non-reference) type which g++ would have produced.
1044 DI = SemaRef.Context.getTrivialTypeSourceInfo(
1045 DI->getType().getNonReferenceType());
1047 // Create the new typedef
1048 TypedefNameDecl *Typedef;
1049 if (IsTypeAlias)
1050 Typedef = TypeAliasDecl::Create(SemaRef.Context, Owner, D->getBeginLoc(),
1051 D->getLocation(), D->getIdentifier(), DI);
1052 else
1053 Typedef = TypedefDecl::Create(SemaRef.Context, Owner, D->getBeginLoc(),
1054 D->getLocation(), D->getIdentifier(), DI);
1055 if (Invalid)
1056 Typedef->setInvalidDecl();
1058 // If the old typedef was the name for linkage purposes of an anonymous
1059 // tag decl, re-establish that relationship for the new typedef.
1060 if (const TagType *oldTagType = D->getUnderlyingType()->getAs<TagType>()) {
1061 TagDecl *oldTag = oldTagType->getDecl();
1062 if (oldTag->getTypedefNameForAnonDecl() == D && !Invalid) {
1063 TagDecl *newTag = DI->getType()->castAs<TagType>()->getDecl();
1064 assert(!newTag->hasNameForLinkage());
1065 newTag->setTypedefNameForAnonDecl(Typedef);
1069 if (TypedefNameDecl *Prev = getPreviousDeclForInstantiation(D)) {
1070 NamedDecl *InstPrev = SemaRef.FindInstantiatedDecl(D->getLocation(), Prev,
1071 TemplateArgs);
1072 if (!InstPrev)
1073 return nullptr;
1075 TypedefNameDecl *InstPrevTypedef = cast<TypedefNameDecl>(InstPrev);
1077 // If the typedef types are not identical, reject them.
1078 SemaRef.isIncompatibleTypedef(InstPrevTypedef, Typedef);
1080 Typedef->setPreviousDecl(InstPrevTypedef);
1083 SemaRef.InstantiateAttrs(TemplateArgs, D, Typedef);
1085 if (D->getUnderlyingType()->getAs<DependentNameType>())
1086 SemaRef.inferGslPointerAttribute(Typedef);
1088 Typedef->setAccess(D->getAccess());
1089 Typedef->setReferenced(D->isReferenced());
1091 return Typedef;
1094 Decl *TemplateDeclInstantiator::VisitTypedefDecl(TypedefDecl *D) {
1095 Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/false);
1096 if (Typedef)
1097 Owner->addDecl(Typedef);
1098 return Typedef;
1101 Decl *TemplateDeclInstantiator::VisitTypeAliasDecl(TypeAliasDecl *D) {
1102 Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/true);
1103 if (Typedef)
1104 Owner->addDecl(Typedef);
1105 return Typedef;
1108 Decl *TemplateDeclInstantiator::InstantiateTypeAliasTemplateDecl(
1109 TypeAliasTemplateDecl *D) {
1110 // Create a local instantiation scope for this type alias template, which
1111 // will contain the instantiations of the template parameters.
1112 LocalInstantiationScope Scope(SemaRef);
1114 TemplateParameterList *TempParams = D->getTemplateParameters();
1115 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1116 if (!InstParams)
1117 return nullptr;
1119 TypeAliasDecl *Pattern = D->getTemplatedDecl();
1120 Sema::InstantiatingTemplate InstTemplate(
1121 SemaRef, D->getBeginLoc(), D,
1122 D->getTemplateDepth() >= TemplateArgs.getNumLevels()
1123 ? ArrayRef<TemplateArgument>()
1124 : (TemplateArgs.begin() + TemplateArgs.getNumLevels() - 1 -
1125 D->getTemplateDepth())
1126 ->Args);
1127 if (InstTemplate.isInvalid())
1128 return nullptr;
1130 TypeAliasTemplateDecl *PrevAliasTemplate = nullptr;
1131 if (getPreviousDeclForInstantiation<TypedefNameDecl>(Pattern)) {
1132 DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
1133 if (!Found.empty()) {
1134 PrevAliasTemplate = dyn_cast<TypeAliasTemplateDecl>(Found.front());
1138 TypeAliasDecl *AliasInst = cast_or_null<TypeAliasDecl>(
1139 InstantiateTypedefNameDecl(Pattern, /*IsTypeAlias=*/true));
1140 if (!AliasInst)
1141 return nullptr;
1143 TypeAliasTemplateDecl *Inst
1144 = TypeAliasTemplateDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1145 D->getDeclName(), InstParams, AliasInst);
1146 AliasInst->setDescribedAliasTemplate(Inst);
1147 if (PrevAliasTemplate)
1148 Inst->setPreviousDecl(PrevAliasTemplate);
1150 Inst->setAccess(D->getAccess());
1152 if (!PrevAliasTemplate)
1153 Inst->setInstantiatedFromMemberTemplate(D);
1155 return Inst;
1158 Decl *
1159 TemplateDeclInstantiator::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) {
1160 Decl *Inst = InstantiateTypeAliasTemplateDecl(D);
1161 if (Inst)
1162 Owner->addDecl(Inst);
1164 return Inst;
1167 Decl *TemplateDeclInstantiator::VisitBindingDecl(BindingDecl *D) {
1168 auto *NewBD = BindingDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1169 D->getIdentifier());
1170 NewBD->setReferenced(D->isReferenced());
1171 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewBD);
1172 return NewBD;
1175 Decl *TemplateDeclInstantiator::VisitDecompositionDecl(DecompositionDecl *D) {
1176 // Transform the bindings first.
1177 SmallVector<BindingDecl*, 16> NewBindings;
1178 for (auto *OldBD : D->bindings())
1179 NewBindings.push_back(cast<BindingDecl>(VisitBindingDecl(OldBD)));
1180 ArrayRef<BindingDecl*> NewBindingArray = NewBindings;
1182 auto *NewDD = cast_or_null<DecompositionDecl>(
1183 VisitVarDecl(D, /*InstantiatingVarTemplate=*/false, &NewBindingArray));
1185 if (!NewDD || NewDD->isInvalidDecl())
1186 for (auto *NewBD : NewBindings)
1187 NewBD->setInvalidDecl();
1189 return NewDD;
1192 Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D) {
1193 return VisitVarDecl(D, /*InstantiatingVarTemplate=*/false);
1196 Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D,
1197 bool InstantiatingVarTemplate,
1198 ArrayRef<BindingDecl*> *Bindings) {
1200 // Do substitution on the type of the declaration
1201 TypeSourceInfo *DI = SemaRef.SubstType(
1202 D->getTypeSourceInfo(), TemplateArgs, D->getTypeSpecStartLoc(),
1203 D->getDeclName(), /*AllowDeducedTST*/true);
1204 if (!DI)
1205 return nullptr;
1207 if (DI->getType()->isFunctionType()) {
1208 SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function)
1209 << D->isStaticDataMember() << DI->getType();
1210 return nullptr;
1213 DeclContext *DC = Owner;
1214 if (D->isLocalExternDecl())
1215 SemaRef.adjustContextForLocalExternDecl(DC);
1217 // Build the instantiated declaration.
1218 VarDecl *Var;
1219 if (Bindings)
1220 Var = DecompositionDecl::Create(SemaRef.Context, DC, D->getInnerLocStart(),
1221 D->getLocation(), DI->getType(), DI,
1222 D->getStorageClass(), *Bindings);
1223 else
1224 Var = VarDecl::Create(SemaRef.Context, DC, D->getInnerLocStart(),
1225 D->getLocation(), D->getIdentifier(), DI->getType(),
1226 DI, D->getStorageClass());
1228 // In ARC, infer 'retaining' for variables of retainable type.
1229 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
1230 SemaRef.ObjC().inferObjCARCLifetime(Var))
1231 Var->setInvalidDecl();
1233 if (SemaRef.getLangOpts().OpenCL)
1234 SemaRef.deduceOpenCLAddressSpace(Var);
1236 // Substitute the nested name specifier, if any.
1237 if (SubstQualifier(D, Var))
1238 return nullptr;
1240 SemaRef.BuildVariableInstantiation(Var, D, TemplateArgs, LateAttrs, Owner,
1241 StartingScope, InstantiatingVarTemplate);
1242 if (D->isNRVOVariable() && !Var->isInvalidDecl()) {
1243 QualType RT;
1244 if (auto *F = dyn_cast<FunctionDecl>(DC))
1245 RT = F->getReturnType();
1246 else if (isa<BlockDecl>(DC))
1247 RT = cast<FunctionType>(SemaRef.getCurBlock()->FunctionType)
1248 ->getReturnType();
1249 else
1250 llvm_unreachable("Unknown context type");
1252 // This is the last chance we have of checking copy elision eligibility
1253 // for functions in dependent contexts. The sema actions for building
1254 // the return statement during template instantiation will have no effect
1255 // regarding copy elision, since NRVO propagation runs on the scope exit
1256 // actions, and these are not run on instantiation.
1257 // This might run through some VarDecls which were returned from non-taken
1258 // 'if constexpr' branches, and these will end up being constructed on the
1259 // return slot even if they will never be returned, as a sort of accidental
1260 // 'optimization'. Notably, functions with 'auto' return types won't have it
1261 // deduced by this point. Coupled with the limitation described
1262 // previously, this makes it very hard to support copy elision for these.
1263 Sema::NamedReturnInfo Info = SemaRef.getNamedReturnInfo(Var);
1264 bool NRVO = SemaRef.getCopyElisionCandidate(Info, RT) != nullptr;
1265 Var->setNRVOVariable(NRVO);
1268 Var->setImplicit(D->isImplicit());
1270 if (Var->isStaticLocal())
1271 SemaRef.CheckStaticLocalForDllExport(Var);
1273 if (Var->getTLSKind())
1274 SemaRef.CheckThreadLocalForLargeAlignment(Var);
1276 return Var;
1279 Decl *TemplateDeclInstantiator::VisitAccessSpecDecl(AccessSpecDecl *D) {
1280 AccessSpecDecl* AD
1281 = AccessSpecDecl::Create(SemaRef.Context, D->getAccess(), Owner,
1282 D->getAccessSpecifierLoc(), D->getColonLoc());
1283 Owner->addHiddenDecl(AD);
1284 return AD;
1287 Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) {
1288 bool Invalid = false;
1289 TypeSourceInfo *DI = D->getTypeSourceInfo();
1290 if (DI->getType()->isInstantiationDependentType() ||
1291 DI->getType()->isVariablyModifiedType()) {
1292 DI = SemaRef.SubstType(DI, TemplateArgs,
1293 D->getLocation(), D->getDeclName());
1294 if (!DI) {
1295 DI = D->getTypeSourceInfo();
1296 Invalid = true;
1297 } else if (DI->getType()->isFunctionType()) {
1298 // C++ [temp.arg.type]p3:
1299 // If a declaration acquires a function type through a type
1300 // dependent on a template-parameter and this causes a
1301 // declaration that does not use the syntactic form of a
1302 // function declarator to have function type, the program is
1303 // ill-formed.
1304 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
1305 << DI->getType();
1306 Invalid = true;
1308 } else {
1309 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
1312 Expr *BitWidth = D->getBitWidth();
1313 if (Invalid)
1314 BitWidth = nullptr;
1315 else if (BitWidth) {
1316 // The bit-width expression is a constant expression.
1317 EnterExpressionEvaluationContext Unevaluated(
1318 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
1320 ExprResult InstantiatedBitWidth
1321 = SemaRef.SubstExpr(BitWidth, TemplateArgs);
1322 if (InstantiatedBitWidth.isInvalid()) {
1323 Invalid = true;
1324 BitWidth = nullptr;
1325 } else
1326 BitWidth = InstantiatedBitWidth.getAs<Expr>();
1329 FieldDecl *Field = SemaRef.CheckFieldDecl(D->getDeclName(),
1330 DI->getType(), DI,
1331 cast<RecordDecl>(Owner),
1332 D->getLocation(),
1333 D->isMutable(),
1334 BitWidth,
1335 D->getInClassInitStyle(),
1336 D->getInnerLocStart(),
1337 D->getAccess(),
1338 nullptr);
1339 if (!Field) {
1340 cast<Decl>(Owner)->setInvalidDecl();
1341 return nullptr;
1344 SemaRef.InstantiateAttrs(TemplateArgs, D, Field, LateAttrs, StartingScope);
1346 if (Field->hasAttrs())
1347 SemaRef.CheckAlignasUnderalignment(Field);
1349 if (Invalid)
1350 Field->setInvalidDecl();
1352 if (!Field->getDeclName() || Field->isPlaceholderVar(SemaRef.getLangOpts())) {
1353 // Keep track of where this decl came from.
1354 SemaRef.Context.setInstantiatedFromUnnamedFieldDecl(Field, D);
1356 if (CXXRecordDecl *Parent= dyn_cast<CXXRecordDecl>(Field->getDeclContext())) {
1357 if (Parent->isAnonymousStructOrUnion() &&
1358 Parent->getRedeclContext()->isFunctionOrMethod())
1359 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Field);
1362 Field->setImplicit(D->isImplicit());
1363 Field->setAccess(D->getAccess());
1364 Owner->addDecl(Field);
1366 return Field;
1369 Decl *TemplateDeclInstantiator::VisitMSPropertyDecl(MSPropertyDecl *D) {
1370 bool Invalid = false;
1371 TypeSourceInfo *DI = D->getTypeSourceInfo();
1373 if (DI->getType()->isVariablyModifiedType()) {
1374 SemaRef.Diag(D->getLocation(), diag::err_property_is_variably_modified)
1375 << D;
1376 Invalid = true;
1377 } else if (DI->getType()->isInstantiationDependentType()) {
1378 DI = SemaRef.SubstType(DI, TemplateArgs,
1379 D->getLocation(), D->getDeclName());
1380 if (!DI) {
1381 DI = D->getTypeSourceInfo();
1382 Invalid = true;
1383 } else if (DI->getType()->isFunctionType()) {
1384 // C++ [temp.arg.type]p3:
1385 // If a declaration acquires a function type through a type
1386 // dependent on a template-parameter and this causes a
1387 // declaration that does not use the syntactic form of a
1388 // function declarator to have function type, the program is
1389 // ill-formed.
1390 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
1391 << DI->getType();
1392 Invalid = true;
1394 } else {
1395 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
1398 MSPropertyDecl *Property = MSPropertyDecl::Create(
1399 SemaRef.Context, Owner, D->getLocation(), D->getDeclName(), DI->getType(),
1400 DI, D->getBeginLoc(), D->getGetterId(), D->getSetterId());
1402 SemaRef.InstantiateAttrs(TemplateArgs, D, Property, LateAttrs,
1403 StartingScope);
1405 if (Invalid)
1406 Property->setInvalidDecl();
1408 Property->setAccess(D->getAccess());
1409 Owner->addDecl(Property);
1411 return Property;
1414 Decl *TemplateDeclInstantiator::VisitIndirectFieldDecl(IndirectFieldDecl *D) {
1415 NamedDecl **NamedChain =
1416 new (SemaRef.Context)NamedDecl*[D->getChainingSize()];
1418 int i = 0;
1419 for (auto *PI : D->chain()) {
1420 NamedDecl *Next = SemaRef.FindInstantiatedDecl(D->getLocation(), PI,
1421 TemplateArgs);
1422 if (!Next)
1423 return nullptr;
1425 NamedChain[i++] = Next;
1428 QualType T = cast<FieldDecl>(NamedChain[i-1])->getType();
1429 IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
1430 SemaRef.Context, Owner, D->getLocation(), D->getIdentifier(), T,
1431 {NamedChain, D->getChainingSize()});
1433 for (const auto *Attr : D->attrs())
1434 IndirectField->addAttr(Attr->clone(SemaRef.Context));
1436 IndirectField->setImplicit(D->isImplicit());
1437 IndirectField->setAccess(D->getAccess());
1438 Owner->addDecl(IndirectField);
1439 return IndirectField;
1442 Decl *TemplateDeclInstantiator::VisitFriendDecl(FriendDecl *D) {
1443 // Handle friend type expressions by simply substituting template
1444 // parameters into the pattern type and checking the result.
1445 if (TypeSourceInfo *Ty = D->getFriendType()) {
1446 TypeSourceInfo *InstTy;
1447 // If this is an unsupported friend, don't bother substituting template
1448 // arguments into it. The actual type referred to won't be used by any
1449 // parts of Clang, and may not be valid for instantiating. Just use the
1450 // same info for the instantiated friend.
1451 if (D->isUnsupportedFriend()) {
1452 InstTy = Ty;
1453 } else {
1454 if (D->isPackExpansion()) {
1455 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
1456 SemaRef.collectUnexpandedParameterPacks(Ty->getTypeLoc(), Unexpanded);
1457 assert(!Unexpanded.empty() && "Pack expansion without packs");
1459 bool ShouldExpand = true;
1460 bool RetainExpansion = false;
1461 std::optional<unsigned> NumExpansions;
1462 if (SemaRef.CheckParameterPacksForExpansion(
1463 D->getEllipsisLoc(), D->getSourceRange(), Unexpanded,
1464 TemplateArgs, ShouldExpand, RetainExpansion, NumExpansions))
1465 return nullptr;
1467 assert(!RetainExpansion &&
1468 "should never retain an expansion for a variadic friend decl");
1470 if (ShouldExpand) {
1471 SmallVector<FriendDecl *> Decls;
1472 for (unsigned I = 0; I != *NumExpansions; I++) {
1473 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
1474 TypeSourceInfo *TSI = SemaRef.SubstType(
1475 Ty, TemplateArgs, D->getEllipsisLoc(), DeclarationName());
1476 if (!TSI)
1477 return nullptr;
1479 auto FD =
1480 FriendDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1481 TSI, D->getFriendLoc());
1483 FD->setAccess(AS_public);
1484 Owner->addDecl(FD);
1485 Decls.push_back(FD);
1488 // Just drop this node; we have no use for it anymore.
1489 return nullptr;
1493 InstTy = SemaRef.SubstType(Ty, TemplateArgs, D->getLocation(),
1494 DeclarationName());
1496 if (!InstTy)
1497 return nullptr;
1499 FriendDecl *FD = FriendDecl::Create(
1500 SemaRef.Context, Owner, D->getLocation(), InstTy, D->getFriendLoc());
1501 FD->setAccess(AS_public);
1502 FD->setUnsupportedFriend(D->isUnsupportedFriend());
1503 Owner->addDecl(FD);
1504 return FD;
1507 NamedDecl *ND = D->getFriendDecl();
1508 assert(ND && "friend decl must be a decl or a type!");
1510 // All of the Visit implementations for the various potential friend
1511 // declarations have to be carefully written to work for friend
1512 // objects, with the most important detail being that the target
1513 // decl should almost certainly not be placed in Owner.
1514 Decl *NewND = Visit(ND);
1515 if (!NewND) return nullptr;
1517 FriendDecl *FD =
1518 FriendDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1519 cast<NamedDecl>(NewND), D->getFriendLoc());
1520 FD->setAccess(AS_public);
1521 FD->setUnsupportedFriend(D->isUnsupportedFriend());
1522 Owner->addDecl(FD);
1523 return FD;
1526 Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) {
1527 Expr *AssertExpr = D->getAssertExpr();
1529 // The expression in a static assertion is a constant expression.
1530 EnterExpressionEvaluationContext Unevaluated(
1531 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
1533 ExprResult InstantiatedAssertExpr
1534 = SemaRef.SubstExpr(AssertExpr, TemplateArgs);
1535 if (InstantiatedAssertExpr.isInvalid())
1536 return nullptr;
1538 ExprResult InstantiatedMessageExpr =
1539 SemaRef.SubstExpr(D->getMessage(), TemplateArgs);
1540 if (InstantiatedMessageExpr.isInvalid())
1541 return nullptr;
1543 return SemaRef.BuildStaticAssertDeclaration(
1544 D->getLocation(), InstantiatedAssertExpr.get(),
1545 InstantiatedMessageExpr.get(), D->getRParenLoc(), D->isFailed());
1548 Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) {
1549 EnumDecl *PrevDecl = nullptr;
1550 if (EnumDecl *PatternPrev = getPreviousDeclForInstantiation(D)) {
1551 NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
1552 PatternPrev,
1553 TemplateArgs);
1554 if (!Prev) return nullptr;
1555 PrevDecl = cast<EnumDecl>(Prev);
1558 EnumDecl *Enum =
1559 EnumDecl::Create(SemaRef.Context, Owner, D->getBeginLoc(),
1560 D->getLocation(), D->getIdentifier(), PrevDecl,
1561 D->isScoped(), D->isScopedUsingClassTag(), D->isFixed());
1562 if (D->isFixed()) {
1563 if (TypeSourceInfo *TI = D->getIntegerTypeSourceInfo()) {
1564 // If we have type source information for the underlying type, it means it
1565 // has been explicitly set by the user. Perform substitution on it before
1566 // moving on.
1567 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
1568 TypeSourceInfo *NewTI = SemaRef.SubstType(TI, TemplateArgs, UnderlyingLoc,
1569 DeclarationName());
1570 if (!NewTI || SemaRef.CheckEnumUnderlyingType(NewTI))
1571 Enum->setIntegerType(SemaRef.Context.IntTy);
1572 else
1573 Enum->setIntegerTypeSourceInfo(NewTI);
1574 } else {
1575 assert(!D->getIntegerType()->isDependentType()
1576 && "Dependent type without type source info");
1577 Enum->setIntegerType(D->getIntegerType());
1581 SemaRef.InstantiateAttrs(TemplateArgs, D, Enum);
1583 Enum->setInstantiationOfMemberEnum(D, TSK_ImplicitInstantiation);
1584 Enum->setAccess(D->getAccess());
1585 // Forward the mangling number from the template to the instantiated decl.
1586 SemaRef.Context.setManglingNumber(Enum, SemaRef.Context.getManglingNumber(D));
1587 // See if the old tag was defined along with a declarator.
1588 // If it did, mark the new tag as being associated with that declarator.
1589 if (DeclaratorDecl *DD = SemaRef.Context.getDeclaratorForUnnamedTagDecl(D))
1590 SemaRef.Context.addDeclaratorForUnnamedTagDecl(Enum, DD);
1591 // See if the old tag was defined along with a typedef.
1592 // If it did, mark the new tag as being associated with that typedef.
1593 if (TypedefNameDecl *TND = SemaRef.Context.getTypedefNameForUnnamedTagDecl(D))
1594 SemaRef.Context.addTypedefNameForUnnamedTagDecl(Enum, TND);
1595 if (SubstQualifier(D, Enum)) return nullptr;
1596 Owner->addDecl(Enum);
1598 EnumDecl *Def = D->getDefinition();
1599 if (Def && Def != D) {
1600 // If this is an out-of-line definition of an enum member template, check
1601 // that the underlying types match in the instantiation of both
1602 // declarations.
1603 if (TypeSourceInfo *TI = Def->getIntegerTypeSourceInfo()) {
1604 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
1605 QualType DefnUnderlying =
1606 SemaRef.SubstType(TI->getType(), TemplateArgs,
1607 UnderlyingLoc, DeclarationName());
1608 SemaRef.CheckEnumRedeclaration(Def->getLocation(), Def->isScoped(),
1609 DefnUnderlying, /*IsFixed=*/true, Enum);
1613 // C++11 [temp.inst]p1: The implicit instantiation of a class template
1614 // specialization causes the implicit instantiation of the declarations, but
1615 // not the definitions of scoped member enumerations.
1617 // DR1484 clarifies that enumeration definitions inside of a template
1618 // declaration aren't considered entities that can be separately instantiated
1619 // from the rest of the entity they are declared inside of.
1620 if (isDeclWithinFunction(D) ? D == Def : Def && !Enum->isScoped()) {
1621 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Enum);
1622 InstantiateEnumDefinition(Enum, Def);
1625 return Enum;
1628 void TemplateDeclInstantiator::InstantiateEnumDefinition(
1629 EnumDecl *Enum, EnumDecl *Pattern) {
1630 Enum->startDefinition();
1632 // Update the location to refer to the definition.
1633 Enum->setLocation(Pattern->getLocation());
1635 SmallVector<Decl*, 4> Enumerators;
1637 EnumConstantDecl *LastEnumConst = nullptr;
1638 for (auto *EC : Pattern->enumerators()) {
1639 // The specified value for the enumerator.
1640 ExprResult Value((Expr *)nullptr);
1641 if (Expr *UninstValue = EC->getInitExpr()) {
1642 // The enumerator's value expression is a constant expression.
1643 EnterExpressionEvaluationContext Unevaluated(
1644 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
1646 Value = SemaRef.SubstExpr(UninstValue, TemplateArgs);
1649 // Drop the initial value and continue.
1650 bool isInvalid = false;
1651 if (Value.isInvalid()) {
1652 Value = nullptr;
1653 isInvalid = true;
1656 EnumConstantDecl *EnumConst
1657 = SemaRef.CheckEnumConstant(Enum, LastEnumConst,
1658 EC->getLocation(), EC->getIdentifier(),
1659 Value.get());
1661 if (isInvalid) {
1662 if (EnumConst)
1663 EnumConst->setInvalidDecl();
1664 Enum->setInvalidDecl();
1667 if (EnumConst) {
1668 SemaRef.InstantiateAttrs(TemplateArgs, EC, EnumConst);
1670 EnumConst->setAccess(Enum->getAccess());
1671 Enum->addDecl(EnumConst);
1672 Enumerators.push_back(EnumConst);
1673 LastEnumConst = EnumConst;
1675 if (Pattern->getDeclContext()->isFunctionOrMethod() &&
1676 !Enum->isScoped()) {
1677 // If the enumeration is within a function or method, record the enum
1678 // constant as a local.
1679 SemaRef.CurrentInstantiationScope->InstantiatedLocal(EC, EnumConst);
1684 SemaRef.ActOnEnumBody(Enum->getLocation(), Enum->getBraceRange(), Enum,
1685 Enumerators, nullptr, ParsedAttributesView());
1688 Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) {
1689 llvm_unreachable("EnumConstantDecls can only occur within EnumDecls.");
1692 Decl *
1693 TemplateDeclInstantiator::VisitBuiltinTemplateDecl(BuiltinTemplateDecl *D) {
1694 llvm_unreachable("BuiltinTemplateDecls cannot be instantiated.");
1697 Decl *TemplateDeclInstantiator::VisitClassTemplateDecl(ClassTemplateDecl *D) {
1698 bool isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
1700 // Create a local instantiation scope for this class template, which
1701 // will contain the instantiations of the template parameters.
1702 LocalInstantiationScope Scope(SemaRef);
1703 TemplateParameterList *TempParams = D->getTemplateParameters();
1704 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1705 if (!InstParams)
1706 return nullptr;
1708 CXXRecordDecl *Pattern = D->getTemplatedDecl();
1710 // Instantiate the qualifier. We have to do this first in case
1711 // we're a friend declaration, because if we are then we need to put
1712 // the new declaration in the appropriate context.
1713 NestedNameSpecifierLoc QualifierLoc = Pattern->getQualifierLoc();
1714 if (QualifierLoc) {
1715 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
1716 TemplateArgs);
1717 if (!QualifierLoc)
1718 return nullptr;
1721 CXXRecordDecl *PrevDecl = nullptr;
1722 ClassTemplateDecl *PrevClassTemplate = nullptr;
1724 if (!isFriend && getPreviousDeclForInstantiation(Pattern)) {
1725 DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
1726 if (!Found.empty()) {
1727 PrevClassTemplate = dyn_cast<ClassTemplateDecl>(Found.front());
1728 if (PrevClassTemplate)
1729 PrevDecl = PrevClassTemplate->getTemplatedDecl();
1733 // If this isn't a friend, then it's a member template, in which
1734 // case we just want to build the instantiation in the
1735 // specialization. If it is a friend, we want to build it in
1736 // the appropriate context.
1737 DeclContext *DC = Owner;
1738 if (isFriend) {
1739 if (QualifierLoc) {
1740 CXXScopeSpec SS;
1741 SS.Adopt(QualifierLoc);
1742 DC = SemaRef.computeDeclContext(SS);
1743 if (!DC) return nullptr;
1744 } else {
1745 DC = SemaRef.FindInstantiatedContext(Pattern->getLocation(),
1746 Pattern->getDeclContext(),
1747 TemplateArgs);
1750 // Look for a previous declaration of the template in the owning
1751 // context.
1752 LookupResult R(SemaRef, Pattern->getDeclName(), Pattern->getLocation(),
1753 Sema::LookupOrdinaryName,
1754 SemaRef.forRedeclarationInCurContext());
1755 SemaRef.LookupQualifiedName(R, DC);
1757 if (R.isSingleResult()) {
1758 PrevClassTemplate = R.getAsSingle<ClassTemplateDecl>();
1759 if (PrevClassTemplate)
1760 PrevDecl = PrevClassTemplate->getTemplatedDecl();
1763 if (!PrevClassTemplate && QualifierLoc) {
1764 SemaRef.Diag(Pattern->getLocation(), diag::err_not_tag_in_scope)
1765 << llvm::to_underlying(D->getTemplatedDecl()->getTagKind())
1766 << Pattern->getDeclName() << DC << QualifierLoc.getSourceRange();
1767 return nullptr;
1771 CXXRecordDecl *RecordInst = CXXRecordDecl::Create(
1772 SemaRef.Context, Pattern->getTagKind(), DC, Pattern->getBeginLoc(),
1773 Pattern->getLocation(), Pattern->getIdentifier(), PrevDecl,
1774 /*DelayTypeCreation=*/true);
1775 if (QualifierLoc)
1776 RecordInst->setQualifierInfo(QualifierLoc);
1778 SemaRef.InstantiateAttrsForDecl(TemplateArgs, Pattern, RecordInst, LateAttrs,
1779 StartingScope);
1781 ClassTemplateDecl *Inst
1782 = ClassTemplateDecl::Create(SemaRef.Context, DC, D->getLocation(),
1783 D->getIdentifier(), InstParams, RecordInst);
1784 RecordInst->setDescribedClassTemplate(Inst);
1786 if (isFriend) {
1787 assert(!Owner->isDependentContext());
1788 Inst->setLexicalDeclContext(Owner);
1789 RecordInst->setLexicalDeclContext(Owner);
1790 Inst->setObjectOfFriendDecl();
1792 if (PrevClassTemplate) {
1793 Inst->setCommonPtr(PrevClassTemplate->getCommonPtr());
1794 RecordInst->setTypeForDecl(
1795 PrevClassTemplate->getTemplatedDecl()->getTypeForDecl());
1796 const ClassTemplateDecl *MostRecentPrevCT =
1797 PrevClassTemplate->getMostRecentDecl();
1798 TemplateParameterList *PrevParams =
1799 MostRecentPrevCT->getTemplateParameters();
1801 // Make sure the parameter lists match.
1802 if (!SemaRef.TemplateParameterListsAreEqual(
1803 RecordInst, InstParams, MostRecentPrevCT->getTemplatedDecl(),
1804 PrevParams, true, Sema::TPL_TemplateMatch))
1805 return nullptr;
1807 // Do some additional validation, then merge default arguments
1808 // from the existing declarations.
1809 if (SemaRef.CheckTemplateParameterList(InstParams, PrevParams,
1810 Sema::TPC_ClassTemplate))
1811 return nullptr;
1813 Inst->setAccess(PrevClassTemplate->getAccess());
1814 } else {
1815 Inst->setAccess(D->getAccess());
1818 Inst->setObjectOfFriendDecl();
1819 // TODO: do we want to track the instantiation progeny of this
1820 // friend target decl?
1821 } else {
1822 Inst->setAccess(D->getAccess());
1823 if (!PrevClassTemplate)
1824 Inst->setInstantiatedFromMemberTemplate(D);
1827 Inst->setPreviousDecl(PrevClassTemplate);
1829 // Trigger creation of the type for the instantiation.
1830 SemaRef.Context.getInjectedClassNameType(
1831 RecordInst, Inst->getInjectedClassNameSpecialization());
1833 // Finish handling of friends.
1834 if (isFriend) {
1835 DC->makeDeclVisibleInContext(Inst);
1836 return Inst;
1839 if (D->isOutOfLine()) {
1840 Inst->setLexicalDeclContext(D->getLexicalDeclContext());
1841 RecordInst->setLexicalDeclContext(D->getLexicalDeclContext());
1844 Owner->addDecl(Inst);
1846 if (!PrevClassTemplate) {
1847 // Queue up any out-of-line partial specializations of this member
1848 // class template; the client will force their instantiation once
1849 // the enclosing class has been instantiated.
1850 SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
1851 D->getPartialSpecializations(PartialSpecs);
1852 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
1853 if (PartialSpecs[I]->getFirstDecl()->isOutOfLine())
1854 OutOfLinePartialSpecs.push_back(std::make_pair(Inst, PartialSpecs[I]));
1857 return Inst;
1860 Decl *
1861 TemplateDeclInstantiator::VisitClassTemplatePartialSpecializationDecl(
1862 ClassTemplatePartialSpecializationDecl *D) {
1863 ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
1865 // Lookup the already-instantiated declaration in the instantiation
1866 // of the class template and return that.
1867 DeclContext::lookup_result Found
1868 = Owner->lookup(ClassTemplate->getDeclName());
1869 if (Found.empty())
1870 return nullptr;
1872 ClassTemplateDecl *InstClassTemplate
1873 = dyn_cast<ClassTemplateDecl>(Found.front());
1874 if (!InstClassTemplate)
1875 return nullptr;
1877 if (ClassTemplatePartialSpecializationDecl *Result
1878 = InstClassTemplate->findPartialSpecInstantiatedFromMember(D))
1879 return Result;
1881 return InstantiateClassTemplatePartialSpecialization(InstClassTemplate, D);
1884 Decl *TemplateDeclInstantiator::VisitVarTemplateDecl(VarTemplateDecl *D) {
1885 assert(D->getTemplatedDecl()->isStaticDataMember() &&
1886 "Only static data member templates are allowed.");
1888 // Create a local instantiation scope for this variable template, which
1889 // will contain the instantiations of the template parameters.
1890 LocalInstantiationScope Scope(SemaRef);
1891 TemplateParameterList *TempParams = D->getTemplateParameters();
1892 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1893 if (!InstParams)
1894 return nullptr;
1896 VarDecl *Pattern = D->getTemplatedDecl();
1897 VarTemplateDecl *PrevVarTemplate = nullptr;
1899 if (getPreviousDeclForInstantiation(Pattern)) {
1900 DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
1901 if (!Found.empty())
1902 PrevVarTemplate = dyn_cast<VarTemplateDecl>(Found.front());
1905 VarDecl *VarInst =
1906 cast_or_null<VarDecl>(VisitVarDecl(Pattern,
1907 /*InstantiatingVarTemplate=*/true));
1908 if (!VarInst) return nullptr;
1910 DeclContext *DC = Owner;
1912 VarTemplateDecl *Inst = VarTemplateDecl::Create(
1913 SemaRef.Context, DC, D->getLocation(), D->getIdentifier(), InstParams,
1914 VarInst);
1915 VarInst->setDescribedVarTemplate(Inst);
1916 Inst->setPreviousDecl(PrevVarTemplate);
1918 Inst->setAccess(D->getAccess());
1919 if (!PrevVarTemplate)
1920 Inst->setInstantiatedFromMemberTemplate(D);
1922 if (D->isOutOfLine()) {
1923 Inst->setLexicalDeclContext(D->getLexicalDeclContext());
1924 VarInst->setLexicalDeclContext(D->getLexicalDeclContext());
1927 Owner->addDecl(Inst);
1929 if (!PrevVarTemplate) {
1930 // Queue up any out-of-line partial specializations of this member
1931 // variable template; the client will force their instantiation once
1932 // the enclosing class has been instantiated.
1933 SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs;
1934 D->getPartialSpecializations(PartialSpecs);
1935 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
1936 if (PartialSpecs[I]->getFirstDecl()->isOutOfLine())
1937 OutOfLineVarPartialSpecs.push_back(
1938 std::make_pair(Inst, PartialSpecs[I]));
1941 return Inst;
1944 Decl *TemplateDeclInstantiator::VisitVarTemplatePartialSpecializationDecl(
1945 VarTemplatePartialSpecializationDecl *D) {
1946 assert(D->isStaticDataMember() &&
1947 "Only static data member templates are allowed.");
1949 VarTemplateDecl *VarTemplate = D->getSpecializedTemplate();
1951 // Lookup the already-instantiated declaration and return that.
1952 DeclContext::lookup_result Found = Owner->lookup(VarTemplate->getDeclName());
1953 assert(!Found.empty() && "Instantiation found nothing?");
1955 VarTemplateDecl *InstVarTemplate = dyn_cast<VarTemplateDecl>(Found.front());
1956 assert(InstVarTemplate && "Instantiation did not find a variable template?");
1958 if (VarTemplatePartialSpecializationDecl *Result =
1959 InstVarTemplate->findPartialSpecInstantiatedFromMember(D))
1960 return Result;
1962 return InstantiateVarTemplatePartialSpecialization(InstVarTemplate, D);
1965 Decl *
1966 TemplateDeclInstantiator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
1967 // Create a local instantiation scope for this function template, which
1968 // will contain the instantiations of the template parameters and then get
1969 // merged with the local instantiation scope for the function template
1970 // itself.
1971 LocalInstantiationScope Scope(SemaRef);
1972 Sema::ConstraintEvalRAII<TemplateDeclInstantiator> RAII(*this);
1974 TemplateParameterList *TempParams = D->getTemplateParameters();
1975 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1976 if (!InstParams)
1977 return nullptr;
1979 FunctionDecl *Instantiated = nullptr;
1980 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(D->getTemplatedDecl()))
1981 Instantiated = cast_or_null<FunctionDecl>(VisitCXXMethodDecl(DMethod,
1982 InstParams));
1983 else
1984 Instantiated = cast_or_null<FunctionDecl>(VisitFunctionDecl(
1985 D->getTemplatedDecl(),
1986 InstParams));
1988 if (!Instantiated)
1989 return nullptr;
1991 // Link the instantiated function template declaration to the function
1992 // template from which it was instantiated.
1993 FunctionTemplateDecl *InstTemplate
1994 = Instantiated->getDescribedFunctionTemplate();
1995 InstTemplate->setAccess(D->getAccess());
1996 assert(InstTemplate &&
1997 "VisitFunctionDecl/CXXMethodDecl didn't create a template!");
1999 bool isFriend = (InstTemplate->getFriendObjectKind() != Decl::FOK_None);
2001 // Link the instantiation back to the pattern *unless* this is a
2002 // non-definition friend declaration.
2003 if (!InstTemplate->getInstantiatedFromMemberTemplate() &&
2004 !(isFriend && !D->getTemplatedDecl()->isThisDeclarationADefinition()))
2005 InstTemplate->setInstantiatedFromMemberTemplate(D);
2007 // Make declarations visible in the appropriate context.
2008 if (!isFriend) {
2009 Owner->addDecl(InstTemplate);
2010 } else if (InstTemplate->getDeclContext()->isRecord() &&
2011 !getPreviousDeclForInstantiation(D)) {
2012 SemaRef.CheckFriendAccess(InstTemplate);
2015 return InstTemplate;
2018 Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) {
2019 CXXRecordDecl *PrevDecl = nullptr;
2020 if (CXXRecordDecl *PatternPrev = getPreviousDeclForInstantiation(D)) {
2021 NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
2022 PatternPrev,
2023 TemplateArgs);
2024 if (!Prev) return nullptr;
2025 PrevDecl = cast<CXXRecordDecl>(Prev);
2028 CXXRecordDecl *Record = nullptr;
2029 bool IsInjectedClassName = D->isInjectedClassName();
2030 if (D->isLambda())
2031 Record = CXXRecordDecl::CreateLambda(
2032 SemaRef.Context, Owner, D->getLambdaTypeInfo(), D->getLocation(),
2033 D->getLambdaDependencyKind(), D->isGenericLambda(),
2034 D->getLambdaCaptureDefault());
2035 else
2036 Record = CXXRecordDecl::Create(SemaRef.Context, D->getTagKind(), Owner,
2037 D->getBeginLoc(), D->getLocation(),
2038 D->getIdentifier(), PrevDecl,
2039 /*DelayTypeCreation=*/IsInjectedClassName);
2040 // Link the type of the injected-class-name to that of the outer class.
2041 if (IsInjectedClassName)
2042 (void)SemaRef.Context.getTypeDeclType(Record, cast<CXXRecordDecl>(Owner));
2044 // Substitute the nested name specifier, if any.
2045 if (SubstQualifier(D, Record))
2046 return nullptr;
2048 SemaRef.InstantiateAttrsForDecl(TemplateArgs, D, Record, LateAttrs,
2049 StartingScope);
2051 Record->setImplicit(D->isImplicit());
2052 // FIXME: Check against AS_none is an ugly hack to work around the issue that
2053 // the tag decls introduced by friend class declarations don't have an access
2054 // specifier. Remove once this area of the code gets sorted out.
2055 if (D->getAccess() != AS_none)
2056 Record->setAccess(D->getAccess());
2057 if (!IsInjectedClassName)
2058 Record->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
2060 // If the original function was part of a friend declaration,
2061 // inherit its namespace state.
2062 if (D->getFriendObjectKind())
2063 Record->setObjectOfFriendDecl();
2065 // Make sure that anonymous structs and unions are recorded.
2066 if (D->isAnonymousStructOrUnion())
2067 Record->setAnonymousStructOrUnion(true);
2069 if (D->isLocalClass())
2070 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Record);
2072 // Forward the mangling number from the template to the instantiated decl.
2073 SemaRef.Context.setManglingNumber(Record,
2074 SemaRef.Context.getManglingNumber(D));
2076 // See if the old tag was defined along with a declarator.
2077 // If it did, mark the new tag as being associated with that declarator.
2078 if (DeclaratorDecl *DD = SemaRef.Context.getDeclaratorForUnnamedTagDecl(D))
2079 SemaRef.Context.addDeclaratorForUnnamedTagDecl(Record, DD);
2081 // See if the old tag was defined along with a typedef.
2082 // If it did, mark the new tag as being associated with that typedef.
2083 if (TypedefNameDecl *TND = SemaRef.Context.getTypedefNameForUnnamedTagDecl(D))
2084 SemaRef.Context.addTypedefNameForUnnamedTagDecl(Record, TND);
2086 Owner->addDecl(Record);
2088 // DR1484 clarifies that the members of a local class are instantiated as part
2089 // of the instantiation of their enclosing entity.
2090 if (D->isCompleteDefinition() && D->isLocalClass()) {
2091 Sema::LocalEagerInstantiationScope LocalInstantiations(SemaRef);
2093 SemaRef.InstantiateClass(D->getLocation(), Record, D, TemplateArgs,
2094 TSK_ImplicitInstantiation,
2095 /*Complain=*/true);
2097 // For nested local classes, we will instantiate the members when we
2098 // reach the end of the outermost (non-nested) local class.
2099 if (!D->isCXXClassMember())
2100 SemaRef.InstantiateClassMembers(D->getLocation(), Record, TemplateArgs,
2101 TSK_ImplicitInstantiation);
2103 // This class may have local implicit instantiations that need to be
2104 // performed within this scope.
2105 LocalInstantiations.perform();
2108 SemaRef.DiagnoseUnusedNestedTypedefs(Record);
2110 if (IsInjectedClassName)
2111 assert(Record->isInjectedClassName() && "Broken injected-class-name");
2113 return Record;
2116 /// Adjust the given function type for an instantiation of the
2117 /// given declaration, to cope with modifications to the function's type that
2118 /// aren't reflected in the type-source information.
2120 /// \param D The declaration we're instantiating.
2121 /// \param TInfo The already-instantiated type.
2122 static QualType adjustFunctionTypeForInstantiation(ASTContext &Context,
2123 FunctionDecl *D,
2124 TypeSourceInfo *TInfo) {
2125 const FunctionProtoType *OrigFunc
2126 = D->getType()->castAs<FunctionProtoType>();
2127 const FunctionProtoType *NewFunc
2128 = TInfo->getType()->castAs<FunctionProtoType>();
2129 if (OrigFunc->getExtInfo() == NewFunc->getExtInfo())
2130 return TInfo->getType();
2132 FunctionProtoType::ExtProtoInfo NewEPI = NewFunc->getExtProtoInfo();
2133 NewEPI.ExtInfo = OrigFunc->getExtInfo();
2134 return Context.getFunctionType(NewFunc->getReturnType(),
2135 NewFunc->getParamTypes(), NewEPI);
2138 /// Normal class members are of more specific types and therefore
2139 /// don't make it here. This function serves three purposes:
2140 /// 1) instantiating function templates
2141 /// 2) substituting friend and local function declarations
2142 /// 3) substituting deduction guide declarations for nested class templates
2143 Decl *TemplateDeclInstantiator::VisitFunctionDecl(
2144 FunctionDecl *D, TemplateParameterList *TemplateParams,
2145 RewriteKind FunctionRewriteKind) {
2146 // Check whether there is already a function template specialization for
2147 // this declaration.
2148 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
2149 if (FunctionTemplate && !TemplateParams) {
2150 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
2152 void *InsertPos = nullptr;
2153 FunctionDecl *SpecFunc
2154 = FunctionTemplate->findSpecialization(Innermost, InsertPos);
2156 // If we already have a function template specialization, return it.
2157 if (SpecFunc)
2158 return SpecFunc;
2161 bool isFriend;
2162 if (FunctionTemplate)
2163 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
2164 else
2165 isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
2167 bool MergeWithParentScope = (TemplateParams != nullptr) ||
2168 Owner->isFunctionOrMethod() ||
2169 !(isa<Decl>(Owner) &&
2170 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
2171 LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
2173 ExplicitSpecifier InstantiatedExplicitSpecifier;
2174 if (auto *DGuide = dyn_cast<CXXDeductionGuideDecl>(D)) {
2175 InstantiatedExplicitSpecifier = SemaRef.instantiateExplicitSpecifier(
2176 TemplateArgs, DGuide->getExplicitSpecifier());
2177 if (InstantiatedExplicitSpecifier.isInvalid())
2178 return nullptr;
2181 SmallVector<ParmVarDecl *, 4> Params;
2182 TypeSourceInfo *TInfo = SubstFunctionType(D, Params);
2183 if (!TInfo)
2184 return nullptr;
2185 QualType T = adjustFunctionTypeForInstantiation(SemaRef.Context, D, TInfo);
2187 if (TemplateParams && TemplateParams->size()) {
2188 auto *LastParam =
2189 dyn_cast<TemplateTypeParmDecl>(TemplateParams->asArray().back());
2190 if (LastParam && LastParam->isImplicit() &&
2191 LastParam->hasTypeConstraint()) {
2192 // In abbreviated templates, the type-constraints of invented template
2193 // type parameters are instantiated with the function type, invalidating
2194 // the TemplateParameterList which relied on the template type parameter
2195 // not having a type constraint. Recreate the TemplateParameterList with
2196 // the updated parameter list.
2197 TemplateParams = TemplateParameterList::Create(
2198 SemaRef.Context, TemplateParams->getTemplateLoc(),
2199 TemplateParams->getLAngleLoc(), TemplateParams->asArray(),
2200 TemplateParams->getRAngleLoc(), TemplateParams->getRequiresClause());
2204 NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
2205 if (QualifierLoc) {
2206 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
2207 TemplateArgs);
2208 if (!QualifierLoc)
2209 return nullptr;
2212 Expr *TrailingRequiresClause = D->getTrailingRequiresClause();
2214 // If we're instantiating a local function declaration, put the result
2215 // in the enclosing namespace; otherwise we need to find the instantiated
2216 // context.
2217 DeclContext *DC;
2218 if (D->isLocalExternDecl()) {
2219 DC = Owner;
2220 SemaRef.adjustContextForLocalExternDecl(DC);
2221 } else if (isFriend && QualifierLoc) {
2222 CXXScopeSpec SS;
2223 SS.Adopt(QualifierLoc);
2224 DC = SemaRef.computeDeclContext(SS);
2225 if (!DC) return nullptr;
2226 } else {
2227 DC = SemaRef.FindInstantiatedContext(D->getLocation(), D->getDeclContext(),
2228 TemplateArgs);
2231 DeclarationNameInfo NameInfo
2232 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
2234 if (FunctionRewriteKind != RewriteKind::None)
2235 adjustForRewrite(FunctionRewriteKind, D, T, TInfo, NameInfo);
2237 FunctionDecl *Function;
2238 if (auto *DGuide = dyn_cast<CXXDeductionGuideDecl>(D)) {
2239 Function = CXXDeductionGuideDecl::Create(
2240 SemaRef.Context, DC, D->getInnerLocStart(),
2241 InstantiatedExplicitSpecifier, NameInfo, T, TInfo,
2242 D->getSourceRange().getEnd(), DGuide->getCorrespondingConstructor(),
2243 DGuide->getDeductionCandidateKind(), TrailingRequiresClause);
2244 Function->setAccess(D->getAccess());
2245 } else {
2246 Function = FunctionDecl::Create(
2247 SemaRef.Context, DC, D->getInnerLocStart(), NameInfo, T, TInfo,
2248 D->getCanonicalDecl()->getStorageClass(), D->UsesFPIntrin(),
2249 D->isInlineSpecified(), D->hasWrittenPrototype(), D->getConstexprKind(),
2250 TrailingRequiresClause);
2251 Function->setFriendConstraintRefersToEnclosingTemplate(
2252 D->FriendConstraintRefersToEnclosingTemplate());
2253 Function->setRangeEnd(D->getSourceRange().getEnd());
2256 if (D->isInlined())
2257 Function->setImplicitlyInline();
2259 if (QualifierLoc)
2260 Function->setQualifierInfo(QualifierLoc);
2262 if (D->isLocalExternDecl())
2263 Function->setLocalExternDecl();
2265 DeclContext *LexicalDC = Owner;
2266 if (!isFriend && D->isOutOfLine() && !D->isLocalExternDecl()) {
2267 assert(D->getDeclContext()->isFileContext());
2268 LexicalDC = D->getDeclContext();
2270 else if (D->isLocalExternDecl()) {
2271 LexicalDC = SemaRef.CurContext;
2274 Function->setLexicalDeclContext(LexicalDC);
2276 // Attach the parameters
2277 for (unsigned P = 0; P < Params.size(); ++P)
2278 if (Params[P])
2279 Params[P]->setOwningFunction(Function);
2280 Function->setParams(Params);
2282 if (TrailingRequiresClause)
2283 Function->setTrailingRequiresClause(TrailingRequiresClause);
2285 if (TemplateParams) {
2286 // Our resulting instantiation is actually a function template, since we
2287 // are substituting only the outer template parameters. For example, given
2289 // template<typename T>
2290 // struct X {
2291 // template<typename U> friend void f(T, U);
2292 // };
2294 // X<int> x;
2296 // We are instantiating the friend function template "f" within X<int>,
2297 // which means substituting int for T, but leaving "f" as a friend function
2298 // template.
2299 // Build the function template itself.
2300 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, DC,
2301 Function->getLocation(),
2302 Function->getDeclName(),
2303 TemplateParams, Function);
2304 Function->setDescribedFunctionTemplate(FunctionTemplate);
2306 FunctionTemplate->setLexicalDeclContext(LexicalDC);
2308 if (isFriend && D->isThisDeclarationADefinition()) {
2309 FunctionTemplate->setInstantiatedFromMemberTemplate(
2310 D->getDescribedFunctionTemplate());
2312 } else if (FunctionTemplate &&
2313 SemaRef.CodeSynthesisContexts.back().Kind !=
2314 Sema::CodeSynthesisContext::BuildingDeductionGuides) {
2315 // Record this function template specialization.
2316 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
2317 Function->setFunctionTemplateSpecialization(FunctionTemplate,
2318 TemplateArgumentList::CreateCopy(SemaRef.Context,
2319 Innermost),
2320 /*InsertPos=*/nullptr);
2321 } else if (FunctionRewriteKind == RewriteKind::None) {
2322 if (isFriend && D->isThisDeclarationADefinition()) {
2323 // Do not connect the friend to the template unless it's actually a
2324 // definition. We don't want non-template functions to be marked as being
2325 // template instantiations.
2326 Function->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
2327 } else if (!isFriend) {
2328 // If this is not a function template, and this is not a friend (that is,
2329 // this is a locally declared function), save the instantiation
2330 // relationship for the purposes of constraint instantiation.
2331 Function->setInstantiatedFromDecl(D);
2335 if (isFriend) {
2336 Function->setObjectOfFriendDecl();
2337 if (FunctionTemplateDecl *FT = Function->getDescribedFunctionTemplate())
2338 FT->setObjectOfFriendDecl();
2341 if (InitFunctionInstantiation(Function, D))
2342 Function->setInvalidDecl();
2344 bool IsExplicitSpecialization = false;
2346 LookupResult Previous(
2347 SemaRef, Function->getDeclName(), SourceLocation(),
2348 D->isLocalExternDecl() ? Sema::LookupRedeclarationWithLinkage
2349 : Sema::LookupOrdinaryName,
2350 D->isLocalExternDecl() ? RedeclarationKind::ForExternalRedeclaration
2351 : SemaRef.forRedeclarationInCurContext());
2353 if (DependentFunctionTemplateSpecializationInfo *DFTSI =
2354 D->getDependentSpecializationInfo()) {
2355 assert(isFriend && "dependent specialization info on "
2356 "non-member non-friend function?");
2358 // Instantiate the explicit template arguments.
2359 TemplateArgumentListInfo ExplicitArgs;
2360 if (const auto *ArgsWritten = DFTSI->TemplateArgumentsAsWritten) {
2361 ExplicitArgs.setLAngleLoc(ArgsWritten->getLAngleLoc());
2362 ExplicitArgs.setRAngleLoc(ArgsWritten->getRAngleLoc());
2363 if (SemaRef.SubstTemplateArguments(ArgsWritten->arguments(), TemplateArgs,
2364 ExplicitArgs))
2365 return nullptr;
2368 // Map the candidates for the primary template to their instantiations.
2369 for (FunctionTemplateDecl *FTD : DFTSI->getCandidates()) {
2370 if (NamedDecl *ND =
2371 SemaRef.FindInstantiatedDecl(D->getLocation(), FTD, TemplateArgs))
2372 Previous.addDecl(ND);
2373 else
2374 return nullptr;
2377 if (SemaRef.CheckFunctionTemplateSpecialization(
2378 Function,
2379 DFTSI->TemplateArgumentsAsWritten ? &ExplicitArgs : nullptr,
2380 Previous))
2381 Function->setInvalidDecl();
2383 IsExplicitSpecialization = true;
2384 } else if (const ASTTemplateArgumentListInfo *ArgsWritten =
2385 D->getTemplateSpecializationArgsAsWritten()) {
2386 // The name of this function was written as a template-id.
2387 SemaRef.LookupQualifiedName(Previous, DC);
2389 // Instantiate the explicit template arguments.
2390 TemplateArgumentListInfo ExplicitArgs(ArgsWritten->getLAngleLoc(),
2391 ArgsWritten->getRAngleLoc());
2392 if (SemaRef.SubstTemplateArguments(ArgsWritten->arguments(), TemplateArgs,
2393 ExplicitArgs))
2394 return nullptr;
2396 if (SemaRef.CheckFunctionTemplateSpecialization(Function,
2397 &ExplicitArgs,
2398 Previous))
2399 Function->setInvalidDecl();
2401 IsExplicitSpecialization = true;
2402 } else if (TemplateParams || !FunctionTemplate) {
2403 // Look only into the namespace where the friend would be declared to
2404 // find a previous declaration. This is the innermost enclosing namespace,
2405 // as described in ActOnFriendFunctionDecl.
2406 SemaRef.LookupQualifiedName(Previous, DC->getRedeclContext());
2408 // In C++, the previous declaration we find might be a tag type
2409 // (class or enum). In this case, the new declaration will hide the
2410 // tag type. Note that this does not apply if we're declaring a
2411 // typedef (C++ [dcl.typedef]p4).
2412 if (Previous.isSingleTagDecl())
2413 Previous.clear();
2415 // Filter out previous declarations that don't match the scope. The only
2416 // effect this has is to remove declarations found in inline namespaces
2417 // for friend declarations with unqualified names.
2418 if (isFriend && !QualifierLoc) {
2419 SemaRef.FilterLookupForScope(Previous, DC, /*Scope=*/ nullptr,
2420 /*ConsiderLinkage=*/ true,
2421 QualifierLoc.hasQualifier());
2425 // Per [temp.inst], default arguments in function declarations at local scope
2426 // are instantiated along with the enclosing declaration. For example:
2428 // template<typename T>
2429 // void ft() {
2430 // void f(int = []{ return T::value; }());
2431 // }
2432 // template void ft<int>(); // error: type 'int' cannot be used prior
2433 // to '::' because it has no members
2435 // The error is issued during instantiation of ft<int>() because substitution
2436 // into the default argument fails; the default argument is instantiated even
2437 // though it is never used.
2438 if (Function->isLocalExternDecl()) {
2439 for (ParmVarDecl *PVD : Function->parameters()) {
2440 if (!PVD->hasDefaultArg())
2441 continue;
2442 if (SemaRef.SubstDefaultArgument(D->getInnerLocStart(), PVD, TemplateArgs)) {
2443 // If substitution fails, the default argument is set to a
2444 // RecoveryExpr that wraps the uninstantiated default argument so
2445 // that downstream diagnostics are omitted.
2446 Expr *UninstExpr = PVD->getUninstantiatedDefaultArg();
2447 ExprResult ErrorResult = SemaRef.CreateRecoveryExpr(
2448 UninstExpr->getBeginLoc(), UninstExpr->getEndLoc(),
2449 { UninstExpr }, UninstExpr->getType());
2450 if (ErrorResult.isUsable())
2451 PVD->setDefaultArg(ErrorResult.get());
2456 SemaRef.CheckFunctionDeclaration(/*Scope*/ nullptr, Function, Previous,
2457 IsExplicitSpecialization,
2458 Function->isThisDeclarationADefinition());
2460 // Check the template parameter list against the previous declaration. The
2461 // goal here is to pick up default arguments added since the friend was
2462 // declared; we know the template parameter lists match, since otherwise
2463 // we would not have picked this template as the previous declaration.
2464 if (isFriend && TemplateParams && FunctionTemplate->getPreviousDecl()) {
2465 SemaRef.CheckTemplateParameterList(
2466 TemplateParams,
2467 FunctionTemplate->getPreviousDecl()->getTemplateParameters(),
2468 Function->isThisDeclarationADefinition()
2469 ? Sema::TPC_FriendFunctionTemplateDefinition
2470 : Sema::TPC_FriendFunctionTemplate);
2473 // If we're introducing a friend definition after the first use, trigger
2474 // instantiation.
2475 // FIXME: If this is a friend function template definition, we should check
2476 // to see if any specializations have been used.
2477 if (isFriend && D->isThisDeclarationADefinition() && Function->isUsed(false)) {
2478 if (MemberSpecializationInfo *MSInfo =
2479 Function->getMemberSpecializationInfo()) {
2480 if (MSInfo->getPointOfInstantiation().isInvalid()) {
2481 SourceLocation Loc = D->getLocation(); // FIXME
2482 MSInfo->setPointOfInstantiation(Loc);
2483 SemaRef.PendingLocalImplicitInstantiations.push_back(
2484 std::make_pair(Function, Loc));
2489 if (D->isExplicitlyDefaulted()) {
2490 if (SubstDefaultedFunction(Function, D))
2491 return nullptr;
2493 if (D->isDeleted())
2494 SemaRef.SetDeclDeleted(Function, D->getLocation(), D->getDeletedMessage());
2496 NamedDecl *PrincipalDecl =
2497 (TemplateParams ? cast<NamedDecl>(FunctionTemplate) : Function);
2499 // If this declaration lives in a different context from its lexical context,
2500 // add it to the corresponding lookup table.
2501 if (isFriend ||
2502 (Function->isLocalExternDecl() && !Function->getPreviousDecl()))
2503 DC->makeDeclVisibleInContext(PrincipalDecl);
2505 if (Function->isOverloadedOperator() && !DC->isRecord() &&
2506 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
2507 PrincipalDecl->setNonMemberOperator();
2509 return Function;
2512 Decl *TemplateDeclInstantiator::VisitCXXMethodDecl(
2513 CXXMethodDecl *D, TemplateParameterList *TemplateParams,
2514 RewriteKind FunctionRewriteKind) {
2515 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
2516 if (FunctionTemplate && !TemplateParams) {
2517 // We are creating a function template specialization from a function
2518 // template. Check whether there is already a function template
2519 // specialization for this particular set of template arguments.
2520 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
2522 void *InsertPos = nullptr;
2523 FunctionDecl *SpecFunc
2524 = FunctionTemplate->findSpecialization(Innermost, InsertPos);
2526 // If we already have a function template specialization, return it.
2527 if (SpecFunc)
2528 return SpecFunc;
2531 bool isFriend;
2532 if (FunctionTemplate)
2533 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
2534 else
2535 isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
2537 bool MergeWithParentScope = (TemplateParams != nullptr) ||
2538 !(isa<Decl>(Owner) &&
2539 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
2540 LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
2542 Sema::LambdaScopeForCallOperatorInstantiationRAII LambdaScope(
2543 SemaRef, const_cast<CXXMethodDecl *>(D), TemplateArgs, Scope);
2545 // Instantiate enclosing template arguments for friends.
2546 SmallVector<TemplateParameterList *, 4> TempParamLists;
2547 unsigned NumTempParamLists = 0;
2548 if (isFriend && (NumTempParamLists = D->getNumTemplateParameterLists())) {
2549 TempParamLists.resize(NumTempParamLists);
2550 for (unsigned I = 0; I != NumTempParamLists; ++I) {
2551 TemplateParameterList *TempParams = D->getTemplateParameterList(I);
2552 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
2553 if (!InstParams)
2554 return nullptr;
2555 TempParamLists[I] = InstParams;
2559 auto InstantiatedExplicitSpecifier = ExplicitSpecifier::getFromDecl(D);
2560 // deduction guides need this
2561 const bool CouldInstantiate =
2562 InstantiatedExplicitSpecifier.getExpr() == nullptr ||
2563 !InstantiatedExplicitSpecifier.getExpr()->isValueDependent();
2565 // Delay the instantiation of the explicit-specifier until after the
2566 // constraints are checked during template argument deduction.
2567 if (CouldInstantiate ||
2568 SemaRef.CodeSynthesisContexts.back().Kind !=
2569 Sema::CodeSynthesisContext::DeducedTemplateArgumentSubstitution) {
2570 InstantiatedExplicitSpecifier = SemaRef.instantiateExplicitSpecifier(
2571 TemplateArgs, InstantiatedExplicitSpecifier);
2573 if (InstantiatedExplicitSpecifier.isInvalid())
2574 return nullptr;
2575 } else {
2576 InstantiatedExplicitSpecifier.setKind(ExplicitSpecKind::Unresolved);
2579 // Implicit destructors/constructors created for local classes in
2580 // DeclareImplicit* (see SemaDeclCXX.cpp) might not have an associated TSI.
2581 // Unfortunately there isn't enough context in those functions to
2582 // conditionally populate the TSI without breaking non-template related use
2583 // cases. Populate TSIs prior to calling SubstFunctionType to make sure we get
2584 // a proper transformation.
2585 if (cast<CXXRecordDecl>(D->getParent())->isLambda() &&
2586 !D->getTypeSourceInfo() &&
2587 isa<CXXConstructorDecl, CXXDestructorDecl>(D)) {
2588 TypeSourceInfo *TSI =
2589 SemaRef.Context.getTrivialTypeSourceInfo(D->getType());
2590 D->setTypeSourceInfo(TSI);
2593 SmallVector<ParmVarDecl *, 4> Params;
2594 TypeSourceInfo *TInfo = SubstFunctionType(D, Params);
2595 if (!TInfo)
2596 return nullptr;
2597 QualType T = adjustFunctionTypeForInstantiation(SemaRef.Context, D, TInfo);
2599 if (TemplateParams && TemplateParams->size()) {
2600 auto *LastParam =
2601 dyn_cast<TemplateTypeParmDecl>(TemplateParams->asArray().back());
2602 if (LastParam && LastParam->isImplicit() &&
2603 LastParam->hasTypeConstraint()) {
2604 // In abbreviated templates, the type-constraints of invented template
2605 // type parameters are instantiated with the function type, invalidating
2606 // the TemplateParameterList which relied on the template type parameter
2607 // not having a type constraint. Recreate the TemplateParameterList with
2608 // the updated parameter list.
2609 TemplateParams = TemplateParameterList::Create(
2610 SemaRef.Context, TemplateParams->getTemplateLoc(),
2611 TemplateParams->getLAngleLoc(), TemplateParams->asArray(),
2612 TemplateParams->getRAngleLoc(), TemplateParams->getRequiresClause());
2616 NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
2617 if (QualifierLoc) {
2618 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
2619 TemplateArgs);
2620 if (!QualifierLoc)
2621 return nullptr;
2624 DeclContext *DC = Owner;
2625 if (isFriend) {
2626 if (QualifierLoc) {
2627 CXXScopeSpec SS;
2628 SS.Adopt(QualifierLoc);
2629 DC = SemaRef.computeDeclContext(SS);
2631 if (DC && SemaRef.RequireCompleteDeclContext(SS, DC))
2632 return nullptr;
2633 } else {
2634 DC = SemaRef.FindInstantiatedContext(D->getLocation(),
2635 D->getDeclContext(),
2636 TemplateArgs);
2638 if (!DC) return nullptr;
2641 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
2642 Expr *TrailingRequiresClause = D->getTrailingRequiresClause();
2644 DeclarationNameInfo NameInfo
2645 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
2647 if (FunctionRewriteKind != RewriteKind::None)
2648 adjustForRewrite(FunctionRewriteKind, D, T, TInfo, NameInfo);
2650 // Build the instantiated method declaration.
2651 CXXMethodDecl *Method = nullptr;
2653 SourceLocation StartLoc = D->getInnerLocStart();
2654 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
2655 Method = CXXConstructorDecl::Create(
2656 SemaRef.Context, Record, StartLoc, NameInfo, T, TInfo,
2657 InstantiatedExplicitSpecifier, Constructor->UsesFPIntrin(),
2658 Constructor->isInlineSpecified(), false,
2659 Constructor->getConstexprKind(), InheritedConstructor(),
2660 TrailingRequiresClause);
2661 Method->setRangeEnd(Constructor->getEndLoc());
2662 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
2663 Method = CXXDestructorDecl::Create(
2664 SemaRef.Context, Record, StartLoc, NameInfo, T, TInfo,
2665 Destructor->UsesFPIntrin(), Destructor->isInlineSpecified(), false,
2666 Destructor->getConstexprKind(), TrailingRequiresClause);
2667 Method->setIneligibleOrNotSelected(true);
2668 Method->setRangeEnd(Destructor->getEndLoc());
2669 Method->setDeclName(SemaRef.Context.DeclarationNames.getCXXDestructorName(
2670 SemaRef.Context.getCanonicalType(
2671 SemaRef.Context.getTypeDeclType(Record))));
2672 } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) {
2673 Method = CXXConversionDecl::Create(
2674 SemaRef.Context, Record, StartLoc, NameInfo, T, TInfo,
2675 Conversion->UsesFPIntrin(), Conversion->isInlineSpecified(),
2676 InstantiatedExplicitSpecifier, Conversion->getConstexprKind(),
2677 Conversion->getEndLoc(), TrailingRequiresClause);
2678 } else {
2679 StorageClass SC = D->isStatic() ? SC_Static : SC_None;
2680 Method = CXXMethodDecl::Create(
2681 SemaRef.Context, Record, StartLoc, NameInfo, T, TInfo, SC,
2682 D->UsesFPIntrin(), D->isInlineSpecified(), D->getConstexprKind(),
2683 D->getEndLoc(), TrailingRequiresClause);
2686 if (D->isInlined())
2687 Method->setImplicitlyInline();
2689 if (QualifierLoc)
2690 Method->setQualifierInfo(QualifierLoc);
2692 if (TemplateParams) {
2693 // Our resulting instantiation is actually a function template, since we
2694 // are substituting only the outer template parameters. For example, given
2696 // template<typename T>
2697 // struct X {
2698 // template<typename U> void f(T, U);
2699 // };
2701 // X<int> x;
2703 // We are instantiating the member template "f" within X<int>, which means
2704 // substituting int for T, but leaving "f" as a member function template.
2705 // Build the function template itself.
2706 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Record,
2707 Method->getLocation(),
2708 Method->getDeclName(),
2709 TemplateParams, Method);
2710 if (isFriend) {
2711 FunctionTemplate->setLexicalDeclContext(Owner);
2712 FunctionTemplate->setObjectOfFriendDecl();
2713 } else if (D->isOutOfLine())
2714 FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
2715 Method->setDescribedFunctionTemplate(FunctionTemplate);
2716 } else if (FunctionTemplate) {
2717 // Record this function template specialization.
2718 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
2719 Method->setFunctionTemplateSpecialization(FunctionTemplate,
2720 TemplateArgumentList::CreateCopy(SemaRef.Context,
2721 Innermost),
2722 /*InsertPos=*/nullptr);
2723 } else if (!isFriend && FunctionRewriteKind == RewriteKind::None) {
2724 // Record that this is an instantiation of a member function.
2725 Method->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
2728 // If we are instantiating a member function defined
2729 // out-of-line, the instantiation will have the same lexical
2730 // context (which will be a namespace scope) as the template.
2731 if (isFriend) {
2732 if (NumTempParamLists)
2733 Method->setTemplateParameterListsInfo(
2734 SemaRef.Context,
2735 llvm::ArrayRef(TempParamLists.data(), NumTempParamLists));
2737 Method->setLexicalDeclContext(Owner);
2738 Method->setObjectOfFriendDecl();
2739 } else if (D->isOutOfLine())
2740 Method->setLexicalDeclContext(D->getLexicalDeclContext());
2742 // Attach the parameters
2743 for (unsigned P = 0; P < Params.size(); ++P)
2744 Params[P]->setOwningFunction(Method);
2745 Method->setParams(Params);
2747 if (InitMethodInstantiation(Method, D))
2748 Method->setInvalidDecl();
2750 LookupResult Previous(SemaRef, NameInfo, Sema::LookupOrdinaryName,
2751 RedeclarationKind::ForExternalRedeclaration);
2753 bool IsExplicitSpecialization = false;
2755 // If the name of this function was written as a template-id, instantiate
2756 // the explicit template arguments.
2757 if (DependentFunctionTemplateSpecializationInfo *DFTSI =
2758 D->getDependentSpecializationInfo()) {
2759 // Instantiate the explicit template arguments.
2760 TemplateArgumentListInfo ExplicitArgs;
2761 if (const auto *ArgsWritten = DFTSI->TemplateArgumentsAsWritten) {
2762 ExplicitArgs.setLAngleLoc(ArgsWritten->getLAngleLoc());
2763 ExplicitArgs.setRAngleLoc(ArgsWritten->getRAngleLoc());
2764 if (SemaRef.SubstTemplateArguments(ArgsWritten->arguments(), TemplateArgs,
2765 ExplicitArgs))
2766 return nullptr;
2769 // Map the candidates for the primary template to their instantiations.
2770 for (FunctionTemplateDecl *FTD : DFTSI->getCandidates()) {
2771 if (NamedDecl *ND =
2772 SemaRef.FindInstantiatedDecl(D->getLocation(), FTD, TemplateArgs))
2773 Previous.addDecl(ND);
2774 else
2775 return nullptr;
2778 if (SemaRef.CheckFunctionTemplateSpecialization(
2779 Method, DFTSI->TemplateArgumentsAsWritten ? &ExplicitArgs : nullptr,
2780 Previous))
2781 Method->setInvalidDecl();
2783 IsExplicitSpecialization = true;
2784 } else if (const ASTTemplateArgumentListInfo *ArgsWritten =
2785 D->getTemplateSpecializationArgsAsWritten()) {
2786 SemaRef.LookupQualifiedName(Previous, DC);
2788 TemplateArgumentListInfo ExplicitArgs(ArgsWritten->getLAngleLoc(),
2789 ArgsWritten->getRAngleLoc());
2791 if (SemaRef.SubstTemplateArguments(ArgsWritten->arguments(), TemplateArgs,
2792 ExplicitArgs))
2793 return nullptr;
2795 if (SemaRef.CheckFunctionTemplateSpecialization(Method,
2796 &ExplicitArgs,
2797 Previous))
2798 Method->setInvalidDecl();
2800 IsExplicitSpecialization = true;
2801 } else if (!FunctionTemplate || TemplateParams || isFriend) {
2802 SemaRef.LookupQualifiedName(Previous, Record);
2804 // In C++, the previous declaration we find might be a tag type
2805 // (class or enum). In this case, the new declaration will hide the
2806 // tag type. Note that this does not apply if we're declaring a
2807 // typedef (C++ [dcl.typedef]p4).
2808 if (Previous.isSingleTagDecl())
2809 Previous.clear();
2812 // Per [temp.inst], default arguments in member functions of local classes
2813 // are instantiated along with the member function declaration. For example:
2815 // template<typename T>
2816 // void ft() {
2817 // struct lc {
2818 // int operator()(int p = []{ return T::value; }());
2819 // };
2820 // }
2821 // template void ft<int>(); // error: type 'int' cannot be used prior
2822 // to '::'because it has no members
2824 // The error is issued during instantiation of ft<int>()::lc::operator()
2825 // because substitution into the default argument fails; the default argument
2826 // is instantiated even though it is never used.
2827 if (D->isInLocalScopeForInstantiation()) {
2828 for (unsigned P = 0; P < Params.size(); ++P) {
2829 if (!Params[P]->hasDefaultArg())
2830 continue;
2831 if (SemaRef.SubstDefaultArgument(StartLoc, Params[P], TemplateArgs)) {
2832 // If substitution fails, the default argument is set to a
2833 // RecoveryExpr that wraps the uninstantiated default argument so
2834 // that downstream diagnostics are omitted.
2835 Expr *UninstExpr = Params[P]->getUninstantiatedDefaultArg();
2836 ExprResult ErrorResult = SemaRef.CreateRecoveryExpr(
2837 UninstExpr->getBeginLoc(), UninstExpr->getEndLoc(),
2838 { UninstExpr }, UninstExpr->getType());
2839 if (ErrorResult.isUsable())
2840 Params[P]->setDefaultArg(ErrorResult.get());
2845 SemaRef.CheckFunctionDeclaration(nullptr, Method, Previous,
2846 IsExplicitSpecialization,
2847 Method->isThisDeclarationADefinition());
2849 if (D->isPureVirtual())
2850 SemaRef.CheckPureMethod(Method, SourceRange());
2852 // Propagate access. For a non-friend declaration, the access is
2853 // whatever we're propagating from. For a friend, it should be the
2854 // previous declaration we just found.
2855 if (isFriend && Method->getPreviousDecl())
2856 Method->setAccess(Method->getPreviousDecl()->getAccess());
2857 else
2858 Method->setAccess(D->getAccess());
2859 if (FunctionTemplate)
2860 FunctionTemplate->setAccess(Method->getAccess());
2862 SemaRef.CheckOverrideControl(Method);
2864 // If a function is defined as defaulted or deleted, mark it as such now.
2865 if (D->isExplicitlyDefaulted()) {
2866 if (SubstDefaultedFunction(Method, D))
2867 return nullptr;
2869 if (D->isDeletedAsWritten())
2870 SemaRef.SetDeclDeleted(Method, Method->getLocation(),
2871 D->getDeletedMessage());
2873 // If this is an explicit specialization, mark the implicitly-instantiated
2874 // template specialization as being an explicit specialization too.
2875 // FIXME: Is this necessary?
2876 if (IsExplicitSpecialization && !isFriend)
2877 SemaRef.CompleteMemberSpecialization(Method, Previous);
2879 // If the method is a special member function, we need to mark it as
2880 // ineligible so that Owner->addDecl() won't mark the class as non trivial.
2881 // At the end of the class instantiation, we calculate eligibility again and
2882 // then we adjust trivility if needed.
2883 // We need this check to happen only after the method parameters are set,
2884 // because being e.g. a copy constructor depends on the instantiated
2885 // arguments.
2886 if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Method)) {
2887 if (Constructor->isDefaultConstructor() ||
2888 Constructor->isCopyOrMoveConstructor())
2889 Method->setIneligibleOrNotSelected(true);
2890 } else if (Method->isCopyAssignmentOperator() ||
2891 Method->isMoveAssignmentOperator()) {
2892 Method->setIneligibleOrNotSelected(true);
2895 // If there's a function template, let our caller handle it.
2896 if (FunctionTemplate) {
2897 // do nothing
2899 // Don't hide a (potentially) valid declaration with an invalid one.
2900 } else if (Method->isInvalidDecl() && !Previous.empty()) {
2901 // do nothing
2903 // Otherwise, check access to friends and make them visible.
2904 } else if (isFriend) {
2905 // We only need to re-check access for methods which we didn't
2906 // manage to match during parsing.
2907 if (!D->getPreviousDecl())
2908 SemaRef.CheckFriendAccess(Method);
2910 Record->makeDeclVisibleInContext(Method);
2912 // Otherwise, add the declaration. We don't need to do this for
2913 // class-scope specializations because we'll have matched them with
2914 // the appropriate template.
2915 } else {
2916 Owner->addDecl(Method);
2919 // PR17480: Honor the used attribute to instantiate member function
2920 // definitions
2921 if (Method->hasAttr<UsedAttr>()) {
2922 if (const auto *A = dyn_cast<CXXRecordDecl>(Owner)) {
2923 SourceLocation Loc;
2924 if (const MemberSpecializationInfo *MSInfo =
2925 A->getMemberSpecializationInfo())
2926 Loc = MSInfo->getPointOfInstantiation();
2927 else if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(A))
2928 Loc = Spec->getPointOfInstantiation();
2929 SemaRef.MarkFunctionReferenced(Loc, Method);
2933 return Method;
2936 Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
2937 return VisitCXXMethodDecl(D);
2940 Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
2941 return VisitCXXMethodDecl(D);
2944 Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
2945 return VisitCXXMethodDecl(D);
2948 Decl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
2949 return SemaRef.SubstParmVarDecl(D, TemplateArgs, /*indexAdjustment*/ 0,
2950 std::nullopt,
2951 /*ExpectParameterPack=*/false);
2954 Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl(
2955 TemplateTypeParmDecl *D) {
2956 assert(D->getTypeForDecl()->isTemplateTypeParmType());
2958 std::optional<unsigned> NumExpanded;
2960 if (const TypeConstraint *TC = D->getTypeConstraint()) {
2961 if (D->isPackExpansion() && !D->isExpandedParameterPack()) {
2962 assert(TC->getTemplateArgsAsWritten() &&
2963 "type parameter can only be an expansion when explicit arguments "
2964 "are specified");
2965 // The template type parameter pack's type is a pack expansion of types.
2966 // Determine whether we need to expand this parameter pack into separate
2967 // types.
2968 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
2969 for (auto &ArgLoc : TC->getTemplateArgsAsWritten()->arguments())
2970 SemaRef.collectUnexpandedParameterPacks(ArgLoc, Unexpanded);
2972 // Determine whether the set of unexpanded parameter packs can and should
2973 // be expanded.
2974 bool Expand = true;
2975 bool RetainExpansion = false;
2976 if (SemaRef.CheckParameterPacksForExpansion(
2977 cast<CXXFoldExpr>(TC->getImmediatelyDeclaredConstraint())
2978 ->getEllipsisLoc(),
2979 SourceRange(TC->getConceptNameLoc(),
2980 TC->hasExplicitTemplateArgs() ?
2981 TC->getTemplateArgsAsWritten()->getRAngleLoc() :
2982 TC->getConceptNameInfo().getEndLoc()),
2983 Unexpanded, TemplateArgs, Expand, RetainExpansion, NumExpanded))
2984 return nullptr;
2988 TemplateTypeParmDecl *Inst = TemplateTypeParmDecl::Create(
2989 SemaRef.Context, Owner, D->getBeginLoc(), D->getLocation(),
2990 D->getDepth() - TemplateArgs.getNumSubstitutedLevels(), D->getIndex(),
2991 D->getIdentifier(), D->wasDeclaredWithTypename(), D->isParameterPack(),
2992 D->hasTypeConstraint(), NumExpanded);
2994 Inst->setAccess(AS_public);
2995 Inst->setImplicit(D->isImplicit());
2996 if (auto *TC = D->getTypeConstraint()) {
2997 if (!D->isImplicit()) {
2998 // Invented template parameter type constraints will be instantiated
2999 // with the corresponding auto-typed parameter as it might reference
3000 // other parameters.
3001 if (SemaRef.SubstTypeConstraint(Inst, TC, TemplateArgs,
3002 EvaluateConstraints))
3003 return nullptr;
3006 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited()) {
3007 TemplateArgumentLoc Output;
3008 if (!SemaRef.SubstTemplateArgument(D->getDefaultArgument(), TemplateArgs,
3009 Output))
3010 Inst->setDefaultArgument(SemaRef.getASTContext(), Output);
3013 // Introduce this template parameter's instantiation into the instantiation
3014 // scope.
3015 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst);
3017 return Inst;
3020 Decl *TemplateDeclInstantiator::VisitNonTypeTemplateParmDecl(
3021 NonTypeTemplateParmDecl *D) {
3022 // Substitute into the type of the non-type template parameter.
3023 TypeLoc TL = D->getTypeSourceInfo()->getTypeLoc();
3024 SmallVector<TypeSourceInfo *, 4> ExpandedParameterPackTypesAsWritten;
3025 SmallVector<QualType, 4> ExpandedParameterPackTypes;
3026 bool IsExpandedParameterPack = false;
3027 TypeSourceInfo *DI;
3028 QualType T;
3029 bool Invalid = false;
3031 if (D->isExpandedParameterPack()) {
3032 // The non-type template parameter pack is an already-expanded pack
3033 // expansion of types. Substitute into each of the expanded types.
3034 ExpandedParameterPackTypes.reserve(D->getNumExpansionTypes());
3035 ExpandedParameterPackTypesAsWritten.reserve(D->getNumExpansionTypes());
3036 for (unsigned I = 0, N = D->getNumExpansionTypes(); I != N; ++I) {
3037 TypeSourceInfo *NewDI =
3038 SemaRef.SubstType(D->getExpansionTypeSourceInfo(I), TemplateArgs,
3039 D->getLocation(), D->getDeclName());
3040 if (!NewDI)
3041 return nullptr;
3043 QualType NewT =
3044 SemaRef.CheckNonTypeTemplateParameterType(NewDI, D->getLocation());
3045 if (NewT.isNull())
3046 return nullptr;
3048 ExpandedParameterPackTypesAsWritten.push_back(NewDI);
3049 ExpandedParameterPackTypes.push_back(NewT);
3052 IsExpandedParameterPack = true;
3053 DI = D->getTypeSourceInfo();
3054 T = DI->getType();
3055 } else if (D->isPackExpansion()) {
3056 // The non-type template parameter pack's type is a pack expansion of types.
3057 // Determine whether we need to expand this parameter pack into separate
3058 // types.
3059 PackExpansionTypeLoc Expansion = TL.castAs<PackExpansionTypeLoc>();
3060 TypeLoc Pattern = Expansion.getPatternLoc();
3061 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
3062 SemaRef.collectUnexpandedParameterPacks(Pattern, Unexpanded);
3064 // Determine whether the set of unexpanded parameter packs can and should
3065 // be expanded.
3066 bool Expand = true;
3067 bool RetainExpansion = false;
3068 std::optional<unsigned> OrigNumExpansions =
3069 Expansion.getTypePtr()->getNumExpansions();
3070 std::optional<unsigned> NumExpansions = OrigNumExpansions;
3071 if (SemaRef.CheckParameterPacksForExpansion(Expansion.getEllipsisLoc(),
3072 Pattern.getSourceRange(),
3073 Unexpanded,
3074 TemplateArgs,
3075 Expand, RetainExpansion,
3076 NumExpansions))
3077 return nullptr;
3079 if (Expand) {
3080 for (unsigned I = 0; I != *NumExpansions; ++I) {
3081 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
3082 TypeSourceInfo *NewDI = SemaRef.SubstType(Pattern, TemplateArgs,
3083 D->getLocation(),
3084 D->getDeclName());
3085 if (!NewDI)
3086 return nullptr;
3088 QualType NewT =
3089 SemaRef.CheckNonTypeTemplateParameterType(NewDI, D->getLocation());
3090 if (NewT.isNull())
3091 return nullptr;
3093 ExpandedParameterPackTypesAsWritten.push_back(NewDI);
3094 ExpandedParameterPackTypes.push_back(NewT);
3097 // Note that we have an expanded parameter pack. The "type" of this
3098 // expanded parameter pack is the original expansion type, but callers
3099 // will end up using the expanded parameter pack types for type-checking.
3100 IsExpandedParameterPack = true;
3101 DI = D->getTypeSourceInfo();
3102 T = DI->getType();
3103 } else {
3104 // We cannot fully expand the pack expansion now, so substitute into the
3105 // pattern and create a new pack expansion type.
3106 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
3107 TypeSourceInfo *NewPattern = SemaRef.SubstType(Pattern, TemplateArgs,
3108 D->getLocation(),
3109 D->getDeclName());
3110 if (!NewPattern)
3111 return nullptr;
3113 SemaRef.CheckNonTypeTemplateParameterType(NewPattern, D->getLocation());
3114 DI = SemaRef.CheckPackExpansion(NewPattern, Expansion.getEllipsisLoc(),
3115 NumExpansions);
3116 if (!DI)
3117 return nullptr;
3119 T = DI->getType();
3121 } else {
3122 // Simple case: substitution into a parameter that is not a parameter pack.
3123 DI = SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs,
3124 D->getLocation(), D->getDeclName());
3125 if (!DI)
3126 return nullptr;
3128 // Check that this type is acceptable for a non-type template parameter.
3129 T = SemaRef.CheckNonTypeTemplateParameterType(DI, D->getLocation());
3130 if (T.isNull()) {
3131 T = SemaRef.Context.IntTy;
3132 Invalid = true;
3136 NonTypeTemplateParmDecl *Param;
3137 if (IsExpandedParameterPack)
3138 Param = NonTypeTemplateParmDecl::Create(
3139 SemaRef.Context, Owner, D->getInnerLocStart(), D->getLocation(),
3140 D->getDepth() - TemplateArgs.getNumSubstitutedLevels(),
3141 D->getPosition(), D->getIdentifier(), T, DI, ExpandedParameterPackTypes,
3142 ExpandedParameterPackTypesAsWritten);
3143 else
3144 Param = NonTypeTemplateParmDecl::Create(
3145 SemaRef.Context, Owner, D->getInnerLocStart(), D->getLocation(),
3146 D->getDepth() - TemplateArgs.getNumSubstitutedLevels(),
3147 D->getPosition(), D->getIdentifier(), T, D->isParameterPack(), DI);
3149 if (AutoTypeLoc AutoLoc = DI->getTypeLoc().getContainedAutoTypeLoc())
3150 if (AutoLoc.isConstrained()) {
3151 SourceLocation EllipsisLoc;
3152 if (IsExpandedParameterPack)
3153 EllipsisLoc =
3154 DI->getTypeLoc().getAs<PackExpansionTypeLoc>().getEllipsisLoc();
3155 else if (auto *Constraint = dyn_cast_if_present<CXXFoldExpr>(
3156 D->getPlaceholderTypeConstraint()))
3157 EllipsisLoc = Constraint->getEllipsisLoc();
3158 // Note: We attach the uninstantiated constriant here, so that it can be
3159 // instantiated relative to the top level, like all our other
3160 // constraints.
3161 if (SemaRef.AttachTypeConstraint(AutoLoc, /*NewConstrainedParm=*/Param,
3162 /*OrigConstrainedParm=*/D, EllipsisLoc))
3163 Invalid = true;
3166 Param->setAccess(AS_public);
3167 Param->setImplicit(D->isImplicit());
3168 if (Invalid)
3169 Param->setInvalidDecl();
3171 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited()) {
3172 EnterExpressionEvaluationContext ConstantEvaluated(
3173 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
3174 TemplateArgumentLoc Result;
3175 if (!SemaRef.SubstTemplateArgument(D->getDefaultArgument(), TemplateArgs,
3176 Result))
3177 Param->setDefaultArgument(SemaRef.Context, Result);
3180 // Introduce this template parameter's instantiation into the instantiation
3181 // scope.
3182 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
3183 return Param;
3186 static void collectUnexpandedParameterPacks(
3187 Sema &S,
3188 TemplateParameterList *Params,
3189 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
3190 for (const auto &P : *Params) {
3191 if (P->isTemplateParameterPack())
3192 continue;
3193 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P))
3194 S.collectUnexpandedParameterPacks(NTTP->getTypeSourceInfo()->getTypeLoc(),
3195 Unexpanded);
3196 if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(P))
3197 collectUnexpandedParameterPacks(S, TTP->getTemplateParameters(),
3198 Unexpanded);
3202 Decl *
3203 TemplateDeclInstantiator::VisitTemplateTemplateParmDecl(
3204 TemplateTemplateParmDecl *D) {
3205 // Instantiate the template parameter list of the template template parameter.
3206 TemplateParameterList *TempParams = D->getTemplateParameters();
3207 TemplateParameterList *InstParams;
3208 SmallVector<TemplateParameterList*, 8> ExpandedParams;
3210 bool IsExpandedParameterPack = false;
3212 if (D->isExpandedParameterPack()) {
3213 // The template template parameter pack is an already-expanded pack
3214 // expansion of template parameters. Substitute into each of the expanded
3215 // parameters.
3216 ExpandedParams.reserve(D->getNumExpansionTemplateParameters());
3217 for (unsigned I = 0, N = D->getNumExpansionTemplateParameters();
3218 I != N; ++I) {
3219 LocalInstantiationScope Scope(SemaRef);
3220 TemplateParameterList *Expansion =
3221 SubstTemplateParams(D->getExpansionTemplateParameters(I));
3222 if (!Expansion)
3223 return nullptr;
3224 ExpandedParams.push_back(Expansion);
3227 IsExpandedParameterPack = true;
3228 InstParams = TempParams;
3229 } else if (D->isPackExpansion()) {
3230 // The template template parameter pack expands to a pack of template
3231 // template parameters. Determine whether we need to expand this parameter
3232 // pack into separate parameters.
3233 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
3234 collectUnexpandedParameterPacks(SemaRef, D->getTemplateParameters(),
3235 Unexpanded);
3237 // Determine whether the set of unexpanded parameter packs can and should
3238 // be expanded.
3239 bool Expand = true;
3240 bool RetainExpansion = false;
3241 std::optional<unsigned> NumExpansions;
3242 if (SemaRef.CheckParameterPacksForExpansion(D->getLocation(),
3243 TempParams->getSourceRange(),
3244 Unexpanded,
3245 TemplateArgs,
3246 Expand, RetainExpansion,
3247 NumExpansions))
3248 return nullptr;
3250 if (Expand) {
3251 for (unsigned I = 0; I != *NumExpansions; ++I) {
3252 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
3253 LocalInstantiationScope Scope(SemaRef);
3254 TemplateParameterList *Expansion = SubstTemplateParams(TempParams);
3255 if (!Expansion)
3256 return nullptr;
3257 ExpandedParams.push_back(Expansion);
3260 // Note that we have an expanded parameter pack. The "type" of this
3261 // expanded parameter pack is the original expansion type, but callers
3262 // will end up using the expanded parameter pack types for type-checking.
3263 IsExpandedParameterPack = true;
3264 InstParams = TempParams;
3265 } else {
3266 // We cannot fully expand the pack expansion now, so just substitute
3267 // into the pattern.
3268 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
3270 LocalInstantiationScope Scope(SemaRef);
3271 InstParams = SubstTemplateParams(TempParams);
3272 if (!InstParams)
3273 return nullptr;
3275 } else {
3276 // Perform the actual substitution of template parameters within a new,
3277 // local instantiation scope.
3278 LocalInstantiationScope Scope(SemaRef);
3279 InstParams = SubstTemplateParams(TempParams);
3280 if (!InstParams)
3281 return nullptr;
3284 // Build the template template parameter.
3285 TemplateTemplateParmDecl *Param;
3286 if (IsExpandedParameterPack)
3287 Param = TemplateTemplateParmDecl::Create(
3288 SemaRef.Context, Owner, D->getLocation(),
3289 D->getDepth() - TemplateArgs.getNumSubstitutedLevels(),
3290 D->getPosition(), D->getIdentifier(), D->wasDeclaredWithTypename(),
3291 InstParams, ExpandedParams);
3292 else
3293 Param = TemplateTemplateParmDecl::Create(
3294 SemaRef.Context, Owner, D->getLocation(),
3295 D->getDepth() - TemplateArgs.getNumSubstitutedLevels(),
3296 D->getPosition(), D->isParameterPack(), D->getIdentifier(),
3297 D->wasDeclaredWithTypename(), InstParams);
3298 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited()) {
3299 NestedNameSpecifierLoc QualifierLoc =
3300 D->getDefaultArgument().getTemplateQualifierLoc();
3301 QualifierLoc =
3302 SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgs);
3303 TemplateName TName = SemaRef.SubstTemplateName(
3304 QualifierLoc, D->getDefaultArgument().getArgument().getAsTemplate(),
3305 D->getDefaultArgument().getTemplateNameLoc(), TemplateArgs);
3306 if (!TName.isNull())
3307 Param->setDefaultArgument(
3308 SemaRef.Context,
3309 TemplateArgumentLoc(SemaRef.Context, TemplateArgument(TName),
3310 D->getDefaultArgument().getTemplateQualifierLoc(),
3311 D->getDefaultArgument().getTemplateNameLoc()));
3313 Param->setAccess(AS_public);
3314 Param->setImplicit(D->isImplicit());
3316 // Introduce this template parameter's instantiation into the instantiation
3317 // scope.
3318 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
3320 return Param;
3323 Decl *TemplateDeclInstantiator::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
3324 // Using directives are never dependent (and never contain any types or
3325 // expressions), so they require no explicit instantiation work.
3327 UsingDirectiveDecl *Inst
3328 = UsingDirectiveDecl::Create(SemaRef.Context, Owner, D->getLocation(),
3329 D->getNamespaceKeyLocation(),
3330 D->getQualifierLoc(),
3331 D->getIdentLocation(),
3332 D->getNominatedNamespace(),
3333 D->getCommonAncestor());
3335 // Add the using directive to its declaration context
3336 // only if this is not a function or method.
3337 if (!Owner->isFunctionOrMethod())
3338 Owner->addDecl(Inst);
3340 return Inst;
3343 Decl *TemplateDeclInstantiator::VisitBaseUsingDecls(BaseUsingDecl *D,
3344 BaseUsingDecl *Inst,
3345 LookupResult *Lookup) {
3347 bool isFunctionScope = Owner->isFunctionOrMethod();
3349 for (auto *Shadow : D->shadows()) {
3350 // FIXME: UsingShadowDecl doesn't preserve its immediate target, so
3351 // reconstruct it in the case where it matters. Hm, can we extract it from
3352 // the DeclSpec when parsing and save it in the UsingDecl itself?
3353 NamedDecl *OldTarget = Shadow->getTargetDecl();
3354 if (auto *CUSD = dyn_cast<ConstructorUsingShadowDecl>(Shadow))
3355 if (auto *BaseShadow = CUSD->getNominatedBaseClassShadowDecl())
3356 OldTarget = BaseShadow;
3358 NamedDecl *InstTarget = nullptr;
3359 if (auto *EmptyD =
3360 dyn_cast<UnresolvedUsingIfExistsDecl>(Shadow->getTargetDecl())) {
3361 InstTarget = UnresolvedUsingIfExistsDecl::Create(
3362 SemaRef.Context, Owner, EmptyD->getLocation(), EmptyD->getDeclName());
3363 } else {
3364 InstTarget = cast_or_null<NamedDecl>(SemaRef.FindInstantiatedDecl(
3365 Shadow->getLocation(), OldTarget, TemplateArgs));
3367 if (!InstTarget)
3368 return nullptr;
3370 UsingShadowDecl *PrevDecl = nullptr;
3371 if (Lookup &&
3372 SemaRef.CheckUsingShadowDecl(Inst, InstTarget, *Lookup, PrevDecl))
3373 continue;
3375 if (UsingShadowDecl *OldPrev = getPreviousDeclForInstantiation(Shadow))
3376 PrevDecl = cast_or_null<UsingShadowDecl>(SemaRef.FindInstantiatedDecl(
3377 Shadow->getLocation(), OldPrev, TemplateArgs));
3379 UsingShadowDecl *InstShadow = SemaRef.BuildUsingShadowDecl(
3380 /*Scope*/ nullptr, Inst, InstTarget, PrevDecl);
3381 SemaRef.Context.setInstantiatedFromUsingShadowDecl(InstShadow, Shadow);
3383 if (isFunctionScope)
3384 SemaRef.CurrentInstantiationScope->InstantiatedLocal(Shadow, InstShadow);
3387 return Inst;
3390 Decl *TemplateDeclInstantiator::VisitUsingDecl(UsingDecl *D) {
3392 // The nested name specifier may be dependent, for example
3393 // template <typename T> struct t {
3394 // struct s1 { T f1(); };
3395 // struct s2 : s1 { using s1::f1; };
3396 // };
3397 // template struct t<int>;
3398 // Here, in using s1::f1, s1 refers to t<T>::s1;
3399 // we need to substitute for t<int>::s1.
3400 NestedNameSpecifierLoc QualifierLoc
3401 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
3402 TemplateArgs);
3403 if (!QualifierLoc)
3404 return nullptr;
3406 // For an inheriting constructor declaration, the name of the using
3407 // declaration is the name of a constructor in this class, not in the
3408 // base class.
3409 DeclarationNameInfo NameInfo = D->getNameInfo();
3410 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName)
3411 if (auto *RD = dyn_cast<CXXRecordDecl>(SemaRef.CurContext))
3412 NameInfo.setName(SemaRef.Context.DeclarationNames.getCXXConstructorName(
3413 SemaRef.Context.getCanonicalType(SemaRef.Context.getRecordType(RD))));
3415 // We only need to do redeclaration lookups if we're in a class scope (in
3416 // fact, it's not really even possible in non-class scopes).
3417 bool CheckRedeclaration = Owner->isRecord();
3418 LookupResult Prev(SemaRef, NameInfo, Sema::LookupUsingDeclName,
3419 RedeclarationKind::ForVisibleRedeclaration);
3421 UsingDecl *NewUD = UsingDecl::Create(SemaRef.Context, Owner,
3422 D->getUsingLoc(),
3423 QualifierLoc,
3424 NameInfo,
3425 D->hasTypename());
3427 CXXScopeSpec SS;
3428 SS.Adopt(QualifierLoc);
3429 if (CheckRedeclaration) {
3430 Prev.setHideTags(false);
3431 SemaRef.LookupQualifiedName(Prev, Owner);
3433 // Check for invalid redeclarations.
3434 if (SemaRef.CheckUsingDeclRedeclaration(D->getUsingLoc(),
3435 D->hasTypename(), SS,
3436 D->getLocation(), Prev))
3437 NewUD->setInvalidDecl();
3440 if (!NewUD->isInvalidDecl() &&
3441 SemaRef.CheckUsingDeclQualifier(D->getUsingLoc(), D->hasTypename(), SS,
3442 NameInfo, D->getLocation(), nullptr, D))
3443 NewUD->setInvalidDecl();
3445 SemaRef.Context.setInstantiatedFromUsingDecl(NewUD, D);
3446 NewUD->setAccess(D->getAccess());
3447 Owner->addDecl(NewUD);
3449 // Don't process the shadow decls for an invalid decl.
3450 if (NewUD->isInvalidDecl())
3451 return NewUD;
3453 // If the using scope was dependent, or we had dependent bases, we need to
3454 // recheck the inheritance
3455 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName)
3456 SemaRef.CheckInheritingConstructorUsingDecl(NewUD);
3458 return VisitBaseUsingDecls(D, NewUD, CheckRedeclaration ? &Prev : nullptr);
3461 Decl *TemplateDeclInstantiator::VisitUsingEnumDecl(UsingEnumDecl *D) {
3462 // Cannot be a dependent type, but still could be an instantiation
3463 EnumDecl *EnumD = cast_or_null<EnumDecl>(SemaRef.FindInstantiatedDecl(
3464 D->getLocation(), D->getEnumDecl(), TemplateArgs));
3466 if (SemaRef.RequireCompleteEnumDecl(EnumD, EnumD->getLocation()))
3467 return nullptr;
3469 TypeSourceInfo *TSI = SemaRef.SubstType(D->getEnumType(), TemplateArgs,
3470 D->getLocation(), D->getDeclName());
3472 if (!TSI)
3473 return nullptr;
3475 UsingEnumDecl *NewUD =
3476 UsingEnumDecl::Create(SemaRef.Context, Owner, D->getUsingLoc(),
3477 D->getEnumLoc(), D->getLocation(), TSI);
3479 SemaRef.Context.setInstantiatedFromUsingEnumDecl(NewUD, D);
3480 NewUD->setAccess(D->getAccess());
3481 Owner->addDecl(NewUD);
3483 // Don't process the shadow decls for an invalid decl.
3484 if (NewUD->isInvalidDecl())
3485 return NewUD;
3487 // We don't have to recheck for duplication of the UsingEnumDecl itself, as it
3488 // cannot be dependent, and will therefore have been checked during template
3489 // definition.
3491 return VisitBaseUsingDecls(D, NewUD, nullptr);
3494 Decl *TemplateDeclInstantiator::VisitUsingShadowDecl(UsingShadowDecl *D) {
3495 // Ignore these; we handle them in bulk when processing the UsingDecl.
3496 return nullptr;
3499 Decl *TemplateDeclInstantiator::VisitConstructorUsingShadowDecl(
3500 ConstructorUsingShadowDecl *D) {
3501 // Ignore these; we handle them in bulk when processing the UsingDecl.
3502 return nullptr;
3505 template <typename T>
3506 Decl *TemplateDeclInstantiator::instantiateUnresolvedUsingDecl(
3507 T *D, bool InstantiatingPackElement) {
3508 // If this is a pack expansion, expand it now.
3509 if (D->isPackExpansion() && !InstantiatingPackElement) {
3510 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
3511 SemaRef.collectUnexpandedParameterPacks(D->getQualifierLoc(), Unexpanded);
3512 SemaRef.collectUnexpandedParameterPacks(D->getNameInfo(), Unexpanded);
3514 // Determine whether the set of unexpanded parameter packs can and should
3515 // be expanded.
3516 bool Expand = true;
3517 bool RetainExpansion = false;
3518 std::optional<unsigned> NumExpansions;
3519 if (SemaRef.CheckParameterPacksForExpansion(
3520 D->getEllipsisLoc(), D->getSourceRange(), Unexpanded, TemplateArgs,
3521 Expand, RetainExpansion, NumExpansions))
3522 return nullptr;
3524 // This declaration cannot appear within a function template signature,
3525 // so we can't have a partial argument list for a parameter pack.
3526 assert(!RetainExpansion &&
3527 "should never need to retain an expansion for UsingPackDecl");
3529 if (!Expand) {
3530 // We cannot fully expand the pack expansion now, so substitute into the
3531 // pattern and create a new pack expansion.
3532 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
3533 return instantiateUnresolvedUsingDecl(D, true);
3536 // Within a function, we don't have any normal way to check for conflicts
3537 // between shadow declarations from different using declarations in the
3538 // same pack expansion, but this is always ill-formed because all expansions
3539 // must produce (conflicting) enumerators.
3541 // Sadly we can't just reject this in the template definition because it
3542 // could be valid if the pack is empty or has exactly one expansion.
3543 if (D->getDeclContext()->isFunctionOrMethod() && *NumExpansions > 1) {
3544 SemaRef.Diag(D->getEllipsisLoc(),
3545 diag::err_using_decl_redeclaration_expansion);
3546 return nullptr;
3549 // Instantiate the slices of this pack and build a UsingPackDecl.
3550 SmallVector<NamedDecl*, 8> Expansions;
3551 for (unsigned I = 0; I != *NumExpansions; ++I) {
3552 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
3553 Decl *Slice = instantiateUnresolvedUsingDecl(D, true);
3554 if (!Slice)
3555 return nullptr;
3556 // Note that we can still get unresolved using declarations here, if we
3557 // had arguments for all packs but the pattern also contained other
3558 // template arguments (this only happens during partial substitution, eg
3559 // into the body of a generic lambda in a function template).
3560 Expansions.push_back(cast<NamedDecl>(Slice));
3563 auto *NewD = SemaRef.BuildUsingPackDecl(D, Expansions);
3564 if (isDeclWithinFunction(D))
3565 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewD);
3566 return NewD;
3569 UnresolvedUsingTypenameDecl *TD = dyn_cast<UnresolvedUsingTypenameDecl>(D);
3570 SourceLocation TypenameLoc = TD ? TD->getTypenameLoc() : SourceLocation();
3572 NestedNameSpecifierLoc QualifierLoc
3573 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
3574 TemplateArgs);
3575 if (!QualifierLoc)
3576 return nullptr;
3578 CXXScopeSpec SS;
3579 SS.Adopt(QualifierLoc);
3581 DeclarationNameInfo NameInfo
3582 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
3584 // Produce a pack expansion only if we're not instantiating a particular
3585 // slice of a pack expansion.
3586 bool InstantiatingSlice = D->getEllipsisLoc().isValid() &&
3587 SemaRef.ArgumentPackSubstitutionIndex != -1;
3588 SourceLocation EllipsisLoc =
3589 InstantiatingSlice ? SourceLocation() : D->getEllipsisLoc();
3591 bool IsUsingIfExists = D->template hasAttr<UsingIfExistsAttr>();
3592 NamedDecl *UD = SemaRef.BuildUsingDeclaration(
3593 /*Scope*/ nullptr, D->getAccess(), D->getUsingLoc(),
3594 /*HasTypename*/ TD, TypenameLoc, SS, NameInfo, EllipsisLoc,
3595 ParsedAttributesView(),
3596 /*IsInstantiation*/ true, IsUsingIfExists);
3597 if (UD) {
3598 SemaRef.InstantiateAttrs(TemplateArgs, D, UD);
3599 SemaRef.Context.setInstantiatedFromUsingDecl(UD, D);
3602 return UD;
3605 Decl *TemplateDeclInstantiator::VisitUnresolvedUsingTypenameDecl(
3606 UnresolvedUsingTypenameDecl *D) {
3607 return instantiateUnresolvedUsingDecl(D);
3610 Decl *TemplateDeclInstantiator::VisitUnresolvedUsingValueDecl(
3611 UnresolvedUsingValueDecl *D) {
3612 return instantiateUnresolvedUsingDecl(D);
3615 Decl *TemplateDeclInstantiator::VisitUnresolvedUsingIfExistsDecl(
3616 UnresolvedUsingIfExistsDecl *D) {
3617 llvm_unreachable("referring to unresolved decl out of UsingShadowDecl");
3620 Decl *TemplateDeclInstantiator::VisitUsingPackDecl(UsingPackDecl *D) {
3621 SmallVector<NamedDecl*, 8> Expansions;
3622 for (auto *UD : D->expansions()) {
3623 if (NamedDecl *NewUD =
3624 SemaRef.FindInstantiatedDecl(D->getLocation(), UD, TemplateArgs))
3625 Expansions.push_back(NewUD);
3626 else
3627 return nullptr;
3630 auto *NewD = SemaRef.BuildUsingPackDecl(D, Expansions);
3631 if (isDeclWithinFunction(D))
3632 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewD);
3633 return NewD;
3636 Decl *TemplateDeclInstantiator::VisitOMPThreadPrivateDecl(
3637 OMPThreadPrivateDecl *D) {
3638 SmallVector<Expr *, 5> Vars;
3639 for (auto *I : D->varlist()) {
3640 Expr *Var = SemaRef.SubstExpr(I, TemplateArgs).get();
3641 assert(isa<DeclRefExpr>(Var) && "threadprivate arg is not a DeclRefExpr");
3642 Vars.push_back(Var);
3645 OMPThreadPrivateDecl *TD =
3646 SemaRef.OpenMP().CheckOMPThreadPrivateDecl(D->getLocation(), Vars);
3648 TD->setAccess(AS_public);
3649 Owner->addDecl(TD);
3651 return TD;
3654 Decl *TemplateDeclInstantiator::VisitOMPAllocateDecl(OMPAllocateDecl *D) {
3655 SmallVector<Expr *, 5> Vars;
3656 for (auto *I : D->varlist()) {
3657 Expr *Var = SemaRef.SubstExpr(I, TemplateArgs).get();
3658 assert(isa<DeclRefExpr>(Var) && "allocate arg is not a DeclRefExpr");
3659 Vars.push_back(Var);
3661 SmallVector<OMPClause *, 4> Clauses;
3662 // Copy map clauses from the original mapper.
3663 for (OMPClause *C : D->clauselists()) {
3664 OMPClause *IC = nullptr;
3665 if (auto *AC = dyn_cast<OMPAllocatorClause>(C)) {
3666 ExprResult NewE = SemaRef.SubstExpr(AC->getAllocator(), TemplateArgs);
3667 if (!NewE.isUsable())
3668 continue;
3669 IC = SemaRef.OpenMP().ActOnOpenMPAllocatorClause(
3670 NewE.get(), AC->getBeginLoc(), AC->getLParenLoc(), AC->getEndLoc());
3671 } else if (auto *AC = dyn_cast<OMPAlignClause>(C)) {
3672 ExprResult NewE = SemaRef.SubstExpr(AC->getAlignment(), TemplateArgs);
3673 if (!NewE.isUsable())
3674 continue;
3675 IC = SemaRef.OpenMP().ActOnOpenMPAlignClause(
3676 NewE.get(), AC->getBeginLoc(), AC->getLParenLoc(), AC->getEndLoc());
3677 // If align clause value ends up being invalid, this can end up null.
3678 if (!IC)
3679 continue;
3681 Clauses.push_back(IC);
3684 Sema::DeclGroupPtrTy Res = SemaRef.OpenMP().ActOnOpenMPAllocateDirective(
3685 D->getLocation(), Vars, Clauses, Owner);
3686 if (Res.get().isNull())
3687 return nullptr;
3688 return Res.get().getSingleDecl();
3691 Decl *TemplateDeclInstantiator::VisitOMPRequiresDecl(OMPRequiresDecl *D) {
3692 llvm_unreachable(
3693 "Requires directive cannot be instantiated within a dependent context");
3696 Decl *TemplateDeclInstantiator::VisitOMPDeclareReductionDecl(
3697 OMPDeclareReductionDecl *D) {
3698 // Instantiate type and check if it is allowed.
3699 const bool RequiresInstantiation =
3700 D->getType()->isDependentType() ||
3701 D->getType()->isInstantiationDependentType() ||
3702 D->getType()->containsUnexpandedParameterPack();
3703 QualType SubstReductionType;
3704 if (RequiresInstantiation) {
3705 SubstReductionType = SemaRef.OpenMP().ActOnOpenMPDeclareReductionType(
3706 D->getLocation(),
3707 ParsedType::make(SemaRef.SubstType(
3708 D->getType(), TemplateArgs, D->getLocation(), DeclarationName())));
3709 } else {
3710 SubstReductionType = D->getType();
3712 if (SubstReductionType.isNull())
3713 return nullptr;
3714 Expr *Combiner = D->getCombiner();
3715 Expr *Init = D->getInitializer();
3716 bool IsCorrect = true;
3717 // Create instantiated copy.
3718 std::pair<QualType, SourceLocation> ReductionTypes[] = {
3719 std::make_pair(SubstReductionType, D->getLocation())};
3720 auto *PrevDeclInScope = D->getPrevDeclInScope();
3721 if (PrevDeclInScope && !PrevDeclInScope->isInvalidDecl()) {
3722 PrevDeclInScope = cast<OMPDeclareReductionDecl>(
3723 cast<Decl *>(*SemaRef.CurrentInstantiationScope->findInstantiationOf(
3724 PrevDeclInScope)));
3726 auto DRD = SemaRef.OpenMP().ActOnOpenMPDeclareReductionDirectiveStart(
3727 /*S=*/nullptr, Owner, D->getDeclName(), ReductionTypes, D->getAccess(),
3728 PrevDeclInScope);
3729 auto *NewDRD = cast<OMPDeclareReductionDecl>(DRD.get().getSingleDecl());
3730 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewDRD);
3731 Expr *SubstCombiner = nullptr;
3732 Expr *SubstInitializer = nullptr;
3733 // Combiners instantiation sequence.
3734 if (Combiner) {
3735 SemaRef.OpenMP().ActOnOpenMPDeclareReductionCombinerStart(
3736 /*S=*/nullptr, NewDRD);
3737 SemaRef.CurrentInstantiationScope->InstantiatedLocal(
3738 cast<DeclRefExpr>(D->getCombinerIn())->getDecl(),
3739 cast<DeclRefExpr>(NewDRD->getCombinerIn())->getDecl());
3740 SemaRef.CurrentInstantiationScope->InstantiatedLocal(
3741 cast<DeclRefExpr>(D->getCombinerOut())->getDecl(),
3742 cast<DeclRefExpr>(NewDRD->getCombinerOut())->getDecl());
3743 auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(Owner);
3744 Sema::CXXThisScopeRAII ThisScope(SemaRef, ThisContext, Qualifiers(),
3745 ThisContext);
3746 SubstCombiner = SemaRef.SubstExpr(Combiner, TemplateArgs).get();
3747 SemaRef.OpenMP().ActOnOpenMPDeclareReductionCombinerEnd(NewDRD,
3748 SubstCombiner);
3750 // Initializers instantiation sequence.
3751 if (Init) {
3752 VarDecl *OmpPrivParm =
3753 SemaRef.OpenMP().ActOnOpenMPDeclareReductionInitializerStart(
3754 /*S=*/nullptr, NewDRD);
3755 SemaRef.CurrentInstantiationScope->InstantiatedLocal(
3756 cast<DeclRefExpr>(D->getInitOrig())->getDecl(),
3757 cast<DeclRefExpr>(NewDRD->getInitOrig())->getDecl());
3758 SemaRef.CurrentInstantiationScope->InstantiatedLocal(
3759 cast<DeclRefExpr>(D->getInitPriv())->getDecl(),
3760 cast<DeclRefExpr>(NewDRD->getInitPriv())->getDecl());
3761 if (D->getInitializerKind() == OMPDeclareReductionInitKind::Call) {
3762 SubstInitializer = SemaRef.SubstExpr(Init, TemplateArgs).get();
3763 } else {
3764 auto *OldPrivParm =
3765 cast<VarDecl>(cast<DeclRefExpr>(D->getInitPriv())->getDecl());
3766 IsCorrect = IsCorrect && OldPrivParm->hasInit();
3767 if (IsCorrect)
3768 SemaRef.InstantiateVariableInitializer(OmpPrivParm, OldPrivParm,
3769 TemplateArgs);
3771 SemaRef.OpenMP().ActOnOpenMPDeclareReductionInitializerEnd(
3772 NewDRD, SubstInitializer, OmpPrivParm);
3774 IsCorrect = IsCorrect && SubstCombiner &&
3775 (!Init ||
3776 (D->getInitializerKind() == OMPDeclareReductionInitKind::Call &&
3777 SubstInitializer) ||
3778 (D->getInitializerKind() != OMPDeclareReductionInitKind::Call &&
3779 !SubstInitializer));
3781 (void)SemaRef.OpenMP().ActOnOpenMPDeclareReductionDirectiveEnd(
3782 /*S=*/nullptr, DRD, IsCorrect && !D->isInvalidDecl());
3784 return NewDRD;
3787 Decl *
3788 TemplateDeclInstantiator::VisitOMPDeclareMapperDecl(OMPDeclareMapperDecl *D) {
3789 // Instantiate type and check if it is allowed.
3790 const bool RequiresInstantiation =
3791 D->getType()->isDependentType() ||
3792 D->getType()->isInstantiationDependentType() ||
3793 D->getType()->containsUnexpandedParameterPack();
3794 QualType SubstMapperTy;
3795 DeclarationName VN = D->getVarName();
3796 if (RequiresInstantiation) {
3797 SubstMapperTy = SemaRef.OpenMP().ActOnOpenMPDeclareMapperType(
3798 D->getLocation(),
3799 ParsedType::make(SemaRef.SubstType(D->getType(), TemplateArgs,
3800 D->getLocation(), VN)));
3801 } else {
3802 SubstMapperTy = D->getType();
3804 if (SubstMapperTy.isNull())
3805 return nullptr;
3806 // Create an instantiated copy of mapper.
3807 auto *PrevDeclInScope = D->getPrevDeclInScope();
3808 if (PrevDeclInScope && !PrevDeclInScope->isInvalidDecl()) {
3809 PrevDeclInScope = cast<OMPDeclareMapperDecl>(
3810 cast<Decl *>(*SemaRef.CurrentInstantiationScope->findInstantiationOf(
3811 PrevDeclInScope)));
3813 bool IsCorrect = true;
3814 SmallVector<OMPClause *, 6> Clauses;
3815 // Instantiate the mapper variable.
3816 DeclarationNameInfo DirName;
3817 SemaRef.OpenMP().StartOpenMPDSABlock(llvm::omp::OMPD_declare_mapper, DirName,
3818 /*S=*/nullptr,
3819 (*D->clauselist_begin())->getBeginLoc());
3820 ExprResult MapperVarRef =
3821 SemaRef.OpenMP().ActOnOpenMPDeclareMapperDirectiveVarDecl(
3822 /*S=*/nullptr, SubstMapperTy, D->getLocation(), VN);
3823 SemaRef.CurrentInstantiationScope->InstantiatedLocal(
3824 cast<DeclRefExpr>(D->getMapperVarRef())->getDecl(),
3825 cast<DeclRefExpr>(MapperVarRef.get())->getDecl());
3826 auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(Owner);
3827 Sema::CXXThisScopeRAII ThisScope(SemaRef, ThisContext, Qualifiers(),
3828 ThisContext);
3829 // Instantiate map clauses.
3830 for (OMPClause *C : D->clauselists()) {
3831 auto *OldC = cast<OMPMapClause>(C);
3832 SmallVector<Expr *, 4> NewVars;
3833 for (Expr *OE : OldC->varlist()) {
3834 Expr *NE = SemaRef.SubstExpr(OE, TemplateArgs).get();
3835 if (!NE) {
3836 IsCorrect = false;
3837 break;
3839 NewVars.push_back(NE);
3841 if (!IsCorrect)
3842 break;
3843 NestedNameSpecifierLoc NewQualifierLoc =
3844 SemaRef.SubstNestedNameSpecifierLoc(OldC->getMapperQualifierLoc(),
3845 TemplateArgs);
3846 CXXScopeSpec SS;
3847 SS.Adopt(NewQualifierLoc);
3848 DeclarationNameInfo NewNameInfo =
3849 SemaRef.SubstDeclarationNameInfo(OldC->getMapperIdInfo(), TemplateArgs);
3850 OMPVarListLocTy Locs(OldC->getBeginLoc(), OldC->getLParenLoc(),
3851 OldC->getEndLoc());
3852 OMPClause *NewC = SemaRef.OpenMP().ActOnOpenMPMapClause(
3853 OldC->getIteratorModifier(), OldC->getMapTypeModifiers(),
3854 OldC->getMapTypeModifiersLoc(), SS, NewNameInfo, OldC->getMapType(),
3855 OldC->isImplicitMapType(), OldC->getMapLoc(), OldC->getColonLoc(),
3856 NewVars, Locs);
3857 Clauses.push_back(NewC);
3859 SemaRef.OpenMP().EndOpenMPDSABlock(nullptr);
3860 if (!IsCorrect)
3861 return nullptr;
3862 Sema::DeclGroupPtrTy DG = SemaRef.OpenMP().ActOnOpenMPDeclareMapperDirective(
3863 /*S=*/nullptr, Owner, D->getDeclName(), SubstMapperTy, D->getLocation(),
3864 VN, D->getAccess(), MapperVarRef.get(), Clauses, PrevDeclInScope);
3865 Decl *NewDMD = DG.get().getSingleDecl();
3866 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewDMD);
3867 return NewDMD;
3870 Decl *TemplateDeclInstantiator::VisitOMPCapturedExprDecl(
3871 OMPCapturedExprDecl * /*D*/) {
3872 llvm_unreachable("Should not be met in templates");
3875 Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D) {
3876 return VisitFunctionDecl(D, nullptr);
3879 Decl *
3880 TemplateDeclInstantiator::VisitCXXDeductionGuideDecl(CXXDeductionGuideDecl *D) {
3881 Decl *Inst = VisitFunctionDecl(D, nullptr);
3882 if (Inst && !D->getDescribedFunctionTemplate())
3883 Owner->addDecl(Inst);
3884 return Inst;
3887 Decl *TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D) {
3888 return VisitCXXMethodDecl(D, nullptr);
3891 Decl *TemplateDeclInstantiator::VisitRecordDecl(RecordDecl *D) {
3892 llvm_unreachable("There are only CXXRecordDecls in C++");
3895 Decl *
3896 TemplateDeclInstantiator::VisitClassTemplateSpecializationDecl(
3897 ClassTemplateSpecializationDecl *D) {
3898 // As a MS extension, we permit class-scope explicit specialization
3899 // of member class templates.
3900 ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
3901 assert(ClassTemplate->getDeclContext()->isRecord() &&
3902 D->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
3903 "can only instantiate an explicit specialization "
3904 "for a member class template");
3906 // Lookup the already-instantiated declaration in the instantiation
3907 // of the class template.
3908 ClassTemplateDecl *InstClassTemplate =
3909 cast_or_null<ClassTemplateDecl>(SemaRef.FindInstantiatedDecl(
3910 D->getLocation(), ClassTemplate, TemplateArgs));
3911 if (!InstClassTemplate)
3912 return nullptr;
3914 // Substitute into the template arguments of the class template explicit
3915 // specialization.
3916 TemplateArgumentListInfo InstTemplateArgs;
3917 if (const ASTTemplateArgumentListInfo *TemplateArgsInfo =
3918 D->getTemplateArgsAsWritten()) {
3919 InstTemplateArgs.setLAngleLoc(TemplateArgsInfo->getLAngleLoc());
3920 InstTemplateArgs.setRAngleLoc(TemplateArgsInfo->getRAngleLoc());
3922 if (SemaRef.SubstTemplateArguments(TemplateArgsInfo->arguments(),
3923 TemplateArgs, InstTemplateArgs))
3924 return nullptr;
3927 // Check that the template argument list is well-formed for this
3928 // class template.
3929 SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
3930 if (SemaRef.CheckTemplateArgumentList(
3931 InstClassTemplate, D->getLocation(), InstTemplateArgs,
3932 /*DefaultArgs=*/{}, false, SugaredConverted, CanonicalConverted,
3933 /*UpdateArgsWithConversions=*/true))
3934 return nullptr;
3936 // Figure out where to insert this class template explicit specialization
3937 // in the member template's set of class template explicit specializations.
3938 void *InsertPos = nullptr;
3939 ClassTemplateSpecializationDecl *PrevDecl =
3940 InstClassTemplate->findSpecialization(CanonicalConverted, InsertPos);
3942 // Check whether we've already seen a conflicting instantiation of this
3943 // declaration (for instance, if there was a prior implicit instantiation).
3944 bool Ignored;
3945 if (PrevDecl &&
3946 SemaRef.CheckSpecializationInstantiationRedecl(D->getLocation(),
3947 D->getSpecializationKind(),
3948 PrevDecl,
3949 PrevDecl->getSpecializationKind(),
3950 PrevDecl->getPointOfInstantiation(),
3951 Ignored))
3952 return nullptr;
3954 // If PrevDecl was a definition and D is also a definition, diagnose.
3955 // This happens in cases like:
3957 // template<typename T, typename U>
3958 // struct Outer {
3959 // template<typename X> struct Inner;
3960 // template<> struct Inner<T> {};
3961 // template<> struct Inner<U> {};
3962 // };
3964 // Outer<int, int> outer; // error: the explicit specializations of Inner
3965 // // have the same signature.
3966 if (PrevDecl && PrevDecl->getDefinition() &&
3967 D->isThisDeclarationADefinition()) {
3968 SemaRef.Diag(D->getLocation(), diag::err_redefinition) << PrevDecl;
3969 SemaRef.Diag(PrevDecl->getDefinition()->getLocation(),
3970 diag::note_previous_definition);
3971 return nullptr;
3974 // Create the class template partial specialization declaration.
3975 ClassTemplateSpecializationDecl *InstD =
3976 ClassTemplateSpecializationDecl::Create(
3977 SemaRef.Context, D->getTagKind(), Owner, D->getBeginLoc(),
3978 D->getLocation(), InstClassTemplate, CanonicalConverted, PrevDecl);
3979 InstD->setTemplateArgsAsWritten(InstTemplateArgs);
3981 // Add this partial specialization to the set of class template partial
3982 // specializations.
3983 if (!PrevDecl)
3984 InstClassTemplate->AddSpecialization(InstD, InsertPos);
3986 // Substitute the nested name specifier, if any.
3987 if (SubstQualifier(D, InstD))
3988 return nullptr;
3990 InstD->setAccess(D->getAccess());
3991 InstD->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
3992 InstD->setSpecializationKind(D->getSpecializationKind());
3993 InstD->setExternKeywordLoc(D->getExternKeywordLoc());
3994 InstD->setTemplateKeywordLoc(D->getTemplateKeywordLoc());
3996 Owner->addDecl(InstD);
3998 // Instantiate the members of the class-scope explicit specialization eagerly.
3999 // We don't have support for lazy instantiation of an explicit specialization
4000 // yet, and MSVC eagerly instantiates in this case.
4001 // FIXME: This is wrong in standard C++.
4002 if (D->isThisDeclarationADefinition() &&
4003 SemaRef.InstantiateClass(D->getLocation(), InstD, D, TemplateArgs,
4004 TSK_ImplicitInstantiation,
4005 /*Complain=*/true))
4006 return nullptr;
4008 return InstD;
4011 Decl *TemplateDeclInstantiator::VisitVarTemplateSpecializationDecl(
4012 VarTemplateSpecializationDecl *D) {
4014 TemplateArgumentListInfo VarTemplateArgsInfo;
4015 VarTemplateDecl *VarTemplate = D->getSpecializedTemplate();
4016 assert(VarTemplate &&
4017 "A template specialization without specialized template?");
4019 VarTemplateDecl *InstVarTemplate =
4020 cast_or_null<VarTemplateDecl>(SemaRef.FindInstantiatedDecl(
4021 D->getLocation(), VarTemplate, TemplateArgs));
4022 if (!InstVarTemplate)
4023 return nullptr;
4025 // Substitute the current template arguments.
4026 if (const ASTTemplateArgumentListInfo *TemplateArgsInfo =
4027 D->getTemplateArgsAsWritten()) {
4028 VarTemplateArgsInfo.setLAngleLoc(TemplateArgsInfo->getLAngleLoc());
4029 VarTemplateArgsInfo.setRAngleLoc(TemplateArgsInfo->getRAngleLoc());
4031 if (SemaRef.SubstTemplateArguments(TemplateArgsInfo->arguments(),
4032 TemplateArgs, VarTemplateArgsInfo))
4033 return nullptr;
4036 // Check that the template argument list is well-formed for this template.
4037 SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
4038 if (SemaRef.CheckTemplateArgumentList(
4039 InstVarTemplate, D->getLocation(), VarTemplateArgsInfo,
4040 /*DefaultArgs=*/{}, false, SugaredConverted, CanonicalConverted,
4041 /*UpdateArgsWithConversions=*/true))
4042 return nullptr;
4044 // Check whether we've already seen a declaration of this specialization.
4045 void *InsertPos = nullptr;
4046 VarTemplateSpecializationDecl *PrevDecl =
4047 InstVarTemplate->findSpecialization(CanonicalConverted, InsertPos);
4049 // Check whether we've already seen a conflicting instantiation of this
4050 // declaration (for instance, if there was a prior implicit instantiation).
4051 bool Ignored;
4052 if (PrevDecl && SemaRef.CheckSpecializationInstantiationRedecl(
4053 D->getLocation(), D->getSpecializationKind(), PrevDecl,
4054 PrevDecl->getSpecializationKind(),
4055 PrevDecl->getPointOfInstantiation(), Ignored))
4056 return nullptr;
4058 return VisitVarTemplateSpecializationDecl(
4059 InstVarTemplate, D, VarTemplateArgsInfo, CanonicalConverted, PrevDecl);
4062 Decl *TemplateDeclInstantiator::VisitVarTemplateSpecializationDecl(
4063 VarTemplateDecl *VarTemplate, VarDecl *D,
4064 const TemplateArgumentListInfo &TemplateArgsInfo,
4065 ArrayRef<TemplateArgument> Converted,
4066 VarTemplateSpecializationDecl *PrevDecl) {
4068 // Do substitution on the type of the declaration
4069 TypeSourceInfo *DI =
4070 SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs,
4071 D->getTypeSpecStartLoc(), D->getDeclName());
4072 if (!DI)
4073 return nullptr;
4075 if (DI->getType()->isFunctionType()) {
4076 SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function)
4077 << D->isStaticDataMember() << DI->getType();
4078 return nullptr;
4081 // Build the instantiated declaration
4082 VarTemplateSpecializationDecl *Var = VarTemplateSpecializationDecl::Create(
4083 SemaRef.Context, Owner, D->getInnerLocStart(), D->getLocation(),
4084 VarTemplate, DI->getType(), DI, D->getStorageClass(), Converted);
4085 Var->setTemplateArgsAsWritten(TemplateArgsInfo);
4086 if (!PrevDecl) {
4087 void *InsertPos = nullptr;
4088 VarTemplate->findSpecialization(Converted, InsertPos);
4089 VarTemplate->AddSpecialization(Var, InsertPos);
4092 if (SemaRef.getLangOpts().OpenCL)
4093 SemaRef.deduceOpenCLAddressSpace(Var);
4095 // Substitute the nested name specifier, if any.
4096 if (SubstQualifier(D, Var))
4097 return nullptr;
4099 SemaRef.BuildVariableInstantiation(Var, D, TemplateArgs, LateAttrs, Owner,
4100 StartingScope, false, PrevDecl);
4102 return Var;
4105 Decl *TemplateDeclInstantiator::VisitObjCAtDefsFieldDecl(ObjCAtDefsFieldDecl *D) {
4106 llvm_unreachable("@defs is not supported in Objective-C++");
4109 Decl *TemplateDeclInstantiator::VisitFriendTemplateDecl(FriendTemplateDecl *D) {
4110 // FIXME: We need to be able to instantiate FriendTemplateDecls.
4111 unsigned DiagID = SemaRef.getDiagnostics().getCustomDiagID(
4112 DiagnosticsEngine::Error,
4113 "cannot instantiate %0 yet");
4114 SemaRef.Diag(D->getLocation(), DiagID)
4115 << D->getDeclKindName();
4117 return nullptr;
4120 Decl *TemplateDeclInstantiator::VisitConceptDecl(ConceptDecl *D) {
4121 llvm_unreachable("Concept definitions cannot reside inside a template");
4124 Decl *TemplateDeclInstantiator::VisitImplicitConceptSpecializationDecl(
4125 ImplicitConceptSpecializationDecl *D) {
4126 llvm_unreachable("Concept specializations cannot reside inside a template");
4129 Decl *
4130 TemplateDeclInstantiator::VisitRequiresExprBodyDecl(RequiresExprBodyDecl *D) {
4131 return RequiresExprBodyDecl::Create(SemaRef.Context, D->getDeclContext(),
4132 D->getBeginLoc());
4135 Decl *TemplateDeclInstantiator::VisitDecl(Decl *D) {
4136 llvm_unreachable("Unexpected decl");
4139 Decl *Sema::SubstDecl(Decl *D, DeclContext *Owner,
4140 const MultiLevelTemplateArgumentList &TemplateArgs) {
4141 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
4142 if (D->isInvalidDecl())
4143 return nullptr;
4145 Decl *SubstD;
4146 runWithSufficientStackSpace(D->getLocation(), [&] {
4147 SubstD = Instantiator.Visit(D);
4149 return SubstD;
4152 void TemplateDeclInstantiator::adjustForRewrite(RewriteKind RK,
4153 FunctionDecl *Orig, QualType &T,
4154 TypeSourceInfo *&TInfo,
4155 DeclarationNameInfo &NameInfo) {
4156 assert(RK == RewriteKind::RewriteSpaceshipAsEqualEqual);
4158 // C++2a [class.compare.default]p3:
4159 // the return type is replaced with bool
4160 auto *FPT = T->castAs<FunctionProtoType>();
4161 T = SemaRef.Context.getFunctionType(
4162 SemaRef.Context.BoolTy, FPT->getParamTypes(), FPT->getExtProtoInfo());
4164 // Update the return type in the source info too. The most straightforward
4165 // way is to create new TypeSourceInfo for the new type. Use the location of
4166 // the '= default' as the location of the new type.
4168 // FIXME: Set the correct return type when we initially transform the type,
4169 // rather than delaying it to now.
4170 TypeSourceInfo *NewTInfo =
4171 SemaRef.Context.getTrivialTypeSourceInfo(T, Orig->getEndLoc());
4172 auto OldLoc = TInfo->getTypeLoc().getAsAdjusted<FunctionProtoTypeLoc>();
4173 assert(OldLoc && "type of function is not a function type?");
4174 auto NewLoc = NewTInfo->getTypeLoc().castAs<FunctionProtoTypeLoc>();
4175 for (unsigned I = 0, N = OldLoc.getNumParams(); I != N; ++I)
4176 NewLoc.setParam(I, OldLoc.getParam(I));
4177 TInfo = NewTInfo;
4179 // and the declarator-id is replaced with operator==
4180 NameInfo.setName(
4181 SemaRef.Context.DeclarationNames.getCXXOperatorName(OO_EqualEqual));
4184 FunctionDecl *Sema::SubstSpaceshipAsEqualEqual(CXXRecordDecl *RD,
4185 FunctionDecl *Spaceship) {
4186 if (Spaceship->isInvalidDecl())
4187 return nullptr;
4189 // C++2a [class.compare.default]p3:
4190 // an == operator function is declared implicitly [...] with the same
4191 // access and function-definition and in the same class scope as the
4192 // three-way comparison operator function
4193 MultiLevelTemplateArgumentList NoTemplateArgs;
4194 NoTemplateArgs.setKind(TemplateSubstitutionKind::Rewrite);
4195 NoTemplateArgs.addOuterRetainedLevels(RD->getTemplateDepth());
4196 TemplateDeclInstantiator Instantiator(*this, RD, NoTemplateArgs);
4197 Decl *R;
4198 if (auto *MD = dyn_cast<CXXMethodDecl>(Spaceship)) {
4199 R = Instantiator.VisitCXXMethodDecl(
4200 MD, /*TemplateParams=*/nullptr,
4201 TemplateDeclInstantiator::RewriteKind::RewriteSpaceshipAsEqualEqual);
4202 } else {
4203 assert(Spaceship->getFriendObjectKind() &&
4204 "defaulted spaceship is neither a member nor a friend");
4206 R = Instantiator.VisitFunctionDecl(
4207 Spaceship, /*TemplateParams=*/nullptr,
4208 TemplateDeclInstantiator::RewriteKind::RewriteSpaceshipAsEqualEqual);
4209 if (!R)
4210 return nullptr;
4212 FriendDecl *FD =
4213 FriendDecl::Create(Context, RD, Spaceship->getLocation(),
4214 cast<NamedDecl>(R), Spaceship->getBeginLoc());
4215 FD->setAccess(AS_public);
4216 RD->addDecl(FD);
4218 return cast_or_null<FunctionDecl>(R);
4221 /// Instantiates a nested template parameter list in the current
4222 /// instantiation context.
4224 /// \param L The parameter list to instantiate
4226 /// \returns NULL if there was an error
4227 TemplateParameterList *
4228 TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList *L) {
4229 // Get errors for all the parameters before bailing out.
4230 bool Invalid = false;
4232 unsigned N = L->size();
4233 typedef SmallVector<NamedDecl *, 8> ParamVector;
4234 ParamVector Params;
4235 Params.reserve(N);
4236 for (auto &P : *L) {
4237 NamedDecl *D = cast_or_null<NamedDecl>(Visit(P));
4238 Params.push_back(D);
4239 Invalid = Invalid || !D || D->isInvalidDecl();
4242 // Clean up if we had an error.
4243 if (Invalid)
4244 return nullptr;
4246 Expr *InstRequiresClause = L->getRequiresClause();
4248 TemplateParameterList *InstL
4249 = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(),
4250 L->getLAngleLoc(), Params,
4251 L->getRAngleLoc(), InstRequiresClause);
4252 return InstL;
4255 TemplateParameterList *
4256 Sema::SubstTemplateParams(TemplateParameterList *Params, DeclContext *Owner,
4257 const MultiLevelTemplateArgumentList &TemplateArgs,
4258 bool EvaluateConstraints) {
4259 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
4260 Instantiator.setEvaluateConstraints(EvaluateConstraints);
4261 return Instantiator.SubstTemplateParams(Params);
4264 /// Instantiate the declaration of a class template partial
4265 /// specialization.
4267 /// \param ClassTemplate the (instantiated) class template that is partially
4268 // specialized by the instantiation of \p PartialSpec.
4270 /// \param PartialSpec the (uninstantiated) class template partial
4271 /// specialization that we are instantiating.
4273 /// \returns The instantiated partial specialization, if successful; otherwise,
4274 /// NULL to indicate an error.
4275 ClassTemplatePartialSpecializationDecl *
4276 TemplateDeclInstantiator::InstantiateClassTemplatePartialSpecialization(
4277 ClassTemplateDecl *ClassTemplate,
4278 ClassTemplatePartialSpecializationDecl *PartialSpec) {
4279 // Create a local instantiation scope for this class template partial
4280 // specialization, which will contain the instantiations of the template
4281 // parameters.
4282 LocalInstantiationScope Scope(SemaRef);
4284 // Substitute into the template parameters of the class template partial
4285 // specialization.
4286 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
4287 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
4288 if (!InstParams)
4289 return nullptr;
4291 // Substitute into the template arguments of the class template partial
4292 // specialization.
4293 const ASTTemplateArgumentListInfo *TemplArgInfo
4294 = PartialSpec->getTemplateArgsAsWritten();
4295 TemplateArgumentListInfo InstTemplateArgs(TemplArgInfo->LAngleLoc,
4296 TemplArgInfo->RAngleLoc);
4297 if (SemaRef.SubstTemplateArguments(TemplArgInfo->arguments(), TemplateArgs,
4298 InstTemplateArgs))
4299 return nullptr;
4301 // Check that the template argument list is well-formed for this
4302 // class template.
4303 SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
4304 if (SemaRef.CheckTemplateArgumentList(
4305 ClassTemplate, PartialSpec->getLocation(), InstTemplateArgs,
4306 /*DefaultArgs=*/{},
4307 /*PartialTemplateArgs=*/false, SugaredConverted, CanonicalConverted))
4308 return nullptr;
4310 // Check these arguments are valid for a template partial specialization.
4311 if (SemaRef.CheckTemplatePartialSpecializationArgs(
4312 PartialSpec->getLocation(), ClassTemplate, InstTemplateArgs.size(),
4313 CanonicalConverted))
4314 return nullptr;
4316 // Figure out where to insert this class template partial specialization
4317 // in the member template's set of class template partial specializations.
4318 void *InsertPos = nullptr;
4319 ClassTemplateSpecializationDecl *PrevDecl =
4320 ClassTemplate->findPartialSpecialization(CanonicalConverted, InstParams,
4321 InsertPos);
4323 // Build the canonical type that describes the converted template
4324 // arguments of the class template partial specialization.
4325 QualType CanonType = SemaRef.Context.getTemplateSpecializationType(
4326 TemplateName(ClassTemplate), CanonicalConverted);
4328 // Create the class template partial specialization declaration.
4329 ClassTemplatePartialSpecializationDecl *InstPartialSpec =
4330 ClassTemplatePartialSpecializationDecl::Create(
4331 SemaRef.Context, PartialSpec->getTagKind(), Owner,
4332 PartialSpec->getBeginLoc(), PartialSpec->getLocation(), InstParams,
4333 ClassTemplate, CanonicalConverted, CanonType,
4334 /*PrevDecl=*/nullptr);
4336 InstPartialSpec->setTemplateArgsAsWritten(InstTemplateArgs);
4338 // Substitute the nested name specifier, if any.
4339 if (SubstQualifier(PartialSpec, InstPartialSpec))
4340 return nullptr;
4342 InstPartialSpec->setInstantiatedFromMember(PartialSpec);
4344 if (PrevDecl) {
4345 // We've already seen a partial specialization with the same template
4346 // parameters and template arguments. This can happen, for example, when
4347 // substituting the outer template arguments ends up causing two
4348 // class template partial specializations of a member class template
4349 // to have identical forms, e.g.,
4351 // template<typename T, typename U>
4352 // struct Outer {
4353 // template<typename X, typename Y> struct Inner;
4354 // template<typename Y> struct Inner<T, Y>;
4355 // template<typename Y> struct Inner<U, Y>;
4356 // };
4358 // Outer<int, int> outer; // error: the partial specializations of Inner
4359 // // have the same signature.
4360 SemaRef.Diag(InstPartialSpec->getLocation(),
4361 diag::err_partial_spec_redeclared)
4362 << InstPartialSpec;
4363 SemaRef.Diag(PrevDecl->getLocation(), diag::note_prev_partial_spec_here)
4364 << SemaRef.Context.getTypeDeclType(PrevDecl);
4365 return nullptr;
4368 // Check the completed partial specialization.
4369 SemaRef.CheckTemplatePartialSpecialization(InstPartialSpec);
4371 // Add this partial specialization to the set of class template partial
4372 // specializations.
4373 ClassTemplate->AddPartialSpecialization(InstPartialSpec,
4374 /*InsertPos=*/nullptr);
4375 return InstPartialSpec;
4378 /// Instantiate the declaration of a variable template partial
4379 /// specialization.
4381 /// \param VarTemplate the (instantiated) variable template that is partially
4382 /// specialized by the instantiation of \p PartialSpec.
4384 /// \param PartialSpec the (uninstantiated) variable template partial
4385 /// specialization that we are instantiating.
4387 /// \returns The instantiated partial specialization, if successful; otherwise,
4388 /// NULL to indicate an error.
4389 VarTemplatePartialSpecializationDecl *
4390 TemplateDeclInstantiator::InstantiateVarTemplatePartialSpecialization(
4391 VarTemplateDecl *VarTemplate,
4392 VarTemplatePartialSpecializationDecl *PartialSpec) {
4393 // Create a local instantiation scope for this variable template partial
4394 // specialization, which will contain the instantiations of the template
4395 // parameters.
4396 LocalInstantiationScope Scope(SemaRef);
4398 // Substitute into the template parameters of the variable template partial
4399 // specialization.
4400 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
4401 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
4402 if (!InstParams)
4403 return nullptr;
4405 // Substitute into the template arguments of the variable template partial
4406 // specialization.
4407 const ASTTemplateArgumentListInfo *TemplArgInfo
4408 = PartialSpec->getTemplateArgsAsWritten();
4409 TemplateArgumentListInfo InstTemplateArgs(TemplArgInfo->LAngleLoc,
4410 TemplArgInfo->RAngleLoc);
4411 if (SemaRef.SubstTemplateArguments(TemplArgInfo->arguments(), TemplateArgs,
4412 InstTemplateArgs))
4413 return nullptr;
4415 // Check that the template argument list is well-formed for this
4416 // class template.
4417 SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
4418 if (SemaRef.CheckTemplateArgumentList(VarTemplate, PartialSpec->getLocation(),
4419 InstTemplateArgs, /*DefaultArgs=*/{},
4420 /*PartialTemplateArgs=*/false,
4421 SugaredConverted, CanonicalConverted))
4422 return nullptr;
4424 // Check these arguments are valid for a template partial specialization.
4425 if (SemaRef.CheckTemplatePartialSpecializationArgs(
4426 PartialSpec->getLocation(), VarTemplate, InstTemplateArgs.size(),
4427 CanonicalConverted))
4428 return nullptr;
4430 // Figure out where to insert this variable template partial specialization
4431 // in the member template's set of variable template partial specializations.
4432 void *InsertPos = nullptr;
4433 VarTemplateSpecializationDecl *PrevDecl =
4434 VarTemplate->findPartialSpecialization(CanonicalConverted, InstParams,
4435 InsertPos);
4437 // Do substitution on the type of the declaration
4438 TypeSourceInfo *DI = SemaRef.SubstType(
4439 PartialSpec->getTypeSourceInfo(), TemplateArgs,
4440 PartialSpec->getTypeSpecStartLoc(), PartialSpec->getDeclName());
4441 if (!DI)
4442 return nullptr;
4444 if (DI->getType()->isFunctionType()) {
4445 SemaRef.Diag(PartialSpec->getLocation(),
4446 diag::err_variable_instantiates_to_function)
4447 << PartialSpec->isStaticDataMember() << DI->getType();
4448 return nullptr;
4451 // Create the variable template partial specialization declaration.
4452 VarTemplatePartialSpecializationDecl *InstPartialSpec =
4453 VarTemplatePartialSpecializationDecl::Create(
4454 SemaRef.Context, Owner, PartialSpec->getInnerLocStart(),
4455 PartialSpec->getLocation(), InstParams, VarTemplate, DI->getType(),
4456 DI, PartialSpec->getStorageClass(), CanonicalConverted);
4458 InstPartialSpec->setTemplateArgsAsWritten(InstTemplateArgs);
4460 // Substitute the nested name specifier, if any.
4461 if (SubstQualifier(PartialSpec, InstPartialSpec))
4462 return nullptr;
4464 InstPartialSpec->setInstantiatedFromMember(PartialSpec);
4466 if (PrevDecl) {
4467 // We've already seen a partial specialization with the same template
4468 // parameters and template arguments. This can happen, for example, when
4469 // substituting the outer template arguments ends up causing two
4470 // variable template partial specializations of a member variable template
4471 // to have identical forms, e.g.,
4473 // template<typename T, typename U>
4474 // struct Outer {
4475 // template<typename X, typename Y> pair<X,Y> p;
4476 // template<typename Y> pair<T, Y> p;
4477 // template<typename Y> pair<U, Y> p;
4478 // };
4480 // Outer<int, int> outer; // error: the partial specializations of Inner
4481 // // have the same signature.
4482 SemaRef.Diag(PartialSpec->getLocation(),
4483 diag::err_var_partial_spec_redeclared)
4484 << InstPartialSpec;
4485 SemaRef.Diag(PrevDecl->getLocation(),
4486 diag::note_var_prev_partial_spec_here);
4487 return nullptr;
4489 // Check the completed partial specialization.
4490 SemaRef.CheckTemplatePartialSpecialization(InstPartialSpec);
4492 // Add this partial specialization to the set of variable template partial
4493 // specializations. The instantiation of the initializer is not necessary.
4494 VarTemplate->AddPartialSpecialization(InstPartialSpec, /*InsertPos=*/nullptr);
4496 SemaRef.BuildVariableInstantiation(InstPartialSpec, PartialSpec, TemplateArgs,
4497 LateAttrs, Owner, StartingScope);
4499 return InstPartialSpec;
4502 TypeSourceInfo*
4503 TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D,
4504 SmallVectorImpl<ParmVarDecl *> &Params) {
4505 TypeSourceInfo *OldTInfo = D->getTypeSourceInfo();
4506 assert(OldTInfo && "substituting function without type source info");
4507 assert(Params.empty() && "parameter vector is non-empty at start");
4509 CXXRecordDecl *ThisContext = nullptr;
4510 Qualifiers ThisTypeQuals;
4511 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
4512 ThisContext = cast<CXXRecordDecl>(Owner);
4513 ThisTypeQuals = Method->getFunctionObjectParameterType().getQualifiers();
4516 TypeSourceInfo *NewTInfo = SemaRef.SubstFunctionDeclType(
4517 OldTInfo, TemplateArgs, D->getTypeSpecStartLoc(), D->getDeclName(),
4518 ThisContext, ThisTypeQuals, EvaluateConstraints);
4519 if (!NewTInfo)
4520 return nullptr;
4522 TypeLoc OldTL = OldTInfo->getTypeLoc().IgnoreParens();
4523 if (FunctionProtoTypeLoc OldProtoLoc = OldTL.getAs<FunctionProtoTypeLoc>()) {
4524 if (NewTInfo != OldTInfo) {
4525 // Get parameters from the new type info.
4526 TypeLoc NewTL = NewTInfo->getTypeLoc().IgnoreParens();
4527 FunctionProtoTypeLoc NewProtoLoc = NewTL.castAs<FunctionProtoTypeLoc>();
4528 unsigned NewIdx = 0;
4529 for (unsigned OldIdx = 0, NumOldParams = OldProtoLoc.getNumParams();
4530 OldIdx != NumOldParams; ++OldIdx) {
4531 ParmVarDecl *OldParam = OldProtoLoc.getParam(OldIdx);
4532 if (!OldParam)
4533 return nullptr;
4535 LocalInstantiationScope *Scope = SemaRef.CurrentInstantiationScope;
4537 std::optional<unsigned> NumArgumentsInExpansion;
4538 if (OldParam->isParameterPack())
4539 NumArgumentsInExpansion =
4540 SemaRef.getNumArgumentsInExpansion(OldParam->getType(),
4541 TemplateArgs);
4542 if (!NumArgumentsInExpansion) {
4543 // Simple case: normal parameter, or a parameter pack that's
4544 // instantiated to a (still-dependent) parameter pack.
4545 ParmVarDecl *NewParam = NewProtoLoc.getParam(NewIdx++);
4546 Params.push_back(NewParam);
4547 Scope->InstantiatedLocal(OldParam, NewParam);
4548 } else {
4549 // Parameter pack expansion: make the instantiation an argument pack.
4550 Scope->MakeInstantiatedLocalArgPack(OldParam);
4551 for (unsigned I = 0; I != *NumArgumentsInExpansion; ++I) {
4552 ParmVarDecl *NewParam = NewProtoLoc.getParam(NewIdx++);
4553 Params.push_back(NewParam);
4554 Scope->InstantiatedLocalPackArg(OldParam, NewParam);
4558 } else {
4559 // The function type itself was not dependent and therefore no
4560 // substitution occurred. However, we still need to instantiate
4561 // the function parameters themselves.
4562 const FunctionProtoType *OldProto =
4563 cast<FunctionProtoType>(OldProtoLoc.getType());
4564 for (unsigned i = 0, i_end = OldProtoLoc.getNumParams(); i != i_end;
4565 ++i) {
4566 ParmVarDecl *OldParam = OldProtoLoc.getParam(i);
4567 if (!OldParam) {
4568 Params.push_back(SemaRef.BuildParmVarDeclForTypedef(
4569 D, D->getLocation(), OldProto->getParamType(i)));
4570 continue;
4573 ParmVarDecl *Parm =
4574 cast_or_null<ParmVarDecl>(VisitParmVarDecl(OldParam));
4575 if (!Parm)
4576 return nullptr;
4577 Params.push_back(Parm);
4580 } else {
4581 // If the type of this function, after ignoring parentheses, is not
4582 // *directly* a function type, then we're instantiating a function that
4583 // was declared via a typedef or with attributes, e.g.,
4585 // typedef int functype(int, int);
4586 // functype func;
4587 // int __cdecl meth(int, int);
4589 // In this case, we'll just go instantiate the ParmVarDecls that we
4590 // synthesized in the method declaration.
4591 SmallVector<QualType, 4> ParamTypes;
4592 Sema::ExtParameterInfoBuilder ExtParamInfos;
4593 if (SemaRef.SubstParmTypes(D->getLocation(), D->parameters(), nullptr,
4594 TemplateArgs, ParamTypes, &Params,
4595 ExtParamInfos))
4596 return nullptr;
4599 return NewTInfo;
4602 void Sema::addInstantiatedLocalVarsToScope(FunctionDecl *Function,
4603 const FunctionDecl *PatternDecl,
4604 LocalInstantiationScope &Scope) {
4605 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(getFunctionScopes().back());
4607 for (auto *decl : PatternDecl->decls()) {
4608 if (!isa<VarDecl>(decl) || isa<ParmVarDecl>(decl))
4609 continue;
4611 VarDecl *VD = cast<VarDecl>(decl);
4612 IdentifierInfo *II = VD->getIdentifier();
4614 auto it = llvm::find_if(Function->decls(), [&](Decl *inst) {
4615 VarDecl *InstVD = dyn_cast<VarDecl>(inst);
4616 return InstVD && InstVD->isLocalVarDecl() &&
4617 InstVD->getIdentifier() == II;
4620 if (it == Function->decls().end())
4621 continue;
4623 Scope.InstantiatedLocal(VD, *it);
4624 LSI->addCapture(cast<VarDecl>(*it), /*isBlock=*/false, /*isByref=*/false,
4625 /*isNested=*/false, VD->getLocation(), SourceLocation(),
4626 VD->getType(), /*Invalid=*/false);
4630 bool Sema::addInstantiatedParametersToScope(
4631 FunctionDecl *Function, const FunctionDecl *PatternDecl,
4632 LocalInstantiationScope &Scope,
4633 const MultiLevelTemplateArgumentList &TemplateArgs) {
4634 unsigned FParamIdx = 0;
4635 for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I) {
4636 const ParmVarDecl *PatternParam = PatternDecl->getParamDecl(I);
4637 if (!PatternParam->isParameterPack()) {
4638 // Simple case: not a parameter pack.
4639 assert(FParamIdx < Function->getNumParams());
4640 ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
4641 FunctionParam->setDeclName(PatternParam->getDeclName());
4642 // If the parameter's type is not dependent, update it to match the type
4643 // in the pattern. They can differ in top-level cv-qualifiers, and we want
4644 // the pattern's type here. If the type is dependent, they can't differ,
4645 // per core issue 1668. Substitute into the type from the pattern, in case
4646 // it's instantiation-dependent.
4647 // FIXME: Updating the type to work around this is at best fragile.
4648 if (!PatternDecl->getType()->isDependentType()) {
4649 QualType T = SubstType(PatternParam->getType(), TemplateArgs,
4650 FunctionParam->getLocation(),
4651 FunctionParam->getDeclName());
4652 if (T.isNull())
4653 return true;
4654 FunctionParam->setType(T);
4657 Scope.InstantiatedLocal(PatternParam, FunctionParam);
4658 ++FParamIdx;
4659 continue;
4662 // Expand the parameter pack.
4663 Scope.MakeInstantiatedLocalArgPack(PatternParam);
4664 std::optional<unsigned> NumArgumentsInExpansion =
4665 getNumArgumentsInExpansion(PatternParam->getType(), TemplateArgs);
4666 if (NumArgumentsInExpansion) {
4667 QualType PatternType =
4668 PatternParam->getType()->castAs<PackExpansionType>()->getPattern();
4669 for (unsigned Arg = 0; Arg < *NumArgumentsInExpansion; ++Arg) {
4670 ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
4671 FunctionParam->setDeclName(PatternParam->getDeclName());
4672 if (!PatternDecl->getType()->isDependentType()) {
4673 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, Arg);
4674 QualType T =
4675 SubstType(PatternType, TemplateArgs, FunctionParam->getLocation(),
4676 FunctionParam->getDeclName());
4677 if (T.isNull())
4678 return true;
4679 FunctionParam->setType(T);
4682 Scope.InstantiatedLocalPackArg(PatternParam, FunctionParam);
4683 ++FParamIdx;
4688 return false;
4691 bool Sema::InstantiateDefaultArgument(SourceLocation CallLoc, FunctionDecl *FD,
4692 ParmVarDecl *Param) {
4693 assert(Param->hasUninstantiatedDefaultArg());
4695 // Instantiate the expression.
4697 // FIXME: Pass in a correct Pattern argument, otherwise
4698 // getTemplateInstantiationArgs uses the lexical context of FD, e.g.
4700 // template<typename T>
4701 // struct A {
4702 // static int FooImpl();
4704 // template<typename Tp>
4705 // // bug: default argument A<T>::FooImpl() is evaluated with 2-level
4706 // // template argument list [[T], [Tp]], should be [[Tp]].
4707 // friend A<Tp> Foo(int a);
4708 // };
4710 // template<typename T>
4711 // A<T> Foo(int a = A<T>::FooImpl());
4712 MultiLevelTemplateArgumentList TemplateArgs = getTemplateInstantiationArgs(
4713 FD, FD->getLexicalDeclContext(),
4714 /*Final=*/false, /*Innermost=*/std::nullopt,
4715 /*RelativeToPrimary=*/true, /*Pattern=*/nullptr,
4716 /*ForConstraintInstantiation=*/false, /*SkipForSpecialization=*/false,
4717 /*ForDefaultArgumentSubstitution=*/true);
4719 if (SubstDefaultArgument(CallLoc, Param, TemplateArgs, /*ForCallExpr*/ true))
4720 return true;
4722 if (ASTMutationListener *L = getASTMutationListener())
4723 L->DefaultArgumentInstantiated(Param);
4725 return false;
4728 void Sema::InstantiateExceptionSpec(SourceLocation PointOfInstantiation,
4729 FunctionDecl *Decl) {
4730 const FunctionProtoType *Proto = Decl->getType()->castAs<FunctionProtoType>();
4731 if (Proto->getExceptionSpecType() != EST_Uninstantiated)
4732 return;
4734 InstantiatingTemplate Inst(*this, PointOfInstantiation, Decl,
4735 InstantiatingTemplate::ExceptionSpecification());
4736 if (Inst.isInvalid()) {
4737 // We hit the instantiation depth limit. Clear the exception specification
4738 // so that our callers don't have to cope with EST_Uninstantiated.
4739 UpdateExceptionSpec(Decl, EST_None);
4740 return;
4742 if (Inst.isAlreadyInstantiating()) {
4743 // This exception specification indirectly depends on itself. Reject.
4744 // FIXME: Corresponding rule in the standard?
4745 Diag(PointOfInstantiation, diag::err_exception_spec_cycle) << Decl;
4746 UpdateExceptionSpec(Decl, EST_None);
4747 return;
4750 // Enter the scope of this instantiation. We don't use
4751 // PushDeclContext because we don't have a scope.
4752 Sema::ContextRAII savedContext(*this, Decl);
4753 LocalInstantiationScope Scope(*this);
4755 MultiLevelTemplateArgumentList TemplateArgs =
4756 getTemplateInstantiationArgs(Decl, Decl->getLexicalDeclContext(),
4757 /*Final=*/false, /*Innermost=*/std::nullopt,
4758 /*RelativeToPrimary*/ true);
4760 // FIXME: We can't use getTemplateInstantiationPattern(false) in general
4761 // here, because for a non-defining friend declaration in a class template,
4762 // we don't store enough information to map back to the friend declaration in
4763 // the template.
4764 FunctionDecl *Template = Proto->getExceptionSpecTemplate();
4765 if (addInstantiatedParametersToScope(Decl, Template, Scope, TemplateArgs)) {
4766 UpdateExceptionSpec(Decl, EST_None);
4767 return;
4770 // The noexcept specification could reference any lambda captures. Ensure
4771 // those are added to the LocalInstantiationScope.
4772 LambdaScopeForCallOperatorInstantiationRAII PushLambdaCaptures(
4773 *this, Decl, TemplateArgs, Scope,
4774 /*ShouldAddDeclsFromParentScope=*/false);
4776 SubstExceptionSpec(Decl, Template->getType()->castAs<FunctionProtoType>(),
4777 TemplateArgs);
4780 /// Initializes the common fields of an instantiation function
4781 /// declaration (New) from the corresponding fields of its template (Tmpl).
4783 /// \returns true if there was an error
4784 bool
4785 TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New,
4786 FunctionDecl *Tmpl) {
4787 New->setImplicit(Tmpl->isImplicit());
4789 // Forward the mangling number from the template to the instantiated decl.
4790 SemaRef.Context.setManglingNumber(New,
4791 SemaRef.Context.getManglingNumber(Tmpl));
4793 // If we are performing substituting explicitly-specified template arguments
4794 // or deduced template arguments into a function template and we reach this
4795 // point, we are now past the point where SFINAE applies and have committed
4796 // to keeping the new function template specialization. We therefore
4797 // convert the active template instantiation for the function template
4798 // into a template instantiation for this specific function template
4799 // specialization, which is not a SFINAE context, so that we diagnose any
4800 // further errors in the declaration itself.
4802 // FIXME: This is a hack.
4803 typedef Sema::CodeSynthesisContext ActiveInstType;
4804 ActiveInstType &ActiveInst = SemaRef.CodeSynthesisContexts.back();
4805 if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution ||
4806 ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) {
4807 if (isa<FunctionTemplateDecl>(ActiveInst.Entity)) {
4808 SemaRef.InstantiatingSpecializations.erase(
4809 {ActiveInst.Entity->getCanonicalDecl(), ActiveInst.Kind});
4810 atTemplateEnd(SemaRef.TemplateInstCallbacks, SemaRef, ActiveInst);
4811 ActiveInst.Kind = ActiveInstType::TemplateInstantiation;
4812 ActiveInst.Entity = New;
4813 atTemplateBegin(SemaRef.TemplateInstCallbacks, SemaRef, ActiveInst);
4817 const FunctionProtoType *Proto = Tmpl->getType()->getAs<FunctionProtoType>();
4818 assert(Proto && "Function template without prototype?");
4820 if (Proto->hasExceptionSpec() || Proto->getNoReturnAttr()) {
4821 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
4823 // DR1330: In C++11, defer instantiation of a non-trivial
4824 // exception specification.
4825 // DR1484: Local classes and their members are instantiated along with the
4826 // containing function.
4827 if (SemaRef.getLangOpts().CPlusPlus11 &&
4828 EPI.ExceptionSpec.Type != EST_None &&
4829 EPI.ExceptionSpec.Type != EST_DynamicNone &&
4830 EPI.ExceptionSpec.Type != EST_BasicNoexcept &&
4831 !Tmpl->isInLocalScopeForInstantiation()) {
4832 FunctionDecl *ExceptionSpecTemplate = Tmpl;
4833 if (EPI.ExceptionSpec.Type == EST_Uninstantiated)
4834 ExceptionSpecTemplate = EPI.ExceptionSpec.SourceTemplate;
4835 ExceptionSpecificationType NewEST = EST_Uninstantiated;
4836 if (EPI.ExceptionSpec.Type == EST_Unevaluated)
4837 NewEST = EST_Unevaluated;
4839 // Mark the function has having an uninstantiated exception specification.
4840 const FunctionProtoType *NewProto
4841 = New->getType()->getAs<FunctionProtoType>();
4842 assert(NewProto && "Template instantiation without function prototype?");
4843 EPI = NewProto->getExtProtoInfo();
4844 EPI.ExceptionSpec.Type = NewEST;
4845 EPI.ExceptionSpec.SourceDecl = New;
4846 EPI.ExceptionSpec.SourceTemplate = ExceptionSpecTemplate;
4847 New->setType(SemaRef.Context.getFunctionType(
4848 NewProto->getReturnType(), NewProto->getParamTypes(), EPI));
4849 } else {
4850 Sema::ContextRAII SwitchContext(SemaRef, New);
4851 SemaRef.SubstExceptionSpec(New, Proto, TemplateArgs);
4855 // Get the definition. Leaves the variable unchanged if undefined.
4856 const FunctionDecl *Definition = Tmpl;
4857 Tmpl->isDefined(Definition);
4859 SemaRef.InstantiateAttrs(TemplateArgs, Definition, New,
4860 LateAttrs, StartingScope);
4862 return false;
4865 /// Initializes common fields of an instantiated method
4866 /// declaration (New) from the corresponding fields of its template
4867 /// (Tmpl).
4869 /// \returns true if there was an error
4870 bool
4871 TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New,
4872 CXXMethodDecl *Tmpl) {
4873 if (InitFunctionInstantiation(New, Tmpl))
4874 return true;
4876 if (isa<CXXDestructorDecl>(New) && SemaRef.getLangOpts().CPlusPlus11)
4877 SemaRef.AdjustDestructorExceptionSpec(cast<CXXDestructorDecl>(New));
4879 New->setAccess(Tmpl->getAccess());
4880 if (Tmpl->isVirtualAsWritten())
4881 New->setVirtualAsWritten(true);
4883 // FIXME: New needs a pointer to Tmpl
4884 return false;
4887 bool TemplateDeclInstantiator::SubstDefaultedFunction(FunctionDecl *New,
4888 FunctionDecl *Tmpl) {
4889 // Transfer across any unqualified lookups.
4890 if (auto *DFI = Tmpl->getDefalutedOrDeletedInfo()) {
4891 SmallVector<DeclAccessPair, 32> Lookups;
4892 Lookups.reserve(DFI->getUnqualifiedLookups().size());
4893 bool AnyChanged = false;
4894 for (DeclAccessPair DA : DFI->getUnqualifiedLookups()) {
4895 NamedDecl *D = SemaRef.FindInstantiatedDecl(New->getLocation(),
4896 DA.getDecl(), TemplateArgs);
4897 if (!D)
4898 return true;
4899 AnyChanged |= (D != DA.getDecl());
4900 Lookups.push_back(DeclAccessPair::make(D, DA.getAccess()));
4903 // It's unlikely that substitution will change any declarations. Don't
4904 // store an unnecessary copy in that case.
4905 New->setDefaultedOrDeletedInfo(
4906 AnyChanged ? FunctionDecl::DefaultedOrDeletedFunctionInfo::Create(
4907 SemaRef.Context, Lookups)
4908 : DFI);
4911 SemaRef.SetDeclDefaulted(New, Tmpl->getLocation());
4912 return false;
4915 FunctionDecl *Sema::InstantiateFunctionDeclaration(
4916 FunctionTemplateDecl *FTD, const TemplateArgumentList *Args,
4917 SourceLocation Loc, CodeSynthesisContext::SynthesisKind CSC) {
4918 FunctionDecl *FD = FTD->getTemplatedDecl();
4920 sema::TemplateDeductionInfo Info(Loc);
4921 InstantiatingTemplate Inst(*this, Loc, FTD, Args->asArray(), CSC, Info);
4922 if (Inst.isInvalid())
4923 return nullptr;
4925 ContextRAII SavedContext(*this, FD);
4926 MultiLevelTemplateArgumentList MArgs(FTD, Args->asArray(),
4927 /*Final=*/false);
4929 return cast_or_null<FunctionDecl>(SubstDecl(FD, FD->getParent(), MArgs));
4932 void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
4933 FunctionDecl *Function,
4934 bool Recursive,
4935 bool DefinitionRequired,
4936 bool AtEndOfTU) {
4937 if (Function->isInvalidDecl() || isa<CXXDeductionGuideDecl>(Function))
4938 return;
4940 // Never instantiate an explicit specialization except if it is a class scope
4941 // explicit specialization.
4942 TemplateSpecializationKind TSK =
4943 Function->getTemplateSpecializationKindForInstantiation();
4944 if (TSK == TSK_ExplicitSpecialization)
4945 return;
4947 // Never implicitly instantiate a builtin; we don't actually need a function
4948 // body.
4949 if (Function->getBuiltinID() && TSK == TSK_ImplicitInstantiation &&
4950 !DefinitionRequired)
4951 return;
4953 // Don't instantiate a definition if we already have one.
4954 const FunctionDecl *ExistingDefn = nullptr;
4955 if (Function->isDefined(ExistingDefn,
4956 /*CheckForPendingFriendDefinition=*/true)) {
4957 if (ExistingDefn->isThisDeclarationADefinition())
4958 return;
4960 // If we're asked to instantiate a function whose body comes from an
4961 // instantiated friend declaration, attach the instantiated body to the
4962 // corresponding declaration of the function.
4963 assert(ExistingDefn->isThisDeclarationInstantiatedFromAFriendDefinition());
4964 Function = const_cast<FunctionDecl*>(ExistingDefn);
4967 // Find the function body that we'll be substituting.
4968 const FunctionDecl *PatternDecl = Function->getTemplateInstantiationPattern();
4969 assert(PatternDecl && "instantiating a non-template");
4971 const FunctionDecl *PatternDef = PatternDecl->getDefinition();
4972 Stmt *Pattern = nullptr;
4973 if (PatternDef) {
4974 Pattern = PatternDef->getBody(PatternDef);
4975 PatternDecl = PatternDef;
4976 if (PatternDef->willHaveBody())
4977 PatternDef = nullptr;
4980 // FIXME: We need to track the instantiation stack in order to know which
4981 // definitions should be visible within this instantiation.
4982 if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Function,
4983 Function->getInstantiatedFromMemberFunction(),
4984 PatternDecl, PatternDef, TSK,
4985 /*Complain*/DefinitionRequired)) {
4986 if (DefinitionRequired)
4987 Function->setInvalidDecl();
4988 else if (TSK == TSK_ExplicitInstantiationDefinition ||
4989 (Function->isConstexpr() && !Recursive)) {
4990 // Try again at the end of the translation unit (at which point a
4991 // definition will be required).
4992 assert(!Recursive);
4993 Function->setInstantiationIsPending(true);
4994 PendingInstantiations.push_back(
4995 std::make_pair(Function, PointOfInstantiation));
4997 if (llvm::isTimeTraceVerbose()) {
4998 llvm::timeTraceAddInstantEvent("DeferInstantiation", [&] {
4999 std::string Name;
5000 llvm::raw_string_ostream OS(Name);
5001 Function->getNameForDiagnostic(OS, getPrintingPolicy(),
5002 /*Qualified=*/true);
5003 return Name;
5006 } else if (TSK == TSK_ImplicitInstantiation) {
5007 if (AtEndOfTU && !getDiagnostics().hasErrorOccurred() &&
5008 !getSourceManager().isInSystemHeader(PatternDecl->getBeginLoc())) {
5009 Diag(PointOfInstantiation, diag::warn_func_template_missing)
5010 << Function;
5011 Diag(PatternDecl->getLocation(), diag::note_forward_template_decl);
5012 if (getLangOpts().CPlusPlus11)
5013 Diag(PointOfInstantiation, diag::note_inst_declaration_hint)
5014 << Function;
5018 return;
5021 // Postpone late parsed template instantiations.
5022 if (PatternDecl->isLateTemplateParsed() &&
5023 !LateTemplateParser) {
5024 Function->setInstantiationIsPending(true);
5025 LateParsedInstantiations.push_back(
5026 std::make_pair(Function, PointOfInstantiation));
5027 return;
5030 llvm::TimeTraceScope TimeScope("InstantiateFunction", [&]() {
5031 llvm::TimeTraceMetadata M;
5032 llvm::raw_string_ostream OS(M.Detail);
5033 Function->getNameForDiagnostic(OS, getPrintingPolicy(),
5034 /*Qualified=*/true);
5035 if (llvm::isTimeTraceVerbose()) {
5036 auto Loc = SourceMgr.getExpansionLoc(Function->getLocation());
5037 M.File = SourceMgr.getFilename(Loc);
5038 M.Line = SourceMgr.getExpansionLineNumber(Loc);
5040 return M;
5043 // If we're performing recursive template instantiation, create our own
5044 // queue of pending implicit instantiations that we will instantiate later,
5045 // while we're still within our own instantiation context.
5046 // This has to happen before LateTemplateParser below is called, so that
5047 // it marks vtables used in late parsed templates as used.
5048 GlobalEagerInstantiationScope GlobalInstantiations(*this,
5049 /*Enabled=*/Recursive);
5050 LocalEagerInstantiationScope LocalInstantiations(*this);
5052 // Call the LateTemplateParser callback if there is a need to late parse
5053 // a templated function definition.
5054 if (!Pattern && PatternDecl->isLateTemplateParsed() &&
5055 LateTemplateParser) {
5056 // FIXME: Optimize to allow individual templates to be deserialized.
5057 if (PatternDecl->isFromASTFile())
5058 ExternalSource->ReadLateParsedTemplates(LateParsedTemplateMap);
5060 auto LPTIter = LateParsedTemplateMap.find(PatternDecl);
5061 assert(LPTIter != LateParsedTemplateMap.end() &&
5062 "missing LateParsedTemplate");
5063 LateTemplateParser(OpaqueParser, *LPTIter->second);
5064 Pattern = PatternDecl->getBody(PatternDecl);
5065 updateAttrsForLateParsedTemplate(PatternDecl, Function);
5068 // Note, we should never try to instantiate a deleted function template.
5069 assert((Pattern || PatternDecl->isDefaulted() ||
5070 PatternDecl->hasSkippedBody()) &&
5071 "unexpected kind of function template definition");
5073 // C++1y [temp.explicit]p10:
5074 // Except for inline functions, declarations with types deduced from their
5075 // initializer or return value, and class template specializations, other
5076 // explicit instantiation declarations have the effect of suppressing the
5077 // implicit instantiation of the entity to which they refer.
5078 if (TSK == TSK_ExplicitInstantiationDeclaration &&
5079 !PatternDecl->isInlined() &&
5080 !PatternDecl->getReturnType()->getContainedAutoType())
5081 return;
5083 if (PatternDecl->isInlined()) {
5084 // Function, and all later redeclarations of it (from imported modules,
5085 // for instance), are now implicitly inline.
5086 for (auto *D = Function->getMostRecentDecl(); /**/;
5087 D = D->getPreviousDecl()) {
5088 D->setImplicitlyInline();
5089 if (D == Function)
5090 break;
5094 InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
5095 if (Inst.isInvalid() || Inst.isAlreadyInstantiating())
5096 return;
5097 PrettyDeclStackTraceEntry CrashInfo(Context, Function, SourceLocation(),
5098 "instantiating function definition");
5100 // The instantiation is visible here, even if it was first declared in an
5101 // unimported module.
5102 Function->setVisibleDespiteOwningModule();
5104 // Copy the source locations from the pattern.
5105 Function->setLocation(PatternDecl->getLocation());
5106 Function->setInnerLocStart(PatternDecl->getInnerLocStart());
5107 Function->setRangeEnd(PatternDecl->getEndLoc());
5108 Function->setDeclarationNameLoc(PatternDecl->getNameInfo().getInfo());
5110 EnterExpressionEvaluationContext EvalContext(
5111 *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
5113 Qualifiers ThisTypeQuals;
5114 CXXRecordDecl *ThisContext = nullptr;
5115 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
5116 ThisContext = Method->getParent();
5117 ThisTypeQuals = Method->getMethodQualifiers();
5119 CXXThisScopeRAII ThisScope(*this, ThisContext, ThisTypeQuals);
5121 // Introduce a new scope where local variable instantiations will be
5122 // recorded, unless we're actually a member function within a local
5123 // class, in which case we need to merge our results with the parent
5124 // scope (of the enclosing function). The exception is instantiating
5125 // a function template specialization, since the template to be
5126 // instantiated already has references to locals properly substituted.
5127 bool MergeWithParentScope = false;
5128 if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Function->getDeclContext()))
5129 MergeWithParentScope =
5130 Rec->isLocalClass() && !Function->isFunctionTemplateSpecialization();
5132 LocalInstantiationScope Scope(*this, MergeWithParentScope);
5133 auto RebuildTypeSourceInfoForDefaultSpecialMembers = [&]() {
5134 // Special members might get their TypeSourceInfo set up w.r.t the
5135 // PatternDecl context, in which case parameters could still be pointing
5136 // back to the original class, make sure arguments are bound to the
5137 // instantiated record instead.
5138 assert(PatternDecl->isDefaulted() &&
5139 "Special member needs to be defaulted");
5140 auto PatternSM = getDefaultedFunctionKind(PatternDecl).asSpecialMember();
5141 if (!(PatternSM == CXXSpecialMemberKind::CopyConstructor ||
5142 PatternSM == CXXSpecialMemberKind::CopyAssignment ||
5143 PatternSM == CXXSpecialMemberKind::MoveConstructor ||
5144 PatternSM == CXXSpecialMemberKind::MoveAssignment))
5145 return;
5147 auto *NewRec = dyn_cast<CXXRecordDecl>(Function->getDeclContext());
5148 const auto *PatternRec =
5149 dyn_cast<CXXRecordDecl>(PatternDecl->getDeclContext());
5150 if (!NewRec || !PatternRec)
5151 return;
5152 if (!PatternRec->isLambda())
5153 return;
5155 struct SpecialMemberTypeInfoRebuilder
5156 : TreeTransform<SpecialMemberTypeInfoRebuilder> {
5157 using Base = TreeTransform<SpecialMemberTypeInfoRebuilder>;
5158 const CXXRecordDecl *OldDecl;
5159 CXXRecordDecl *NewDecl;
5161 SpecialMemberTypeInfoRebuilder(Sema &SemaRef, const CXXRecordDecl *O,
5162 CXXRecordDecl *N)
5163 : TreeTransform(SemaRef), OldDecl(O), NewDecl(N) {}
5165 bool TransformExceptionSpec(SourceLocation Loc,
5166 FunctionProtoType::ExceptionSpecInfo &ESI,
5167 SmallVectorImpl<QualType> &Exceptions,
5168 bool &Changed) {
5169 return false;
5172 QualType TransformRecordType(TypeLocBuilder &TLB, RecordTypeLoc TL) {
5173 const RecordType *T = TL.getTypePtr();
5174 RecordDecl *Record = cast_or_null<RecordDecl>(
5175 getDerived().TransformDecl(TL.getNameLoc(), T->getDecl()));
5176 if (Record != OldDecl)
5177 return Base::TransformRecordType(TLB, TL);
5179 QualType Result = getDerived().RebuildRecordType(NewDecl);
5180 if (Result.isNull())
5181 return QualType();
5183 RecordTypeLoc NewTL = TLB.push<RecordTypeLoc>(Result);
5184 NewTL.setNameLoc(TL.getNameLoc());
5185 return Result;
5187 } IR{*this, PatternRec, NewRec};
5189 TypeSourceInfo *NewSI = IR.TransformType(Function->getTypeSourceInfo());
5190 assert(NewSI && "Type Transform failed?");
5191 Function->setType(NewSI->getType());
5192 Function->setTypeSourceInfo(NewSI);
5194 ParmVarDecl *Parm = Function->getParamDecl(0);
5195 TypeSourceInfo *NewParmSI = IR.TransformType(Parm->getTypeSourceInfo());
5196 assert(NewParmSI && "Type transformation failed.");
5197 Parm->setType(NewParmSI->getType());
5198 Parm->setTypeSourceInfo(NewParmSI);
5201 if (PatternDecl->isDefaulted()) {
5202 RebuildTypeSourceInfoForDefaultSpecialMembers();
5203 SetDeclDefaulted(Function, PatternDecl->getLocation());
5204 } else {
5205 MultiLevelTemplateArgumentList TemplateArgs = getTemplateInstantiationArgs(
5206 Function, Function->getLexicalDeclContext(), /*Final=*/false,
5207 /*Innermost=*/std::nullopt, false, PatternDecl);
5209 // Substitute into the qualifier; we can get a substitution failure here
5210 // through evil use of alias templates.
5211 // FIXME: Is CurContext correct for this? Should we go to the (instantiation
5212 // of the) lexical context of the pattern?
5213 SubstQualifier(*this, PatternDecl, Function, TemplateArgs);
5215 ActOnStartOfFunctionDef(nullptr, Function);
5217 // Enter the scope of this instantiation. We don't use
5218 // PushDeclContext because we don't have a scope.
5219 Sema::ContextRAII savedContext(*this, Function);
5221 FPFeaturesStateRAII SavedFPFeatures(*this);
5222 CurFPFeatures = FPOptions(getLangOpts());
5223 FpPragmaStack.CurrentValue = FPOptionsOverride();
5225 if (addInstantiatedParametersToScope(Function, PatternDecl, Scope,
5226 TemplateArgs))
5227 return;
5229 StmtResult Body;
5230 if (PatternDecl->hasSkippedBody()) {
5231 ActOnSkippedFunctionBody(Function);
5232 Body = nullptr;
5233 } else {
5234 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Function)) {
5235 // If this is a constructor, instantiate the member initializers.
5236 InstantiateMemInitializers(Ctor, cast<CXXConstructorDecl>(PatternDecl),
5237 TemplateArgs);
5239 // If this is an MS ABI dllexport default constructor, instantiate any
5240 // default arguments.
5241 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
5242 Ctor->isDefaultConstructor()) {
5243 InstantiateDefaultCtorDefaultArgs(Ctor);
5247 // Instantiate the function body.
5248 Body = SubstStmt(Pattern, TemplateArgs);
5250 if (Body.isInvalid())
5251 Function->setInvalidDecl();
5253 // FIXME: finishing the function body while in an expression evaluation
5254 // context seems wrong. Investigate more.
5255 ActOnFinishFunctionBody(Function, Body.get(), /*IsInstantiation=*/true);
5257 PerformDependentDiagnostics(PatternDecl, TemplateArgs);
5259 if (auto *Listener = getASTMutationListener())
5260 Listener->FunctionDefinitionInstantiated(Function);
5262 savedContext.pop();
5265 DeclGroupRef DG(Function);
5266 Consumer.HandleTopLevelDecl(DG);
5268 // This class may have local implicit instantiations that need to be
5269 // instantiation within this scope.
5270 LocalInstantiations.perform();
5271 Scope.Exit();
5272 GlobalInstantiations.perform();
5275 VarTemplateSpecializationDecl *Sema::BuildVarTemplateInstantiation(
5276 VarTemplateDecl *VarTemplate, VarDecl *FromVar,
5277 const TemplateArgumentList *PartialSpecArgs,
5278 const TemplateArgumentListInfo &TemplateArgsInfo,
5279 SmallVectorImpl<TemplateArgument> &Converted,
5280 SourceLocation PointOfInstantiation, LateInstantiatedAttrVec *LateAttrs,
5281 LocalInstantiationScope *StartingScope) {
5282 if (FromVar->isInvalidDecl())
5283 return nullptr;
5285 InstantiatingTemplate Inst(*this, PointOfInstantiation, FromVar);
5286 if (Inst.isInvalid())
5287 return nullptr;
5289 // Instantiate the first declaration of the variable template: for a partial
5290 // specialization of a static data member template, the first declaration may
5291 // or may not be the declaration in the class; if it's in the class, we want
5292 // to instantiate a member in the class (a declaration), and if it's outside,
5293 // we want to instantiate a definition.
5295 // If we're instantiating an explicitly-specialized member template or member
5296 // partial specialization, don't do this. The member specialization completely
5297 // replaces the original declaration in this case.
5298 bool IsMemberSpec = false;
5299 MultiLevelTemplateArgumentList MultiLevelList;
5300 if (auto *PartialSpec =
5301 dyn_cast<VarTemplatePartialSpecializationDecl>(FromVar)) {
5302 assert(PartialSpecArgs);
5303 IsMemberSpec = PartialSpec->isMemberSpecialization();
5304 MultiLevelList.addOuterTemplateArguments(
5305 PartialSpec, PartialSpecArgs->asArray(), /*Final=*/false);
5306 } else {
5307 assert(VarTemplate == FromVar->getDescribedVarTemplate());
5308 IsMemberSpec = VarTemplate->isMemberSpecialization();
5309 MultiLevelList.addOuterTemplateArguments(VarTemplate, Converted,
5310 /*Final=*/false);
5312 if (!IsMemberSpec)
5313 FromVar = FromVar->getFirstDecl();
5315 TemplateDeclInstantiator Instantiator(*this, FromVar->getDeclContext(),
5316 MultiLevelList);
5318 // TODO: Set LateAttrs and StartingScope ...
5320 return cast_or_null<VarTemplateSpecializationDecl>(
5321 Instantiator.VisitVarTemplateSpecializationDecl(
5322 VarTemplate, FromVar, TemplateArgsInfo, Converted));
5325 VarTemplateSpecializationDecl *Sema::CompleteVarTemplateSpecializationDecl(
5326 VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl,
5327 const MultiLevelTemplateArgumentList &TemplateArgs) {
5328 assert(PatternDecl->isThisDeclarationADefinition() &&
5329 "don't have a definition to instantiate from");
5331 // Do substitution on the type of the declaration
5332 TypeSourceInfo *DI =
5333 SubstType(PatternDecl->getTypeSourceInfo(), TemplateArgs,
5334 PatternDecl->getTypeSpecStartLoc(), PatternDecl->getDeclName());
5335 if (!DI)
5336 return nullptr;
5338 // Update the type of this variable template specialization.
5339 VarSpec->setType(DI->getType());
5341 // Convert the declaration into a definition now.
5342 VarSpec->setCompleteDefinition();
5344 // Instantiate the initializer.
5345 InstantiateVariableInitializer(VarSpec, PatternDecl, TemplateArgs);
5347 if (getLangOpts().OpenCL)
5348 deduceOpenCLAddressSpace(VarSpec);
5350 return VarSpec;
5353 void Sema::BuildVariableInstantiation(
5354 VarDecl *NewVar, VarDecl *OldVar,
5355 const MultiLevelTemplateArgumentList &TemplateArgs,
5356 LateInstantiatedAttrVec *LateAttrs, DeclContext *Owner,
5357 LocalInstantiationScope *StartingScope,
5358 bool InstantiatingVarTemplate,
5359 VarTemplateSpecializationDecl *PrevDeclForVarTemplateSpecialization) {
5360 // Instantiating a partial specialization to produce a partial
5361 // specialization.
5362 bool InstantiatingVarTemplatePartialSpec =
5363 isa<VarTemplatePartialSpecializationDecl>(OldVar) &&
5364 isa<VarTemplatePartialSpecializationDecl>(NewVar);
5365 // Instantiating from a variable template (or partial specialization) to
5366 // produce a variable template specialization.
5367 bool InstantiatingSpecFromTemplate =
5368 isa<VarTemplateSpecializationDecl>(NewVar) &&
5369 (OldVar->getDescribedVarTemplate() ||
5370 isa<VarTemplatePartialSpecializationDecl>(OldVar));
5372 // If we are instantiating a local extern declaration, the
5373 // instantiation belongs lexically to the containing function.
5374 // If we are instantiating a static data member defined
5375 // out-of-line, the instantiation will have the same lexical
5376 // context (which will be a namespace scope) as the template.
5377 if (OldVar->isLocalExternDecl()) {
5378 NewVar->setLocalExternDecl();
5379 NewVar->setLexicalDeclContext(Owner);
5380 } else if (OldVar->isOutOfLine())
5381 NewVar->setLexicalDeclContext(OldVar->getLexicalDeclContext());
5382 NewVar->setTSCSpec(OldVar->getTSCSpec());
5383 NewVar->setInitStyle(OldVar->getInitStyle());
5384 NewVar->setCXXForRangeDecl(OldVar->isCXXForRangeDecl());
5385 NewVar->setObjCForDecl(OldVar->isObjCForDecl());
5386 NewVar->setConstexpr(OldVar->isConstexpr());
5387 NewVar->setInitCapture(OldVar->isInitCapture());
5388 NewVar->setPreviousDeclInSameBlockScope(
5389 OldVar->isPreviousDeclInSameBlockScope());
5390 NewVar->setAccess(OldVar->getAccess());
5392 if (!OldVar->isStaticDataMember()) {
5393 if (OldVar->isUsed(false))
5394 NewVar->setIsUsed();
5395 NewVar->setReferenced(OldVar->isReferenced());
5398 InstantiateAttrs(TemplateArgs, OldVar, NewVar, LateAttrs, StartingScope);
5400 LookupResult Previous(
5401 *this, NewVar->getDeclName(), NewVar->getLocation(),
5402 NewVar->isLocalExternDecl() ? Sema::LookupRedeclarationWithLinkage
5403 : Sema::LookupOrdinaryName,
5404 NewVar->isLocalExternDecl() ? RedeclarationKind::ForExternalRedeclaration
5405 : forRedeclarationInCurContext());
5407 if (NewVar->isLocalExternDecl() && OldVar->getPreviousDecl() &&
5408 (!OldVar->getPreviousDecl()->getDeclContext()->isDependentContext() ||
5409 OldVar->getPreviousDecl()->getDeclContext()==OldVar->getDeclContext())) {
5410 // We have a previous declaration. Use that one, so we merge with the
5411 // right type.
5412 if (NamedDecl *NewPrev = FindInstantiatedDecl(
5413 NewVar->getLocation(), OldVar->getPreviousDecl(), TemplateArgs))
5414 Previous.addDecl(NewPrev);
5415 } else if (!isa<VarTemplateSpecializationDecl>(NewVar) &&
5416 OldVar->hasLinkage()) {
5417 LookupQualifiedName(Previous, NewVar->getDeclContext(), false);
5418 } else if (PrevDeclForVarTemplateSpecialization) {
5419 Previous.addDecl(PrevDeclForVarTemplateSpecialization);
5421 CheckVariableDeclaration(NewVar, Previous);
5423 if (!InstantiatingVarTemplate) {
5424 NewVar->getLexicalDeclContext()->addHiddenDecl(NewVar);
5425 if (!NewVar->isLocalExternDecl() || !NewVar->getPreviousDecl())
5426 NewVar->getDeclContext()->makeDeclVisibleInContext(NewVar);
5429 if (!OldVar->isOutOfLine()) {
5430 if (NewVar->getDeclContext()->isFunctionOrMethod())
5431 CurrentInstantiationScope->InstantiatedLocal(OldVar, NewVar);
5434 // Link instantiations of static data members back to the template from
5435 // which they were instantiated.
5437 // Don't do this when instantiating a template (we link the template itself
5438 // back in that case) nor when instantiating a static data member template
5439 // (that's not a member specialization).
5440 if (NewVar->isStaticDataMember() && !InstantiatingVarTemplate &&
5441 !InstantiatingSpecFromTemplate)
5442 NewVar->setInstantiationOfStaticDataMember(OldVar,
5443 TSK_ImplicitInstantiation);
5445 // If the pattern is an (in-class) explicit specialization, then the result
5446 // is also an explicit specialization.
5447 if (VarTemplateSpecializationDecl *OldVTSD =
5448 dyn_cast<VarTemplateSpecializationDecl>(OldVar)) {
5449 if (OldVTSD->getSpecializationKind() == TSK_ExplicitSpecialization &&
5450 !isa<VarTemplatePartialSpecializationDecl>(OldVTSD))
5451 cast<VarTemplateSpecializationDecl>(NewVar)->setSpecializationKind(
5452 TSK_ExplicitSpecialization);
5455 // Forward the mangling number from the template to the instantiated decl.
5456 Context.setManglingNumber(NewVar, Context.getManglingNumber(OldVar));
5457 Context.setStaticLocalNumber(NewVar, Context.getStaticLocalNumber(OldVar));
5459 // Figure out whether to eagerly instantiate the initializer.
5460 if (InstantiatingVarTemplate || InstantiatingVarTemplatePartialSpec) {
5461 // We're producing a template. Don't instantiate the initializer yet.
5462 } else if (NewVar->getType()->isUndeducedType()) {
5463 // We need the type to complete the declaration of the variable.
5464 InstantiateVariableInitializer(NewVar, OldVar, TemplateArgs);
5465 } else if (InstantiatingSpecFromTemplate ||
5466 (OldVar->isInline() && OldVar->isThisDeclarationADefinition() &&
5467 !NewVar->isThisDeclarationADefinition())) {
5468 // Delay instantiation of the initializer for variable template
5469 // specializations or inline static data members until a definition of the
5470 // variable is needed.
5471 } else {
5472 InstantiateVariableInitializer(NewVar, OldVar, TemplateArgs);
5475 // Diagnose unused local variables with dependent types, where the diagnostic
5476 // will have been deferred.
5477 if (!NewVar->isInvalidDecl() &&
5478 NewVar->getDeclContext()->isFunctionOrMethod() &&
5479 OldVar->getType()->isDependentType())
5480 DiagnoseUnusedDecl(NewVar);
5483 void Sema::InstantiateVariableInitializer(
5484 VarDecl *Var, VarDecl *OldVar,
5485 const MultiLevelTemplateArgumentList &TemplateArgs) {
5486 if (ASTMutationListener *L = getASTContext().getASTMutationListener())
5487 L->VariableDefinitionInstantiated(Var);
5489 // We propagate the 'inline' flag with the initializer, because it
5490 // would otherwise imply that the variable is a definition for a
5491 // non-static data member.
5492 if (OldVar->isInlineSpecified())
5493 Var->setInlineSpecified();
5494 else if (OldVar->isInline())
5495 Var->setImplicitlyInline();
5497 if (OldVar->getInit()) {
5498 EnterExpressionEvaluationContext Evaluated(
5499 *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated, Var);
5501 currentEvaluationContext().InLifetimeExtendingContext =
5502 parentEvaluationContext().InLifetimeExtendingContext;
5503 currentEvaluationContext().RebuildDefaultArgOrDefaultInit =
5504 parentEvaluationContext().RebuildDefaultArgOrDefaultInit;
5505 // Instantiate the initializer.
5506 ExprResult Init;
5509 ContextRAII SwitchContext(*this, Var->getDeclContext());
5510 Init = SubstInitializer(OldVar->getInit(), TemplateArgs,
5511 OldVar->getInitStyle() == VarDecl::CallInit);
5514 if (!Init.isInvalid()) {
5515 Expr *InitExpr = Init.get();
5517 if (Var->hasAttr<DLLImportAttr>() &&
5518 (!InitExpr ||
5519 !InitExpr->isConstantInitializer(getASTContext(), false))) {
5520 // Do not dynamically initialize dllimport variables.
5521 } else if (InitExpr) {
5522 bool DirectInit = OldVar->isDirectInit();
5523 AddInitializerToDecl(Var, InitExpr, DirectInit);
5524 } else
5525 ActOnUninitializedDecl(Var);
5526 } else {
5527 // FIXME: Not too happy about invalidating the declaration
5528 // because of a bogus initializer.
5529 Var->setInvalidDecl();
5531 } else {
5532 // `inline` variables are a definition and declaration all in one; we won't
5533 // pick up an initializer from anywhere else.
5534 if (Var->isStaticDataMember() && !Var->isInline()) {
5535 if (!Var->isOutOfLine())
5536 return;
5538 // If the declaration inside the class had an initializer, don't add
5539 // another one to the out-of-line definition.
5540 if (OldVar->getFirstDecl()->hasInit())
5541 return;
5544 // We'll add an initializer to a for-range declaration later.
5545 if (Var->isCXXForRangeDecl() || Var->isObjCForDecl())
5546 return;
5548 ActOnUninitializedDecl(Var);
5551 if (getLangOpts().CUDA)
5552 CUDA().checkAllowedInitializer(Var);
5555 void Sema::InstantiateVariableDefinition(SourceLocation PointOfInstantiation,
5556 VarDecl *Var, bool Recursive,
5557 bool DefinitionRequired, bool AtEndOfTU) {
5558 if (Var->isInvalidDecl())
5559 return;
5561 // Never instantiate an explicitly-specialized entity.
5562 TemplateSpecializationKind TSK =
5563 Var->getTemplateSpecializationKindForInstantiation();
5564 if (TSK == TSK_ExplicitSpecialization)
5565 return;
5567 // Find the pattern and the arguments to substitute into it.
5568 VarDecl *PatternDecl = Var->getTemplateInstantiationPattern();
5569 assert(PatternDecl && "no pattern for templated variable");
5570 MultiLevelTemplateArgumentList TemplateArgs =
5571 getTemplateInstantiationArgs(Var);
5573 VarTemplateSpecializationDecl *VarSpec =
5574 dyn_cast<VarTemplateSpecializationDecl>(Var);
5575 if (VarSpec) {
5576 // If this is a static data member template, there might be an
5577 // uninstantiated initializer on the declaration. If so, instantiate
5578 // it now.
5580 // FIXME: This largely duplicates what we would do below. The difference
5581 // is that along this path we may instantiate an initializer from an
5582 // in-class declaration of the template and instantiate the definition
5583 // from a separate out-of-class definition.
5584 if (PatternDecl->isStaticDataMember() &&
5585 (PatternDecl = PatternDecl->getFirstDecl())->hasInit() &&
5586 !Var->hasInit()) {
5587 // FIXME: Factor out the duplicated instantiation context setup/tear down
5588 // code here.
5589 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
5590 if (Inst.isInvalid() || Inst.isAlreadyInstantiating())
5591 return;
5592 PrettyDeclStackTraceEntry CrashInfo(Context, Var, SourceLocation(),
5593 "instantiating variable initializer");
5595 // The instantiation is visible here, even if it was first declared in an
5596 // unimported module.
5597 Var->setVisibleDespiteOwningModule();
5599 // If we're performing recursive template instantiation, create our own
5600 // queue of pending implicit instantiations that we will instantiate
5601 // later, while we're still within our own instantiation context.
5602 GlobalEagerInstantiationScope GlobalInstantiations(*this,
5603 /*Enabled=*/Recursive);
5604 LocalInstantiationScope Local(*this);
5605 LocalEagerInstantiationScope LocalInstantiations(*this);
5607 // Enter the scope of this instantiation. We don't use
5608 // PushDeclContext because we don't have a scope.
5609 ContextRAII PreviousContext(*this, Var->getDeclContext());
5610 InstantiateVariableInitializer(Var, PatternDecl, TemplateArgs);
5611 PreviousContext.pop();
5613 // This variable may have local implicit instantiations that need to be
5614 // instantiated within this scope.
5615 LocalInstantiations.perform();
5616 Local.Exit();
5617 GlobalInstantiations.perform();
5619 } else {
5620 assert(Var->isStaticDataMember() && PatternDecl->isStaticDataMember() &&
5621 "not a static data member?");
5624 VarDecl *Def = PatternDecl->getDefinition(getASTContext());
5626 // If we don't have a definition of the variable template, we won't perform
5627 // any instantiation. Rather, we rely on the user to instantiate this
5628 // definition (or provide a specialization for it) in another translation
5629 // unit.
5630 if (!Def && !DefinitionRequired) {
5631 if (TSK == TSK_ExplicitInstantiationDefinition) {
5632 PendingInstantiations.push_back(
5633 std::make_pair(Var, PointOfInstantiation));
5634 } else if (TSK == TSK_ImplicitInstantiation) {
5635 // Warn about missing definition at the end of translation unit.
5636 if (AtEndOfTU && !getDiagnostics().hasErrorOccurred() &&
5637 !getSourceManager().isInSystemHeader(PatternDecl->getBeginLoc())) {
5638 Diag(PointOfInstantiation, diag::warn_var_template_missing)
5639 << Var;
5640 Diag(PatternDecl->getLocation(), diag::note_forward_template_decl);
5641 if (getLangOpts().CPlusPlus11)
5642 Diag(PointOfInstantiation, diag::note_inst_declaration_hint) << Var;
5644 return;
5648 // FIXME: We need to track the instantiation stack in order to know which
5649 // definitions should be visible within this instantiation.
5650 // FIXME: Produce diagnostics when Var->getInstantiatedFromStaticDataMember().
5651 if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Var,
5652 /*InstantiatedFromMember*/false,
5653 PatternDecl, Def, TSK,
5654 /*Complain*/DefinitionRequired))
5655 return;
5657 // C++11 [temp.explicit]p10:
5658 // Except for inline functions, const variables of literal types, variables
5659 // of reference types, [...] explicit instantiation declarations
5660 // have the effect of suppressing the implicit instantiation of the entity
5661 // to which they refer.
5663 // FIXME: That's not exactly the same as "might be usable in constant
5664 // expressions", which only allows constexpr variables and const integral
5665 // types, not arbitrary const literal types.
5666 if (TSK == TSK_ExplicitInstantiationDeclaration &&
5667 !Var->mightBeUsableInConstantExpressions(getASTContext()))
5668 return;
5670 // Make sure to pass the instantiated variable to the consumer at the end.
5671 struct PassToConsumerRAII {
5672 ASTConsumer &Consumer;
5673 VarDecl *Var;
5675 PassToConsumerRAII(ASTConsumer &Consumer, VarDecl *Var)
5676 : Consumer(Consumer), Var(Var) { }
5678 ~PassToConsumerRAII() {
5679 Consumer.HandleCXXStaticMemberVarInstantiation(Var);
5681 } PassToConsumerRAII(Consumer, Var);
5683 // If we already have a definition, we're done.
5684 if (VarDecl *Def = Var->getDefinition()) {
5685 // We may be explicitly instantiating something we've already implicitly
5686 // instantiated.
5687 Def->setTemplateSpecializationKind(Var->getTemplateSpecializationKind(),
5688 PointOfInstantiation);
5689 return;
5692 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
5693 if (Inst.isInvalid() || Inst.isAlreadyInstantiating())
5694 return;
5695 PrettyDeclStackTraceEntry CrashInfo(Context, Var, SourceLocation(),
5696 "instantiating variable definition");
5698 // If we're performing recursive template instantiation, create our own
5699 // queue of pending implicit instantiations that we will instantiate later,
5700 // while we're still within our own instantiation context.
5701 GlobalEagerInstantiationScope GlobalInstantiations(*this,
5702 /*Enabled=*/Recursive);
5704 // Enter the scope of this instantiation. We don't use
5705 // PushDeclContext because we don't have a scope.
5706 ContextRAII PreviousContext(*this, Var->getDeclContext());
5707 LocalInstantiationScope Local(*this);
5709 LocalEagerInstantiationScope LocalInstantiations(*this);
5711 VarDecl *OldVar = Var;
5712 if (Def->isStaticDataMember() && !Def->isOutOfLine()) {
5713 // We're instantiating an inline static data member whose definition was
5714 // provided inside the class.
5715 InstantiateVariableInitializer(Var, Def, TemplateArgs);
5716 } else if (!VarSpec) {
5717 Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(),
5718 TemplateArgs));
5719 } else if (Var->isStaticDataMember() &&
5720 Var->getLexicalDeclContext()->isRecord()) {
5721 // We need to instantiate the definition of a static data member template,
5722 // and all we have is the in-class declaration of it. Instantiate a separate
5723 // declaration of the definition.
5724 TemplateDeclInstantiator Instantiator(*this, Var->getDeclContext(),
5725 TemplateArgs);
5727 TemplateArgumentListInfo TemplateArgInfo;
5728 if (const ASTTemplateArgumentListInfo *ArgInfo =
5729 VarSpec->getTemplateArgsAsWritten()) {
5730 TemplateArgInfo.setLAngleLoc(ArgInfo->getLAngleLoc());
5731 TemplateArgInfo.setRAngleLoc(ArgInfo->getRAngleLoc());
5732 for (const TemplateArgumentLoc &Arg : ArgInfo->arguments())
5733 TemplateArgInfo.addArgument(Arg);
5736 Var = cast_or_null<VarDecl>(Instantiator.VisitVarTemplateSpecializationDecl(
5737 VarSpec->getSpecializedTemplate(), Def, TemplateArgInfo,
5738 VarSpec->getTemplateArgs().asArray(), VarSpec));
5739 if (Var) {
5740 llvm::PointerUnion<VarTemplateDecl *,
5741 VarTemplatePartialSpecializationDecl *> PatternPtr =
5742 VarSpec->getSpecializedTemplateOrPartial();
5743 if (VarTemplatePartialSpecializationDecl *Partial =
5744 PatternPtr.dyn_cast<VarTemplatePartialSpecializationDecl *>())
5745 cast<VarTemplateSpecializationDecl>(Var)->setInstantiationOf(
5746 Partial, &VarSpec->getTemplateInstantiationArgs());
5748 // Attach the initializer.
5749 InstantiateVariableInitializer(Var, Def, TemplateArgs);
5751 } else
5752 // Complete the existing variable's definition with an appropriately
5753 // substituted type and initializer.
5754 Var = CompleteVarTemplateSpecializationDecl(VarSpec, Def, TemplateArgs);
5756 PreviousContext.pop();
5758 if (Var) {
5759 PassToConsumerRAII.Var = Var;
5760 Var->setTemplateSpecializationKind(OldVar->getTemplateSpecializationKind(),
5761 OldVar->getPointOfInstantiation());
5764 // This variable may have local implicit instantiations that need to be
5765 // instantiated within this scope.
5766 LocalInstantiations.perform();
5767 Local.Exit();
5768 GlobalInstantiations.perform();
5771 void
5772 Sema::InstantiateMemInitializers(CXXConstructorDecl *New,
5773 const CXXConstructorDecl *Tmpl,
5774 const MultiLevelTemplateArgumentList &TemplateArgs) {
5776 SmallVector<CXXCtorInitializer*, 4> NewInits;
5777 bool AnyErrors = Tmpl->isInvalidDecl();
5779 // Instantiate all the initializers.
5780 for (const auto *Init : Tmpl->inits()) {
5781 // Only instantiate written initializers, let Sema re-construct implicit
5782 // ones.
5783 if (!Init->isWritten())
5784 continue;
5786 SourceLocation EllipsisLoc;
5788 if (Init->isPackExpansion()) {
5789 // This is a pack expansion. We should expand it now.
5790 TypeLoc BaseTL = Init->getTypeSourceInfo()->getTypeLoc();
5791 SmallVector<UnexpandedParameterPack, 4> Unexpanded;
5792 collectUnexpandedParameterPacks(BaseTL, Unexpanded);
5793 collectUnexpandedParameterPacks(Init->getInit(), Unexpanded);
5794 bool ShouldExpand = false;
5795 bool RetainExpansion = false;
5796 std::optional<unsigned> NumExpansions;
5797 if (CheckParameterPacksForExpansion(Init->getEllipsisLoc(),
5798 BaseTL.getSourceRange(),
5799 Unexpanded,
5800 TemplateArgs, ShouldExpand,
5801 RetainExpansion,
5802 NumExpansions)) {
5803 AnyErrors = true;
5804 New->setInvalidDecl();
5805 continue;
5807 assert(ShouldExpand && "Partial instantiation of base initializer?");
5809 // Loop over all of the arguments in the argument pack(s),
5810 for (unsigned I = 0; I != *NumExpansions; ++I) {
5811 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
5813 // Instantiate the initializer.
5814 ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs,
5815 /*CXXDirectInit=*/true);
5816 if (TempInit.isInvalid()) {
5817 AnyErrors = true;
5818 break;
5821 // Instantiate the base type.
5822 TypeSourceInfo *BaseTInfo = SubstType(Init->getTypeSourceInfo(),
5823 TemplateArgs,
5824 Init->getSourceLocation(),
5825 New->getDeclName());
5826 if (!BaseTInfo) {
5827 AnyErrors = true;
5828 break;
5831 // Build the initializer.
5832 MemInitResult NewInit = BuildBaseInitializer(BaseTInfo->getType(),
5833 BaseTInfo, TempInit.get(),
5834 New->getParent(),
5835 SourceLocation());
5836 if (NewInit.isInvalid()) {
5837 AnyErrors = true;
5838 break;
5841 NewInits.push_back(NewInit.get());
5844 continue;
5847 // Instantiate the initializer.
5848 ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs,
5849 /*CXXDirectInit=*/true);
5850 if (TempInit.isInvalid()) {
5851 AnyErrors = true;
5852 continue;
5855 MemInitResult NewInit;
5856 if (Init->isDelegatingInitializer() || Init->isBaseInitializer()) {
5857 TypeSourceInfo *TInfo = SubstType(Init->getTypeSourceInfo(),
5858 TemplateArgs,
5859 Init->getSourceLocation(),
5860 New->getDeclName());
5861 if (!TInfo) {
5862 AnyErrors = true;
5863 New->setInvalidDecl();
5864 continue;
5867 if (Init->isBaseInitializer())
5868 NewInit = BuildBaseInitializer(TInfo->getType(), TInfo, TempInit.get(),
5869 New->getParent(), EllipsisLoc);
5870 else
5871 NewInit = BuildDelegatingInitializer(TInfo, TempInit.get(),
5872 cast<CXXRecordDecl>(CurContext->getParent()));
5873 } else if (Init->isMemberInitializer()) {
5874 FieldDecl *Member = cast_or_null<FieldDecl>(FindInstantiatedDecl(
5875 Init->getMemberLocation(),
5876 Init->getMember(),
5877 TemplateArgs));
5878 if (!Member) {
5879 AnyErrors = true;
5880 New->setInvalidDecl();
5881 continue;
5884 NewInit = BuildMemberInitializer(Member, TempInit.get(),
5885 Init->getSourceLocation());
5886 } else if (Init->isIndirectMemberInitializer()) {
5887 IndirectFieldDecl *IndirectMember =
5888 cast_or_null<IndirectFieldDecl>(FindInstantiatedDecl(
5889 Init->getMemberLocation(),
5890 Init->getIndirectMember(), TemplateArgs));
5892 if (!IndirectMember) {
5893 AnyErrors = true;
5894 New->setInvalidDecl();
5895 continue;
5898 NewInit = BuildMemberInitializer(IndirectMember, TempInit.get(),
5899 Init->getSourceLocation());
5902 if (NewInit.isInvalid()) {
5903 AnyErrors = true;
5904 New->setInvalidDecl();
5905 } else {
5906 NewInits.push_back(NewInit.get());
5910 // Assign all the initializers to the new constructor.
5911 ActOnMemInitializers(New,
5912 /*FIXME: ColonLoc */
5913 SourceLocation(),
5914 NewInits,
5915 AnyErrors);
5918 // TODO: this could be templated if the various decl types used the
5919 // same method name.
5920 static bool isInstantiationOf(ClassTemplateDecl *Pattern,
5921 ClassTemplateDecl *Instance) {
5922 Pattern = Pattern->getCanonicalDecl();
5924 do {
5925 Instance = Instance->getCanonicalDecl();
5926 if (Pattern == Instance) return true;
5927 Instance = Instance->getInstantiatedFromMemberTemplate();
5928 } while (Instance);
5930 return false;
5933 static bool isInstantiationOf(FunctionTemplateDecl *Pattern,
5934 FunctionTemplateDecl *Instance) {
5935 Pattern = Pattern->getCanonicalDecl();
5937 do {
5938 Instance = Instance->getCanonicalDecl();
5939 if (Pattern == Instance) return true;
5940 Instance = Instance->getInstantiatedFromMemberTemplate();
5941 } while (Instance);
5943 return false;
5946 static bool
5947 isInstantiationOf(ClassTemplatePartialSpecializationDecl *Pattern,
5948 ClassTemplatePartialSpecializationDecl *Instance) {
5949 Pattern
5950 = cast<ClassTemplatePartialSpecializationDecl>(Pattern->getCanonicalDecl());
5951 do {
5952 Instance = cast<ClassTemplatePartialSpecializationDecl>(
5953 Instance->getCanonicalDecl());
5954 if (Pattern == Instance)
5955 return true;
5956 Instance = Instance->getInstantiatedFromMember();
5957 } while (Instance);
5959 return false;
5962 static bool isInstantiationOf(CXXRecordDecl *Pattern,
5963 CXXRecordDecl *Instance) {
5964 Pattern = Pattern->getCanonicalDecl();
5966 do {
5967 Instance = Instance->getCanonicalDecl();
5968 if (Pattern == Instance) return true;
5969 Instance = Instance->getInstantiatedFromMemberClass();
5970 } while (Instance);
5972 return false;
5975 static bool isInstantiationOf(FunctionDecl *Pattern,
5976 FunctionDecl *Instance) {
5977 Pattern = Pattern->getCanonicalDecl();
5979 do {
5980 Instance = Instance->getCanonicalDecl();
5981 if (Pattern == Instance) return true;
5982 Instance = Instance->getInstantiatedFromMemberFunction();
5983 } while (Instance);
5985 return false;
5988 static bool isInstantiationOf(EnumDecl *Pattern,
5989 EnumDecl *Instance) {
5990 Pattern = Pattern->getCanonicalDecl();
5992 do {
5993 Instance = Instance->getCanonicalDecl();
5994 if (Pattern == Instance) return true;
5995 Instance = Instance->getInstantiatedFromMemberEnum();
5996 } while (Instance);
5998 return false;
6001 static bool isInstantiationOf(UsingShadowDecl *Pattern,
6002 UsingShadowDecl *Instance,
6003 ASTContext &C) {
6004 return declaresSameEntity(C.getInstantiatedFromUsingShadowDecl(Instance),
6005 Pattern);
6008 static bool isInstantiationOf(UsingDecl *Pattern, UsingDecl *Instance,
6009 ASTContext &C) {
6010 return declaresSameEntity(C.getInstantiatedFromUsingDecl(Instance), Pattern);
6013 template<typename T>
6014 static bool isInstantiationOfUnresolvedUsingDecl(T *Pattern, Decl *Other,
6015 ASTContext &Ctx) {
6016 // An unresolved using declaration can instantiate to an unresolved using
6017 // declaration, or to a using declaration or a using declaration pack.
6019 // Multiple declarations can claim to be instantiated from an unresolved
6020 // using declaration if it's a pack expansion. We want the UsingPackDecl
6021 // in that case, not the individual UsingDecls within the pack.
6022 bool OtherIsPackExpansion;
6023 NamedDecl *OtherFrom;
6024 if (auto *OtherUUD = dyn_cast<T>(Other)) {
6025 OtherIsPackExpansion = OtherUUD->isPackExpansion();
6026 OtherFrom = Ctx.getInstantiatedFromUsingDecl(OtherUUD);
6027 } else if (auto *OtherUPD = dyn_cast<UsingPackDecl>(Other)) {
6028 OtherIsPackExpansion = true;
6029 OtherFrom = OtherUPD->getInstantiatedFromUsingDecl();
6030 } else if (auto *OtherUD = dyn_cast<UsingDecl>(Other)) {
6031 OtherIsPackExpansion = false;
6032 OtherFrom = Ctx.getInstantiatedFromUsingDecl(OtherUD);
6033 } else {
6034 return false;
6036 return Pattern->isPackExpansion() == OtherIsPackExpansion &&
6037 declaresSameEntity(OtherFrom, Pattern);
6040 static bool isInstantiationOfStaticDataMember(VarDecl *Pattern,
6041 VarDecl *Instance) {
6042 assert(Instance->isStaticDataMember());
6044 Pattern = Pattern->getCanonicalDecl();
6046 do {
6047 Instance = Instance->getCanonicalDecl();
6048 if (Pattern == Instance) return true;
6049 Instance = Instance->getInstantiatedFromStaticDataMember();
6050 } while (Instance);
6052 return false;
6055 // Other is the prospective instantiation
6056 // D is the prospective pattern
6057 static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) {
6058 if (auto *UUD = dyn_cast<UnresolvedUsingTypenameDecl>(D))
6059 return isInstantiationOfUnresolvedUsingDecl(UUD, Other, Ctx);
6061 if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(D))
6062 return isInstantiationOfUnresolvedUsingDecl(UUD, Other, Ctx);
6064 if (D->getKind() != Other->getKind())
6065 return false;
6067 if (auto *Record = dyn_cast<CXXRecordDecl>(Other))
6068 return isInstantiationOf(cast<CXXRecordDecl>(D), Record);
6070 if (auto *Function = dyn_cast<FunctionDecl>(Other))
6071 return isInstantiationOf(cast<FunctionDecl>(D), Function);
6073 if (auto *Enum = dyn_cast<EnumDecl>(Other))
6074 return isInstantiationOf(cast<EnumDecl>(D), Enum);
6076 if (auto *Var = dyn_cast<VarDecl>(Other))
6077 if (Var->isStaticDataMember())
6078 return isInstantiationOfStaticDataMember(cast<VarDecl>(D), Var);
6080 if (auto *Temp = dyn_cast<ClassTemplateDecl>(Other))
6081 return isInstantiationOf(cast<ClassTemplateDecl>(D), Temp);
6083 if (auto *Temp = dyn_cast<FunctionTemplateDecl>(Other))
6084 return isInstantiationOf(cast<FunctionTemplateDecl>(D), Temp);
6086 if (auto *PartialSpec =
6087 dyn_cast<ClassTemplatePartialSpecializationDecl>(Other))
6088 return isInstantiationOf(cast<ClassTemplatePartialSpecializationDecl>(D),
6089 PartialSpec);
6091 if (auto *Field = dyn_cast<FieldDecl>(Other)) {
6092 if (!Field->getDeclName()) {
6093 // This is an unnamed field.
6094 return declaresSameEntity(Ctx.getInstantiatedFromUnnamedFieldDecl(Field),
6095 cast<FieldDecl>(D));
6099 if (auto *Using = dyn_cast<UsingDecl>(Other))
6100 return isInstantiationOf(cast<UsingDecl>(D), Using, Ctx);
6102 if (auto *Shadow = dyn_cast<UsingShadowDecl>(Other))
6103 return isInstantiationOf(cast<UsingShadowDecl>(D), Shadow, Ctx);
6105 return D->getDeclName() &&
6106 D->getDeclName() == cast<NamedDecl>(Other)->getDeclName();
6109 template<typename ForwardIterator>
6110 static NamedDecl *findInstantiationOf(ASTContext &Ctx,
6111 NamedDecl *D,
6112 ForwardIterator first,
6113 ForwardIterator last) {
6114 for (; first != last; ++first)
6115 if (isInstantiationOf(Ctx, D, *first))
6116 return cast<NamedDecl>(*first);
6118 return nullptr;
6121 DeclContext *Sema::FindInstantiatedContext(SourceLocation Loc, DeclContext* DC,
6122 const MultiLevelTemplateArgumentList &TemplateArgs) {
6123 if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) {
6124 Decl* ID = FindInstantiatedDecl(Loc, D, TemplateArgs, true);
6125 return cast_or_null<DeclContext>(ID);
6126 } else return DC;
6129 /// Determine whether the given context is dependent on template parameters at
6130 /// level \p Level or below.
6132 /// Sometimes we only substitute an inner set of template arguments and leave
6133 /// the outer templates alone. In such cases, contexts dependent only on the
6134 /// outer levels are not effectively dependent.
6135 static bool isDependentContextAtLevel(DeclContext *DC, unsigned Level) {
6136 if (!DC->isDependentContext())
6137 return false;
6138 if (!Level)
6139 return true;
6140 return cast<Decl>(DC)->getTemplateDepth() > Level;
6143 NamedDecl *Sema::FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
6144 const MultiLevelTemplateArgumentList &TemplateArgs,
6145 bool FindingInstantiatedContext) {
6146 DeclContext *ParentDC = D->getDeclContext();
6147 // Determine whether our parent context depends on any of the template
6148 // arguments we're currently substituting.
6149 bool ParentDependsOnArgs = isDependentContextAtLevel(
6150 ParentDC, TemplateArgs.getNumRetainedOuterLevels());
6151 // FIXME: Parameters of pointer to functions (y below) that are themselves
6152 // parameters (p below) can have their ParentDC set to the translation-unit
6153 // - thus we can not consistently check if the ParentDC of such a parameter
6154 // is Dependent or/and a FunctionOrMethod.
6155 // For e.g. this code, during Template argument deduction tries to
6156 // find an instantiated decl for (T y) when the ParentDC for y is
6157 // the translation unit.
6158 // e.g. template <class T> void Foo(auto (*p)(T y) -> decltype(y())) {}
6159 // float baz(float(*)()) { return 0.0; }
6160 // Foo(baz);
6161 // The better fix here is perhaps to ensure that a ParmVarDecl, by the time
6162 // it gets here, always has a FunctionOrMethod as its ParentDC??
6163 // For now:
6164 // - as long as we have a ParmVarDecl whose parent is non-dependent and
6165 // whose type is not instantiation dependent, do nothing to the decl
6166 // - otherwise find its instantiated decl.
6167 if (isa<ParmVarDecl>(D) && !ParentDependsOnArgs &&
6168 !cast<ParmVarDecl>(D)->getType()->isInstantiationDependentType())
6169 return D;
6170 if (isa<ParmVarDecl>(D) || isa<NonTypeTemplateParmDecl>(D) ||
6171 isa<TemplateTypeParmDecl>(D) || isa<TemplateTemplateParmDecl>(D) ||
6172 (ParentDependsOnArgs && (ParentDC->isFunctionOrMethod() ||
6173 isa<OMPDeclareReductionDecl>(ParentDC) ||
6174 isa<OMPDeclareMapperDecl>(ParentDC))) ||
6175 (isa<CXXRecordDecl>(D) && cast<CXXRecordDecl>(D)->isLambda() &&
6176 cast<CXXRecordDecl>(D)->getTemplateDepth() >
6177 TemplateArgs.getNumRetainedOuterLevels())) {
6178 // D is a local of some kind. Look into the map of local
6179 // declarations to their instantiations.
6180 if (CurrentInstantiationScope) {
6181 if (auto Found = CurrentInstantiationScope->findInstantiationOf(D)) {
6182 if (Decl *FD = Found->dyn_cast<Decl *>())
6183 return cast<NamedDecl>(FD);
6185 int PackIdx = ArgumentPackSubstitutionIndex;
6186 assert(PackIdx != -1 &&
6187 "found declaration pack but not pack expanding");
6188 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
6189 return cast<NamedDecl>((*cast<DeclArgumentPack *>(*Found))[PackIdx]);
6193 // If we're performing a partial substitution during template argument
6194 // deduction, we may not have values for template parameters yet. They
6195 // just map to themselves.
6196 if (isa<NonTypeTemplateParmDecl>(D) || isa<TemplateTypeParmDecl>(D) ||
6197 isa<TemplateTemplateParmDecl>(D))
6198 return D;
6200 if (D->isInvalidDecl())
6201 return nullptr;
6203 // Normally this function only searches for already instantiated declaration
6204 // however we have to make an exclusion for local types used before
6205 // definition as in the code:
6207 // template<typename T> void f1() {
6208 // void g1(struct x1);
6209 // struct x1 {};
6210 // }
6212 // In this case instantiation of the type of 'g1' requires definition of
6213 // 'x1', which is defined later. Error recovery may produce an enum used
6214 // before definition. In these cases we need to instantiate relevant
6215 // declarations here.
6216 bool NeedInstantiate = false;
6217 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
6218 NeedInstantiate = RD->isLocalClass();
6219 else if (isa<TypedefNameDecl>(D) &&
6220 isa<CXXDeductionGuideDecl>(D->getDeclContext()))
6221 NeedInstantiate = true;
6222 else
6223 NeedInstantiate = isa<EnumDecl>(D);
6224 if (NeedInstantiate) {
6225 Decl *Inst = SubstDecl(D, CurContext, TemplateArgs);
6226 CurrentInstantiationScope->InstantiatedLocal(D, Inst);
6227 return cast<TypeDecl>(Inst);
6230 // If we didn't find the decl, then we must have a label decl that hasn't
6231 // been found yet. Lazily instantiate it and return it now.
6232 assert(isa<LabelDecl>(D));
6234 Decl *Inst = SubstDecl(D, CurContext, TemplateArgs);
6235 assert(Inst && "Failed to instantiate label??");
6237 CurrentInstantiationScope->InstantiatedLocal(D, Inst);
6238 return cast<LabelDecl>(Inst);
6241 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
6242 if (!Record->isDependentContext())
6243 return D;
6245 // Determine whether this record is the "templated" declaration describing
6246 // a class template or class template specialization.
6247 ClassTemplateDecl *ClassTemplate = Record->getDescribedClassTemplate();
6248 if (ClassTemplate)
6249 ClassTemplate = ClassTemplate->getCanonicalDecl();
6250 else if (ClassTemplateSpecializationDecl *Spec =
6251 dyn_cast<ClassTemplateSpecializationDecl>(Record))
6252 ClassTemplate = Spec->getSpecializedTemplate()->getCanonicalDecl();
6254 // Walk the current context to find either the record or an instantiation of
6255 // it.
6256 DeclContext *DC = CurContext;
6257 while (!DC->isFileContext()) {
6258 // If we're performing substitution while we're inside the template
6259 // definition, we'll find our own context. We're done.
6260 if (DC->Equals(Record))
6261 return Record;
6263 if (CXXRecordDecl *InstRecord = dyn_cast<CXXRecordDecl>(DC)) {
6264 // Check whether we're in the process of instantiating a class template
6265 // specialization of the template we're mapping.
6266 if (ClassTemplateSpecializationDecl *InstSpec
6267 = dyn_cast<ClassTemplateSpecializationDecl>(InstRecord)){
6268 ClassTemplateDecl *SpecTemplate = InstSpec->getSpecializedTemplate();
6269 if (ClassTemplate && isInstantiationOf(ClassTemplate, SpecTemplate))
6270 return InstRecord;
6273 // Check whether we're in the process of instantiating a member class.
6274 if (isInstantiationOf(Record, InstRecord))
6275 return InstRecord;
6278 // Move to the outer template scope.
6279 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC)) {
6280 if (FD->getFriendObjectKind() &&
6281 FD->getNonTransparentDeclContext()->isFileContext()) {
6282 DC = FD->getLexicalDeclContext();
6283 continue;
6285 // An implicit deduction guide acts as if it's within the class template
6286 // specialization described by its name and first N template params.
6287 auto *Guide = dyn_cast<CXXDeductionGuideDecl>(FD);
6288 if (Guide && Guide->isImplicit()) {
6289 TemplateDecl *TD = Guide->getDeducedTemplate();
6290 // Convert the arguments to an "as-written" list.
6291 TemplateArgumentListInfo Args(Loc, Loc);
6292 for (TemplateArgument Arg : TemplateArgs.getInnermost().take_front(
6293 TD->getTemplateParameters()->size())) {
6294 ArrayRef<TemplateArgument> Unpacked(Arg);
6295 if (Arg.getKind() == TemplateArgument::Pack)
6296 Unpacked = Arg.pack_elements();
6297 for (TemplateArgument UnpackedArg : Unpacked)
6298 Args.addArgument(
6299 getTrivialTemplateArgumentLoc(UnpackedArg, QualType(), Loc));
6301 QualType T = CheckTemplateIdType(TemplateName(TD), Loc, Args);
6302 // We may get a non-null type with errors, in which case
6303 // `getAsCXXRecordDecl` will return `nullptr`. For instance, this
6304 // happens when one of the template arguments is an invalid
6305 // expression. We return early to avoid triggering the assertion
6306 // about the `CodeSynthesisContext`.
6307 if (T.isNull() || T->containsErrors())
6308 return nullptr;
6309 CXXRecordDecl *SubstRecord = T->getAsCXXRecordDecl();
6311 if (!SubstRecord) {
6312 // T can be a dependent TemplateSpecializationType when performing a
6313 // substitution for building a deduction guide or for template
6314 // argument deduction in the process of rebuilding immediate
6315 // expressions. (Because the default argument that involves a lambda
6316 // is untransformed and thus could be dependent at this point.)
6317 assert(SemaRef.RebuildingImmediateInvocation ||
6318 CodeSynthesisContexts.back().Kind ==
6319 CodeSynthesisContext::BuildingDeductionGuides);
6320 // Return a nullptr as a sentinel value, we handle it properly in
6321 // the TemplateInstantiator::TransformInjectedClassNameType
6322 // override, which we transform it to a TemplateSpecializationType.
6323 return nullptr;
6325 // Check that this template-id names the primary template and not a
6326 // partial or explicit specialization. (In the latter cases, it's
6327 // meaningless to attempt to find an instantiation of D within the
6328 // specialization.)
6329 // FIXME: The standard doesn't say what should happen here.
6330 if (FindingInstantiatedContext &&
6331 usesPartialOrExplicitSpecialization(
6332 Loc, cast<ClassTemplateSpecializationDecl>(SubstRecord))) {
6333 Diag(Loc, diag::err_specialization_not_primary_template)
6334 << T << (SubstRecord->getTemplateSpecializationKind() ==
6335 TSK_ExplicitSpecialization);
6336 return nullptr;
6338 DC = SubstRecord;
6339 continue;
6343 DC = DC->getParent();
6346 // Fall through to deal with other dependent record types (e.g.,
6347 // anonymous unions in class templates).
6350 if (!ParentDependsOnArgs)
6351 return D;
6353 ParentDC = FindInstantiatedContext(Loc, ParentDC, TemplateArgs);
6354 if (!ParentDC)
6355 return nullptr;
6357 if (ParentDC != D->getDeclContext()) {
6358 // We performed some kind of instantiation in the parent context,
6359 // so now we need to look into the instantiated parent context to
6360 // find the instantiation of the declaration D.
6362 // If our context used to be dependent, we may need to instantiate
6363 // it before performing lookup into that context.
6364 bool IsBeingInstantiated = false;
6365 if (CXXRecordDecl *Spec = dyn_cast<CXXRecordDecl>(ParentDC)) {
6366 if (!Spec->isDependentContext()) {
6367 QualType T = Context.getTypeDeclType(Spec);
6368 const RecordType *Tag = T->getAs<RecordType>();
6369 assert(Tag && "type of non-dependent record is not a RecordType");
6370 if (Tag->isBeingDefined())
6371 IsBeingInstantiated = true;
6372 if (!Tag->isBeingDefined() &&
6373 RequireCompleteType(Loc, T, diag::err_incomplete_type))
6374 return nullptr;
6376 ParentDC = Tag->getDecl();
6380 NamedDecl *Result = nullptr;
6381 // FIXME: If the name is a dependent name, this lookup won't necessarily
6382 // find it. Does that ever matter?
6383 if (auto Name = D->getDeclName()) {
6384 DeclarationNameInfo NameInfo(Name, D->getLocation());
6385 DeclarationNameInfo NewNameInfo =
6386 SubstDeclarationNameInfo(NameInfo, TemplateArgs);
6387 Name = NewNameInfo.getName();
6388 if (!Name)
6389 return nullptr;
6390 DeclContext::lookup_result Found = ParentDC->lookup(Name);
6392 Result = findInstantiationOf(Context, D, Found.begin(), Found.end());
6393 } else {
6394 // Since we don't have a name for the entity we're looking for,
6395 // our only option is to walk through all of the declarations to
6396 // find that name. This will occur in a few cases:
6398 // - anonymous struct/union within a template
6399 // - unnamed class/struct/union/enum within a template
6401 // FIXME: Find a better way to find these instantiations!
6402 Result = findInstantiationOf(Context, D,
6403 ParentDC->decls_begin(),
6404 ParentDC->decls_end());
6407 if (!Result) {
6408 if (isa<UsingShadowDecl>(D)) {
6409 // UsingShadowDecls can instantiate to nothing because of using hiding.
6410 } else if (hasUncompilableErrorOccurred()) {
6411 // We've already complained about some ill-formed code, so most likely
6412 // this declaration failed to instantiate. There's no point in
6413 // complaining further, since this is normal in invalid code.
6414 // FIXME: Use more fine-grained 'invalid' tracking for this.
6415 } else if (IsBeingInstantiated) {
6416 // The class in which this member exists is currently being
6417 // instantiated, and we haven't gotten around to instantiating this
6418 // member yet. This can happen when the code uses forward declarations
6419 // of member classes, and introduces ordering dependencies via
6420 // template instantiation.
6421 Diag(Loc, diag::err_member_not_yet_instantiated)
6422 << D->getDeclName()
6423 << Context.getTypeDeclType(cast<CXXRecordDecl>(ParentDC));
6424 Diag(D->getLocation(), diag::note_non_instantiated_member_here);
6425 } else if (EnumConstantDecl *ED = dyn_cast<EnumConstantDecl>(D)) {
6426 // This enumeration constant was found when the template was defined,
6427 // but can't be found in the instantiation. This can happen if an
6428 // unscoped enumeration member is explicitly specialized.
6429 EnumDecl *Enum = cast<EnumDecl>(ED->getLexicalDeclContext());
6430 EnumDecl *Spec = cast<EnumDecl>(FindInstantiatedDecl(Loc, Enum,
6431 TemplateArgs));
6432 assert(Spec->getTemplateSpecializationKind() ==
6433 TSK_ExplicitSpecialization);
6434 Diag(Loc, diag::err_enumerator_does_not_exist)
6435 << D->getDeclName()
6436 << Context.getTypeDeclType(cast<TypeDecl>(Spec->getDeclContext()));
6437 Diag(Spec->getLocation(), diag::note_enum_specialized_here)
6438 << Context.getTypeDeclType(Spec);
6439 } else {
6440 // We should have found something, but didn't.
6441 llvm_unreachable("Unable to find instantiation of declaration!");
6445 D = Result;
6448 return D;
6451 void Sema::PerformPendingInstantiations(bool LocalOnly) {
6452 std::deque<PendingImplicitInstantiation> delayedPCHInstantiations;
6453 while (!PendingLocalImplicitInstantiations.empty() ||
6454 (!LocalOnly && !PendingInstantiations.empty())) {
6455 PendingImplicitInstantiation Inst;
6457 if (PendingLocalImplicitInstantiations.empty()) {
6458 Inst = PendingInstantiations.front();
6459 PendingInstantiations.pop_front();
6460 } else {
6461 Inst = PendingLocalImplicitInstantiations.front();
6462 PendingLocalImplicitInstantiations.pop_front();
6465 // Instantiate function definitions
6466 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) {
6467 bool DefinitionRequired = Function->getTemplateSpecializationKind() ==
6468 TSK_ExplicitInstantiationDefinition;
6469 if (Function->isMultiVersion()) {
6470 getASTContext().forEachMultiversionedFunctionVersion(
6471 Function, [this, Inst, DefinitionRequired](FunctionDecl *CurFD) {
6472 InstantiateFunctionDefinition(/*FIXME:*/ Inst.second, CurFD, true,
6473 DefinitionRequired, true);
6474 if (CurFD->isDefined())
6475 CurFD->setInstantiationIsPending(false);
6477 } else {
6478 InstantiateFunctionDefinition(/*FIXME:*/ Inst.second, Function, true,
6479 DefinitionRequired, true);
6480 if (Function->isDefined())
6481 Function->setInstantiationIsPending(false);
6483 // Definition of a PCH-ed template declaration may be available only in the TU.
6484 if (!LocalOnly && LangOpts.PCHInstantiateTemplates &&
6485 TUKind == TU_Prefix && Function->instantiationIsPending())
6486 delayedPCHInstantiations.push_back(Inst);
6487 continue;
6490 // Instantiate variable definitions
6491 VarDecl *Var = cast<VarDecl>(Inst.first);
6493 assert((Var->isStaticDataMember() ||
6494 isa<VarTemplateSpecializationDecl>(Var)) &&
6495 "Not a static data member, nor a variable template"
6496 " specialization?");
6498 // Don't try to instantiate declarations if the most recent redeclaration
6499 // is invalid.
6500 if (Var->getMostRecentDecl()->isInvalidDecl())
6501 continue;
6503 // Check if the most recent declaration has changed the specialization kind
6504 // and removed the need for implicit instantiation.
6505 switch (Var->getMostRecentDecl()
6506 ->getTemplateSpecializationKindForInstantiation()) {
6507 case TSK_Undeclared:
6508 llvm_unreachable("Cannot instantitiate an undeclared specialization.");
6509 case TSK_ExplicitInstantiationDeclaration:
6510 case TSK_ExplicitSpecialization:
6511 continue; // No longer need to instantiate this type.
6512 case TSK_ExplicitInstantiationDefinition:
6513 // We only need an instantiation if the pending instantiation *is* the
6514 // explicit instantiation.
6515 if (Var != Var->getMostRecentDecl())
6516 continue;
6517 break;
6518 case TSK_ImplicitInstantiation:
6519 break;
6522 PrettyDeclStackTraceEntry CrashInfo(Context, Var, SourceLocation(),
6523 "instantiating variable definition");
6524 bool DefinitionRequired = Var->getTemplateSpecializationKind() ==
6525 TSK_ExplicitInstantiationDefinition;
6527 // Instantiate static data member definitions or variable template
6528 // specializations.
6529 InstantiateVariableDefinition(/*FIXME:*/ Inst.second, Var, true,
6530 DefinitionRequired, true);
6533 if (!LocalOnly && LangOpts.PCHInstantiateTemplates)
6534 PendingInstantiations.swap(delayedPCHInstantiations);
6537 void Sema::PerformDependentDiagnostics(const DeclContext *Pattern,
6538 const MultiLevelTemplateArgumentList &TemplateArgs) {
6539 for (auto *DD : Pattern->ddiags()) {
6540 switch (DD->getKind()) {
6541 case DependentDiagnostic::Access:
6542 HandleDependentAccessCheck(*DD, TemplateArgs);
6543 break;