clang 21.0.0git
SemaTemplateInstantiateDecl.cpp
Go to the documentation of this file.
1//===--- SemaTemplateInstantiateDecl.cpp - C++ Template Decl Instantiation ===/
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//===----------------------------------------------------------------------===/
7//
8// This file implements C++ template instantiation for declarations.
9//
10//===----------------------------------------------------------------------===/
11
12#include "TreeTransform.h"
15#include "clang/AST/ASTLambda.h"
19#include "clang/AST/Expr.h"
20#include "clang/AST/ExprCXX.h"
22#include "clang/AST/TypeLoc.h"
27#include "clang/Sema/Lookup.h"
30#include "clang/Sema/SemaCUDA.h"
31#include "clang/Sema/SemaHLSL.h"
32#include "clang/Sema/SemaObjC.h"
35#include "clang/Sema/Template.h"
37#include "llvm/Support/TimeProfiler.h"
38#include <optional>
39
40using namespace clang;
41
42static bool isDeclWithinFunction(const Decl *D) {
43 const DeclContext *DC = D->getDeclContext();
44 if (DC->isFunctionOrMethod())
45 return true;
46
47 if (DC->isRecord())
48 return cast<CXXRecordDecl>(DC)->isLocalClass();
49
50 return false;
51}
52
53template<typename DeclT>
54static bool SubstQualifier(Sema &SemaRef, const DeclT *OldDecl, DeclT *NewDecl,
55 const MultiLevelTemplateArgumentList &TemplateArgs) {
56 if (!OldDecl->getQualifierLoc())
57 return false;
58
59 assert((NewDecl->getFriendObjectKind() ||
60 !OldDecl->getLexicalDeclContext()->isDependentContext()) &&
61 "non-friend with qualified name defined in dependent context");
62 Sema::ContextRAII SavedContext(
63 SemaRef,
64 const_cast<DeclContext *>(NewDecl->getFriendObjectKind()
65 ? NewDecl->getLexicalDeclContext()
66 : OldDecl->getLexicalDeclContext()));
67
68 NestedNameSpecifierLoc NewQualifierLoc
69 = SemaRef.SubstNestedNameSpecifierLoc(OldDecl->getQualifierLoc(),
70 TemplateArgs);
71
72 if (!NewQualifierLoc)
73 return true;
74
75 NewDecl->setQualifierInfo(NewQualifierLoc);
76 return false;
77}
78
80 DeclaratorDecl *NewDecl) {
81 return ::SubstQualifier(SemaRef, OldDecl, NewDecl, TemplateArgs);
82}
83
85 TagDecl *NewDecl) {
86 return ::SubstQualifier(SemaRef, OldDecl, NewDecl, TemplateArgs);
87}
88
89// Include attribute instantiation code.
90#include "clang/Sema/AttrTemplateInstantiate.inc"
91
93 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
94 const AlignedAttr *Aligned, Decl *New, bool IsPackExpansion) {
95 if (Aligned->isAlignmentExpr()) {
96 // The alignment expression is a constant expression.
99 ExprResult Result = S.SubstExpr(Aligned->getAlignmentExpr(), TemplateArgs);
100 if (!Result.isInvalid())
101 S.AddAlignedAttr(New, *Aligned, Result.getAs<Expr>(), IsPackExpansion);
102 } else {
104 S.SubstType(Aligned->getAlignmentType(), TemplateArgs,
105 Aligned->getLocation(), DeclarationName())) {
106 if (!S.CheckAlignasTypeArgument(Aligned->getSpelling(), Result,
107 Aligned->getLocation(),
108 Result->getTypeLoc().getSourceRange()))
109 S.AddAlignedAttr(New, *Aligned, Result, IsPackExpansion);
110 }
111 }
112}
113
115 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
116 const AlignedAttr *Aligned, Decl *New) {
117 if (!Aligned->isPackExpansion()) {
118 instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, false);
119 return;
120 }
121
123 if (Aligned->isAlignmentExpr())
124 S.collectUnexpandedParameterPacks(Aligned->getAlignmentExpr(),
125 Unexpanded);
126 else
127 S.collectUnexpandedParameterPacks(Aligned->getAlignmentType()->getTypeLoc(),
128 Unexpanded);
129 assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
130
131 // Determine whether we can expand this attribute pack yet.
132 bool Expand = true, RetainExpansion = false;
133 std::optional<unsigned> NumExpansions;
134 // FIXME: Use the actual location of the ellipsis.
135 SourceLocation EllipsisLoc = Aligned->getLocation();
136 if (S.CheckParameterPacksForExpansion(EllipsisLoc, Aligned->getRange(),
137 Unexpanded, TemplateArgs, Expand,
138 RetainExpansion, NumExpansions))
139 return;
140
141 if (!Expand) {
143 instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, true);
144 } else {
145 for (unsigned I = 0; I != *NumExpansions; ++I) {
147 instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, false);
148 }
149 }
150}
151
153 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
154 const AssumeAlignedAttr *Aligned, Decl *New) {
155 // The alignment expression is a constant expression.
158
159 Expr *E, *OE = nullptr;
160 ExprResult Result = S.SubstExpr(Aligned->getAlignment(), TemplateArgs);
161 if (Result.isInvalid())
162 return;
163 E = Result.getAs<Expr>();
164
165 if (Aligned->getOffset()) {
166 Result = S.SubstExpr(Aligned->getOffset(), TemplateArgs);
167 if (Result.isInvalid())
168 return;
169 OE = Result.getAs<Expr>();
170 }
171
172 S.AddAssumeAlignedAttr(New, *Aligned, E, OE);
173}
174
176 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
177 const AlignValueAttr *Aligned, Decl *New) {
178 // The alignment expression is a constant expression.
181 ExprResult Result = S.SubstExpr(Aligned->getAlignment(), TemplateArgs);
182 if (!Result.isInvalid())
183 S.AddAlignValueAttr(New, *Aligned, Result.getAs<Expr>());
184}
185
187 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
188 const AllocAlignAttr *Align, Decl *New) {
190 S.getASTContext(),
191 llvm::APInt(64, Align->getParamIndex().getSourceIndex()),
192 S.getASTContext().UnsignedLongLongTy, Align->getLocation());
193 S.AddAllocAlignAttr(New, *Align, Param);
194}
195
197 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
198 const AnnotateAttr *Attr, Decl *New) {
201
202 // If the attribute has delayed arguments it will have to instantiate those
203 // and handle them as new arguments for the attribute.
204 bool HasDelayedArgs = Attr->delayedArgs_size();
205
206 ArrayRef<Expr *> ArgsToInstantiate =
207 HasDelayedArgs
208 ? ArrayRef<Expr *>{Attr->delayedArgs_begin(), Attr->delayedArgs_end()}
209 : ArrayRef<Expr *>{Attr->args_begin(), Attr->args_end()};
210
212 if (S.SubstExprs(ArgsToInstantiate,
213 /*IsCall=*/false, TemplateArgs, Args))
214 return;
215
216 StringRef Str = Attr->getAnnotation();
217 if (HasDelayedArgs) {
218 if (Args.size() < 1) {
219 S.Diag(Attr->getLoc(), diag::err_attribute_too_few_arguments)
220 << Attr << 1;
221 return;
222 }
223
224 if (!S.checkStringLiteralArgumentAttr(*Attr, Args[0], Str))
225 return;
226
228 ActualArgs.insert(ActualArgs.begin(), Args.begin() + 1, Args.end());
229 std::swap(Args, ActualArgs);
230 }
231 auto *AA = S.CreateAnnotationAttr(*Attr, Str, Args);
232 if (AA) {
233 New->addAttr(AA);
234 }
235}
236
238 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
239 const Attr *A, Expr *OldCond, const Decl *Tmpl, FunctionDecl *New) {
240 Expr *Cond = nullptr;
241 {
242 Sema::ContextRAII SwitchContext(S, New);
245 ExprResult Result = S.SubstExpr(OldCond, TemplateArgs);
246 if (Result.isInvalid())
247 return nullptr;
248 Cond = Result.getAs<Expr>();
249 }
250 if (!Cond->isTypeDependent()) {
252 if (Converted.isInvalid())
253 return nullptr;
254 Cond = Converted.get();
255 }
256
258 if (OldCond->isValueDependent() && !Cond->isValueDependent() &&
259 !Expr::isPotentialConstantExprUnevaluated(Cond, New, Diags)) {
260 S.Diag(A->getLocation(), diag::err_attr_cond_never_constant_expr) << A;
261 for (const auto &P : Diags)
262 S.Diag(P.first, P.second);
263 return nullptr;
264 }
265 return Cond;
266}
267
269 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
270 const EnableIfAttr *EIA, const Decl *Tmpl, FunctionDecl *New) {
272 S, TemplateArgs, EIA, EIA->getCond(), Tmpl, New);
273
274 if (Cond)
275 New->addAttr(new (S.getASTContext()) EnableIfAttr(S.getASTContext(), *EIA,
276 Cond, EIA->getMessage()));
277}
278
280 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
281 const DiagnoseIfAttr *DIA, const Decl *Tmpl, FunctionDecl *New) {
283 S, TemplateArgs, DIA, DIA->getCond(), Tmpl, New);
284
285 if (Cond)
286 New->addAttr(new (S.getASTContext()) DiagnoseIfAttr(
287 S.getASTContext(), *DIA, Cond, DIA->getMessage(),
288 DIA->getDefaultSeverity(), DIA->getWarningGroup(),
289 DIA->getArgDependent(), New));
290}
291
292// Constructs and adds to New a new instance of CUDALaunchBoundsAttr using
293// template A as the base and arguments from TemplateArgs.
295 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
296 const CUDALaunchBoundsAttr &Attr, Decl *New) {
297 // The alignment expression is a constant expression.
300
301 ExprResult Result = S.SubstExpr(Attr.getMaxThreads(), TemplateArgs);
302 if (Result.isInvalid())
303 return;
304 Expr *MaxThreads = Result.getAs<Expr>();
305
306 Expr *MinBlocks = nullptr;
307 if (Attr.getMinBlocks()) {
308 Result = S.SubstExpr(Attr.getMinBlocks(), TemplateArgs);
309 if (Result.isInvalid())
310 return;
311 MinBlocks = Result.getAs<Expr>();
312 }
313
314 Expr *MaxBlocks = nullptr;
315 if (Attr.getMaxBlocks()) {
316 Result = S.SubstExpr(Attr.getMaxBlocks(), TemplateArgs);
317 if (Result.isInvalid())
318 return;
319 MaxBlocks = Result.getAs<Expr>();
320 }
321
322 S.AddLaunchBoundsAttr(New, Attr, MaxThreads, MinBlocks, MaxBlocks);
323}
324
325static void
327 const MultiLevelTemplateArgumentList &TemplateArgs,
328 const ModeAttr &Attr, Decl *New) {
329 S.AddModeAttr(New, Attr, Attr.getMode(),
330 /*InInstantiation=*/true);
331}
332
333/// Instantiation of 'declare simd' attribute and its arguments.
335 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
336 const OMPDeclareSimdDeclAttr &Attr, Decl *New) {
337 // Allow 'this' in clauses with varlist.
338 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(New))
339 New = FTD->getTemplatedDecl();
340 auto *FD = cast<FunctionDecl>(New);
341 auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(FD->getDeclContext());
342 SmallVector<Expr *, 4> Uniforms, Aligneds, Alignments, Linears, Steps;
343 SmallVector<unsigned, 4> LinModifiers;
344
345 auto SubstExpr = [&](Expr *E) -> ExprResult {
346 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
347 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
348 Sema::ContextRAII SavedContext(S, FD);
350 if (FD->getNumParams() > PVD->getFunctionScopeIndex())
351 Local.InstantiatedLocal(
352 PVD, FD->getParamDecl(PVD->getFunctionScopeIndex()));
353 return S.SubstExpr(E, TemplateArgs);
354 }
355 Sema::CXXThisScopeRAII ThisScope(S, ThisContext, Qualifiers(),
356 FD->isCXXInstanceMember());
357 return S.SubstExpr(E, TemplateArgs);
358 };
359
360 // Substitute a single OpenMP clause, which is a potentially-evaluated
361 // full-expression.
362 auto Subst = [&](Expr *E) -> ExprResult {
365 ExprResult Res = SubstExpr(E);
366 if (Res.isInvalid())
367 return Res;
368 return S.ActOnFinishFullExpr(Res.get(), false);
369 };
370
371 ExprResult Simdlen;
372 if (auto *E = Attr.getSimdlen())
373 Simdlen = Subst(E);
374
375 if (Attr.uniforms_size() > 0) {
376 for(auto *E : Attr.uniforms()) {
377 ExprResult Inst = Subst(E);
378 if (Inst.isInvalid())
379 continue;
380 Uniforms.push_back(Inst.get());
381 }
382 }
383
384 auto AI = Attr.alignments_begin();
385 for (auto *E : Attr.aligneds()) {
386 ExprResult Inst = Subst(E);
387 if (Inst.isInvalid())
388 continue;
389 Aligneds.push_back(Inst.get());
390 Inst = ExprEmpty();
391 if (*AI)
392 Inst = S.SubstExpr(*AI, TemplateArgs);
393 Alignments.push_back(Inst.get());
394 ++AI;
395 }
396
397 auto SI = Attr.steps_begin();
398 for (auto *E : Attr.linears()) {
399 ExprResult Inst = Subst(E);
400 if (Inst.isInvalid())
401 continue;
402 Linears.push_back(Inst.get());
403 Inst = ExprEmpty();
404 if (*SI)
405 Inst = S.SubstExpr(*SI, TemplateArgs);
406 Steps.push_back(Inst.get());
407 ++SI;
408 }
409 LinModifiers.append(Attr.modifiers_begin(), Attr.modifiers_end());
411 S.ConvertDeclToDeclGroup(New), Attr.getBranchState(), Simdlen.get(),
412 Uniforms, Aligneds, Alignments, Linears, LinModifiers, Steps,
413 Attr.getRange());
414}
415
416/// Instantiation of 'declare variant' attribute and its arguments.
418 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
419 const OMPDeclareVariantAttr &Attr, Decl *New) {
420 // Allow 'this' in clauses with varlist.
421 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(New))
422 New = FTD->getTemplatedDecl();
423 auto *FD = cast<FunctionDecl>(New);
424 auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(FD->getDeclContext());
425
426 auto &&SubstExpr = [FD, ThisContext, &S, &TemplateArgs](Expr *E) {
427 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
428 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
429 Sema::ContextRAII SavedContext(S, FD);
431 if (FD->getNumParams() > PVD->getFunctionScopeIndex())
432 Local.InstantiatedLocal(
433 PVD, FD->getParamDecl(PVD->getFunctionScopeIndex()));
434 return S.SubstExpr(E, TemplateArgs);
435 }
436 Sema::CXXThisScopeRAII ThisScope(S, ThisContext, Qualifiers(),
437 FD->isCXXInstanceMember());
438 return S.SubstExpr(E, TemplateArgs);
439 };
440
441 // Substitute a single OpenMP clause, which is a potentially-evaluated
442 // full-expression.
443 auto &&Subst = [&SubstExpr, &S](Expr *E) {
446 ExprResult Res = SubstExpr(E);
447 if (Res.isInvalid())
448 return Res;
449 return S.ActOnFinishFullExpr(Res.get(), false);
450 };
451
452 ExprResult VariantFuncRef;
453 if (Expr *E = Attr.getVariantFuncRef()) {
454 // Do not mark function as is used to prevent its emission if this is the
455 // only place where it is used.
458 VariantFuncRef = Subst(E);
459 }
460
461 // Copy the template version of the OMPTraitInfo and run substitute on all
462 // score and condition expressiosn.
464 TI = *Attr.getTraitInfos();
465
466 // Try to substitute template parameters in score and condition expressions.
467 auto SubstScoreOrConditionExpr = [&S, Subst](Expr *&E, bool) {
468 if (E) {
471 ExprResult ER = Subst(E);
472 if (ER.isUsable())
473 E = ER.get();
474 else
475 return true;
476 }
477 return false;
478 };
479 if (TI.anyScoreOrCondition(SubstScoreOrConditionExpr))
480 return;
481
482 Expr *E = VariantFuncRef.get();
483
484 // Check function/variant ref for `omp declare variant` but not for `omp
485 // begin declare variant` (which use implicit attributes).
486 std::optional<std::pair<FunctionDecl *, Expr *>> DeclVarData =
488 S.ConvertDeclToDeclGroup(New), E, TI, Attr.appendArgs_size(),
489 Attr.getRange());
490
491 if (!DeclVarData)
492 return;
493
494 E = DeclVarData->second;
495 FD = DeclVarData->first;
496
497 if (auto *VariantDRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts())) {
498 if (auto *VariantFD = dyn_cast<FunctionDecl>(VariantDRE->getDecl())) {
499 if (auto *VariantFTD = VariantFD->getDescribedFunctionTemplate()) {
500 if (!VariantFTD->isThisDeclarationADefinition())
501 return;
504 S.Context, TemplateArgs.getInnermost());
505
506 auto *SubstFD = S.InstantiateFunctionDeclaration(VariantFTD, TAL,
507 New->getLocation());
508 if (!SubstFD)
509 return;
511 SubstFD->getType(), FD->getType(),
512 /* OfBlockPointer */ false,
513 /* Unqualified */ false, /* AllowCXX */ true);
514 if (NewType.isNull())
515 return;
517 New->getLocation(), SubstFD, /* Recursive */ true,
518 /* DefinitionRequired */ false, /* AtEndOfTU */ false);
519 SubstFD->setInstantiationIsPending(!SubstFD->isDefined());
521 SourceLocation(), SubstFD,
522 /* RefersToEnclosingVariableOrCapture */ false,
523 /* NameLoc */ SubstFD->getLocation(),
524 SubstFD->getType(), ExprValueKind::VK_PRValue);
525 }
526 }
527 }
528
529 SmallVector<Expr *, 8> NothingExprs;
530 SmallVector<Expr *, 8> NeedDevicePtrExprs;
532
533 for (Expr *E : Attr.adjustArgsNothing()) {
534 ExprResult ER = Subst(E);
535 if (ER.isInvalid())
536 continue;
537 NothingExprs.push_back(ER.get());
538 }
539 for (Expr *E : Attr.adjustArgsNeedDevicePtr()) {
540 ExprResult ER = Subst(E);
541 if (ER.isInvalid())
542 continue;
543 NeedDevicePtrExprs.push_back(ER.get());
544 }
545 for (OMPInteropInfo &II : Attr.appendArgs()) {
546 // When prefer_type is implemented for append_args handle them here too.
547 AppendArgs.emplace_back(II.IsTarget, II.IsTargetSync);
548 }
549
551 FD, E, TI, NothingExprs, NeedDevicePtrExprs, AppendArgs, SourceLocation(),
553}
554
556 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
557 const AMDGPUFlatWorkGroupSizeAttr &Attr, Decl *New) {
558 // Both min and max expression are constant expressions.
561
562 ExprResult Result = S.SubstExpr(Attr.getMin(), TemplateArgs);
563 if (Result.isInvalid())
564 return;
565 Expr *MinExpr = Result.getAs<Expr>();
566
567 Result = S.SubstExpr(Attr.getMax(), TemplateArgs);
568 if (Result.isInvalid())
569 return;
570 Expr *MaxExpr = Result.getAs<Expr>();
571
572 S.AMDGPU().addAMDGPUFlatWorkGroupSizeAttr(New, Attr, MinExpr, MaxExpr);
573}
574
576 const MultiLevelTemplateArgumentList &TemplateArgs, ExplicitSpecifier ES) {
577 if (!ES.getExpr())
578 return ES;
579 Expr *OldCond = ES.getExpr();
580 Expr *Cond = nullptr;
581 {
584 ExprResult SubstResult = SubstExpr(OldCond, TemplateArgs);
585 if (SubstResult.isInvalid()) {
587 }
588 Cond = SubstResult.get();
589 }
590 ExplicitSpecifier Result(Cond, ES.getKind());
591 if (!Cond->isTypeDependent())
593 return Result;
594}
595
597 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
598 const AMDGPUWavesPerEUAttr &Attr, Decl *New) {
599 // Both min and max expression are constant expressions.
602
603 ExprResult Result = S.SubstExpr(Attr.getMin(), TemplateArgs);
604 if (Result.isInvalid())
605 return;
606 Expr *MinExpr = Result.getAs<Expr>();
607
608 Expr *MaxExpr = nullptr;
609 if (auto Max = Attr.getMax()) {
610 Result = S.SubstExpr(Max, TemplateArgs);
611 if (Result.isInvalid())
612 return;
613 MaxExpr = Result.getAs<Expr>();
614 }
615
616 S.AMDGPU().addAMDGPUWavesPerEUAttr(New, Attr, MinExpr, MaxExpr);
617}
618
620 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
621 const AMDGPUMaxNumWorkGroupsAttr &Attr, Decl *New) {
624
625 ExprResult ResultX = S.SubstExpr(Attr.getMaxNumWorkGroupsX(), TemplateArgs);
626 if (!ResultX.isUsable())
627 return;
628 ExprResult ResultY = S.SubstExpr(Attr.getMaxNumWorkGroupsY(), TemplateArgs);
629 if (!ResultY.isUsable())
630 return;
631 ExprResult ResultZ = S.SubstExpr(Attr.getMaxNumWorkGroupsZ(), TemplateArgs);
632 if (!ResultZ.isUsable())
633 return;
634
635 Expr *XExpr = ResultX.getAs<Expr>();
636 Expr *YExpr = ResultY.getAs<Expr>();
637 Expr *ZExpr = ResultZ.getAs<Expr>();
638
639 S.AMDGPU().addAMDGPUMaxNumWorkGroupsAttr(New, Attr, XExpr, YExpr, ZExpr);
640}
641
642// This doesn't take any template parameters, but we have a custom action that
643// needs to happen when the kernel itself is instantiated. We need to run the
644// ItaniumMangler to mark the names required to name this kernel.
646 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
647 const SYCLKernelAttr &Attr, Decl *New) {
648 New->addAttr(Attr.clone(S.getASTContext()));
649}
650
651/// Determine whether the attribute A might be relevant to the declaration D.
652/// If not, we can skip instantiating it. The attribute may or may not have
653/// been instantiated yet.
654static bool isRelevantAttr(Sema &S, const Decl *D, const Attr *A) {
655 // 'preferred_name' is only relevant to the matching specialization of the
656 // template.
657 if (const auto *PNA = dyn_cast<PreferredNameAttr>(A)) {
658 QualType T = PNA->getTypedefType();
659 const auto *RD = cast<CXXRecordDecl>(D);
660 if (!T->isDependentType() && !RD->isDependentContext() &&
662 return false;
663 for (const auto *ExistingPNA : D->specific_attrs<PreferredNameAttr>())
664 if (S.Context.hasSameType(ExistingPNA->getTypedefType(),
665 PNA->getTypedefType()))
666 return false;
667 return true;
668 }
669
670 if (const auto *BA = dyn_cast<BuiltinAttr>(A)) {
671 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
672 switch (BA->getID()) {
673 case Builtin::BIforward:
674 // Do not treat 'std::forward' as a builtin if it takes an rvalue reference
675 // type and returns an lvalue reference type. The library implementation
676 // will produce an error in this case; don't get in its way.
677 if (FD && FD->getNumParams() >= 1 &&
680 return false;
681 }
682 [[fallthrough]];
683 case Builtin::BImove:
684 case Builtin::BImove_if_noexcept:
685 // HACK: Super-old versions of libc++ (3.1 and earlier) provide
686 // std::forward and std::move overloads that sometimes return by value
687 // instead of by reference when building in C++98 mode. Don't treat such
688 // cases as builtins.
689 if (FD && !FD->getReturnType()->isReferenceType())
690 return false;
691 break;
692 }
693 }
694
695 return true;
696}
697
699 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
700 const HLSLParamModifierAttr *Attr, Decl *New) {
701 ParmVarDecl *P = cast<ParmVarDecl>(New);
702 P->addAttr(Attr->clone(S.getASTContext()));
703 P->setType(S.HLSL().getInoutParameterType(P->getType()));
704}
705
707 const MultiLevelTemplateArgumentList &TemplateArgs, const Decl *Tmpl,
708 Decl *New, LateInstantiatedAttrVec *LateAttrs,
709 LocalInstantiationScope *OuterMostScope) {
710 if (NamedDecl *ND = dyn_cast<NamedDecl>(New)) {
711 // FIXME: This function is called multiple times for the same template
712 // specialization. We should only instantiate attributes that were added
713 // since the previous instantiation.
714 for (const auto *TmplAttr : Tmpl->attrs()) {
715 if (!isRelevantAttr(*this, New, TmplAttr))
716 continue;
717
718 // FIXME: If any of the special case versions from InstantiateAttrs become
719 // applicable to template declaration, we'll need to add them here.
720 CXXThisScopeRAII ThisScope(
721 *this, dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext()),
722 Qualifiers(), ND->isCXXInstanceMember());
723
725 TmplAttr, Context, *this, TemplateArgs);
726 if (NewAttr && isRelevantAttr(*this, New, NewAttr))
727 New->addAttr(NewAttr);
728 }
729 }
730}
731
734 switch (A->getKind()) {
735 case clang::attr::CFConsumed:
737 case clang::attr::OSConsumed:
739 case clang::attr::NSConsumed:
741 default:
742 llvm_unreachable("Wrong argument supplied");
743 }
744}
745
747 const Decl *Tmpl, Decl *New,
748 LateInstantiatedAttrVec *LateAttrs,
749 LocalInstantiationScope *OuterMostScope) {
750 for (const auto *TmplAttr : Tmpl->attrs()) {
751 if (!isRelevantAttr(*this, New, TmplAttr))
752 continue;
753
754 // FIXME: This should be generalized to more than just the AlignedAttr.
755 const AlignedAttr *Aligned = dyn_cast<AlignedAttr>(TmplAttr);
756 if (Aligned && Aligned->isAlignmentDependent()) {
757 instantiateDependentAlignedAttr(*this, TemplateArgs, Aligned, New);
758 continue;
759 }
760
761 if (const auto *AssumeAligned = dyn_cast<AssumeAlignedAttr>(TmplAttr)) {
762 instantiateDependentAssumeAlignedAttr(*this, TemplateArgs, AssumeAligned, New);
763 continue;
764 }
765
766 if (const auto *AlignValue = dyn_cast<AlignValueAttr>(TmplAttr)) {
767 instantiateDependentAlignValueAttr(*this, TemplateArgs, AlignValue, New);
768 continue;
769 }
770
771 if (const auto *AllocAlign = dyn_cast<AllocAlignAttr>(TmplAttr)) {
772 instantiateDependentAllocAlignAttr(*this, TemplateArgs, AllocAlign, New);
773 continue;
774 }
775
776 if (const auto *Annotate = dyn_cast<AnnotateAttr>(TmplAttr)) {
777 instantiateDependentAnnotationAttr(*this, TemplateArgs, Annotate, New);
778 continue;
779 }
780
781 if (const auto *EnableIf = dyn_cast<EnableIfAttr>(TmplAttr)) {
782 instantiateDependentEnableIfAttr(*this, TemplateArgs, EnableIf, Tmpl,
783 cast<FunctionDecl>(New));
784 continue;
785 }
786
787 if (const auto *DiagnoseIf = dyn_cast<DiagnoseIfAttr>(TmplAttr)) {
788 instantiateDependentDiagnoseIfAttr(*this, TemplateArgs, DiagnoseIf, Tmpl,
789 cast<FunctionDecl>(New));
790 continue;
791 }
792
793 if (const auto *CUDALaunchBounds =
794 dyn_cast<CUDALaunchBoundsAttr>(TmplAttr)) {
796 *CUDALaunchBounds, New);
797 continue;
798 }
799
800 if (const auto *Mode = dyn_cast<ModeAttr>(TmplAttr)) {
801 instantiateDependentModeAttr(*this, TemplateArgs, *Mode, New);
802 continue;
803 }
804
805 if (const auto *OMPAttr = dyn_cast<OMPDeclareSimdDeclAttr>(TmplAttr)) {
806 instantiateOMPDeclareSimdDeclAttr(*this, TemplateArgs, *OMPAttr, New);
807 continue;
808 }
809
810 if (const auto *OMPAttr = dyn_cast<OMPDeclareVariantAttr>(TmplAttr)) {
811 instantiateOMPDeclareVariantAttr(*this, TemplateArgs, *OMPAttr, New);
812 continue;
813 }
814
815 if (const auto *AMDGPUFlatWorkGroupSize =
816 dyn_cast<AMDGPUFlatWorkGroupSizeAttr>(TmplAttr)) {
818 *this, TemplateArgs, *AMDGPUFlatWorkGroupSize, New);
819 }
820
821 if (const auto *AMDGPUFlatWorkGroupSize =
822 dyn_cast<AMDGPUWavesPerEUAttr>(TmplAttr)) {
824 *AMDGPUFlatWorkGroupSize, New);
825 }
826
827 if (const auto *AMDGPUMaxNumWorkGroups =
828 dyn_cast<AMDGPUMaxNumWorkGroupsAttr>(TmplAttr)) {
830 *this, TemplateArgs, *AMDGPUMaxNumWorkGroups, New);
831 }
832
833 if (const auto *ParamAttr = dyn_cast<HLSLParamModifierAttr>(TmplAttr)) {
834 instantiateDependentHLSLParamModifierAttr(*this, TemplateArgs, ParamAttr,
835 New);
836 continue;
837 }
838
839 // Existing DLL attribute on the instantiation takes precedence.
840 if (TmplAttr->getKind() == attr::DLLExport ||
841 TmplAttr->getKind() == attr::DLLImport) {
842 if (New->hasAttr<DLLExportAttr>() || New->hasAttr<DLLImportAttr>()) {
843 continue;
844 }
845 }
846
847 if (const auto *ABIAttr = dyn_cast<ParameterABIAttr>(TmplAttr)) {
848 Swift().AddParameterABIAttr(New, *ABIAttr, ABIAttr->getABI());
849 continue;
850 }
851
852 if (isa<NSConsumedAttr>(TmplAttr) || isa<OSConsumedAttr>(TmplAttr) ||
853 isa<CFConsumedAttr>(TmplAttr)) {
854 ObjC().AddXConsumedAttr(New, *TmplAttr,
856 /*template instantiation=*/true);
857 continue;
858 }
859
860 if (auto *A = dyn_cast<PointerAttr>(TmplAttr)) {
861 if (!New->hasAttr<PointerAttr>())
862 New->addAttr(A->clone(Context));
863 continue;
864 }
865
866 if (auto *A = dyn_cast<OwnerAttr>(TmplAttr)) {
867 if (!New->hasAttr<OwnerAttr>())
868 New->addAttr(A->clone(Context));
869 continue;
870 }
871
872 if (auto *A = dyn_cast<SYCLKernelAttr>(TmplAttr)) {
873 instantiateDependentSYCLKernelAttr(*this, TemplateArgs, *A, New);
874 continue;
875 }
876
877 if (auto *A = dyn_cast<CUDAGridConstantAttr>(TmplAttr)) {
878 if (!New->hasAttr<CUDAGridConstantAttr>())
879 New->addAttr(A->clone(Context));
880 continue;
881 }
882
883 assert(!TmplAttr->isPackExpansion());
884 if (TmplAttr->isLateParsed() && LateAttrs) {
885 // Late parsed attributes must be instantiated and attached after the
886 // enclosing class has been instantiated. See Sema::InstantiateClass.
887 LocalInstantiationScope *Saved = nullptr;
889 Saved = CurrentInstantiationScope->cloneScopes(OuterMostScope);
890 LateAttrs->push_back(LateInstantiatedAttribute(TmplAttr, Saved, New));
891 } else {
892 // Allow 'this' within late-parsed attributes.
893 auto *ND = cast<NamedDecl>(New);
894 auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext());
895 CXXThisScopeRAII ThisScope(*this, ThisContext, Qualifiers(),
896 ND->isCXXInstanceMember());
897
899 *this, TemplateArgs);
900 if (NewAttr && isRelevantAttr(*this, New, TmplAttr))
901 New->addAttr(NewAttr);
902 }
903 }
904}
905
907 for (const auto *Attr : Pattern->attrs()) {
908 if (auto *A = dyn_cast<StrictFPAttr>(Attr)) {
909 if (!Inst->hasAttr<StrictFPAttr>())
910 Inst->addAttr(A->clone(getASTContext()));
911 continue;
912 }
913 }
914}
915
918 Ctor->isDefaultConstructor());
919 unsigned NumParams = Ctor->getNumParams();
920 if (NumParams == 0)
921 return;
922 DLLExportAttr *Attr = Ctor->getAttr<DLLExportAttr>();
923 if (!Attr)
924 return;
925 for (unsigned I = 0; I != NumParams; ++I) {
927 Ctor->getParamDecl(I));
929 }
930}
931
932/// Get the previous declaration of a declaration for the purposes of template
933/// instantiation. If this finds a previous declaration, then the previous
934/// declaration of the instantiation of D should be an instantiation of the
935/// result of this function.
936template<typename DeclT>
937static DeclT *getPreviousDeclForInstantiation(DeclT *D) {
938 DeclT *Result = D->getPreviousDecl();
939
940 // If the declaration is within a class, and the previous declaration was
941 // merged from a different definition of that class, then we don't have a
942 // previous declaration for the purpose of template instantiation.
943 if (Result && isa<CXXRecordDecl>(D->getDeclContext()) &&
944 D->getLexicalDeclContext() != Result->getLexicalDeclContext())
945 return nullptr;
946
947 return Result;
948}
949
950Decl *
951TemplateDeclInstantiator::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
952 llvm_unreachable("Translation units cannot be instantiated");
953}
954
955Decl *TemplateDeclInstantiator::VisitHLSLBufferDecl(HLSLBufferDecl *Decl) {
956 llvm_unreachable("HLSL buffer declarations cannot be instantiated");
957}
958
959Decl *
960TemplateDeclInstantiator::VisitPragmaCommentDecl(PragmaCommentDecl *D) {
961 llvm_unreachable("pragma comment cannot be instantiated");
962}
963
964Decl *TemplateDeclInstantiator::VisitPragmaDetectMismatchDecl(
966 llvm_unreachable("pragma comment cannot be instantiated");
967}
968
969Decl *
970TemplateDeclInstantiator::VisitExternCContextDecl(ExternCContextDecl *D) {
971 llvm_unreachable("extern \"C\" context cannot be instantiated");
972}
973
974Decl *TemplateDeclInstantiator::VisitMSGuidDecl(MSGuidDecl *D) {
975 llvm_unreachable("GUID declaration cannot be instantiated");
976}
977
978Decl *TemplateDeclInstantiator::VisitUnnamedGlobalConstantDecl(
980 llvm_unreachable("UnnamedGlobalConstantDecl cannot be instantiated");
981}
982
983Decl *TemplateDeclInstantiator::VisitTemplateParamObjectDecl(
985 llvm_unreachable("template parameter objects cannot be instantiated");
986}
987
988Decl *
989TemplateDeclInstantiator::VisitLabelDecl(LabelDecl *D) {
990 LabelDecl *Inst = LabelDecl::Create(SemaRef.Context, Owner, D->getLocation(),
991 D->getIdentifier());
992 SemaRef.InstantiateAttrs(TemplateArgs, D, Inst, LateAttrs, StartingScope);
993 Owner->addDecl(Inst);
994 return Inst;
995}
996
997Decl *
998TemplateDeclInstantiator::VisitNamespaceDecl(NamespaceDecl *D) {
999 llvm_unreachable("Namespaces cannot be instantiated");
1000}
1001
1002Decl *
1003TemplateDeclInstantiator::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
1004 NamespaceAliasDecl *Inst
1005 = NamespaceAliasDecl::Create(SemaRef.Context, Owner,
1006 D->getNamespaceLoc(),
1007 D->getAliasLoc(),
1008 D->getIdentifier(),
1009 D->getQualifierLoc(),
1010 D->getTargetNameLoc(),
1011 D->getNamespace());
1012 Owner->addDecl(Inst);
1013 return Inst;
1014}
1015
1017 bool IsTypeAlias) {
1018 bool Invalid = false;
1019 TypeSourceInfo *DI = D->getTypeSourceInfo();
1022 DI = SemaRef.SubstType(DI, TemplateArgs,
1023 D->getLocation(), D->getDeclName());
1024 if (!DI) {
1025 Invalid = true;
1026 DI = SemaRef.Context.getTrivialTypeSourceInfo(SemaRef.Context.IntTy);
1027 }
1028 } else {
1030 }
1031
1032 // HACK: 2012-10-23 g++ has a bug where it gets the value kind of ?: wrong.
1033 // libstdc++ relies upon this bug in its implementation of common_type. If we
1034 // happen to be processing that implementation, fake up the g++ ?:
1035 // semantics. See LWG issue 2141 for more information on the bug. The bugs
1036 // are fixed in g++ and libstdc++ 4.9.0 (2014-04-22).
1037 const DecltypeType *DT = DI->getType()->getAs<DecltypeType>();
1038 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D->getDeclContext());
1039 if (DT && RD && isa<ConditionalOperator>(DT->getUnderlyingExpr()) &&
1040 DT->isReferenceType() &&
1041 RD->getEnclosingNamespaceContext() == SemaRef.getStdNamespace() &&
1042 RD->getIdentifier() && RD->getIdentifier()->isStr("common_type") &&
1043 D->getIdentifier() && D->getIdentifier()->isStr("type") &&
1045 // Fold it to the (non-reference) type which g++ would have produced.
1046 DI = SemaRef.Context.getTrivialTypeSourceInfo(
1048
1049 // Create the new typedef
1050 TypedefNameDecl *Typedef;
1051 if (IsTypeAlias)
1052 Typedef = TypeAliasDecl::Create(SemaRef.Context, Owner, D->getBeginLoc(),
1053 D->getLocation(), D->getIdentifier(), DI);
1054 else
1055 Typedef = TypedefDecl::Create(SemaRef.Context, Owner, D->getBeginLoc(),
1056 D->getLocation(), D->getIdentifier(), DI);
1057 if (Invalid)
1058 Typedef->setInvalidDecl();
1059
1060 // If the old typedef was the name for linkage purposes of an anonymous
1061 // tag decl, re-establish that relationship for the new typedef.
1062 if (const TagType *oldTagType = D->getUnderlyingType()->getAs<TagType>()) {
1063 TagDecl *oldTag = oldTagType->getDecl();
1064 if (oldTag->getTypedefNameForAnonDecl() == D && !Invalid) {
1065 TagDecl *newTag = DI->getType()->castAs<TagType>()->getDecl();
1066 assert(!newTag->hasNameForLinkage());
1067 newTag->setTypedefNameForAnonDecl(Typedef);
1068 }
1069 }
1070
1072 NamedDecl *InstPrev = SemaRef.FindInstantiatedDecl(D->getLocation(), Prev,
1073 TemplateArgs);
1074 if (!InstPrev)
1075 return nullptr;
1076
1077 TypedefNameDecl *InstPrevTypedef = cast<TypedefNameDecl>(InstPrev);
1078
1079 // If the typedef types are not identical, reject them.
1080 SemaRef.isIncompatibleTypedef(InstPrevTypedef, Typedef);
1081
1082 Typedef->setPreviousDecl(InstPrevTypedef);
1083 }
1084
1085 SemaRef.InstantiateAttrs(TemplateArgs, D, Typedef);
1086
1087 if (D->getUnderlyingType()->getAs<DependentNameType>())
1088 SemaRef.inferGslPointerAttribute(Typedef);
1089
1090 Typedef->setAccess(D->getAccess());
1091 Typedef->setReferenced(D->isReferenced());
1092
1093 return Typedef;
1094}
1095
1096Decl *TemplateDeclInstantiator::VisitTypedefDecl(TypedefDecl *D) {
1097 Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/false);
1098 if (Typedef)
1099 Owner->addDecl(Typedef);
1100 return Typedef;
1101}
1102
1103Decl *TemplateDeclInstantiator::VisitTypeAliasDecl(TypeAliasDecl *D) {
1104 Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/true);
1105 if (Typedef)
1106 Owner->addDecl(Typedef);
1107 return Typedef;
1108}
1109
1112 // Create a local instantiation scope for this type alias template, which
1113 // will contain the instantiations of the template parameters.
1115
1116 TemplateParameterList *TempParams = D->getTemplateParameters();
1117 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1118 if (!InstParams)
1119 return nullptr;
1120
1121 TypeAliasDecl *Pattern = D->getTemplatedDecl();
1122 Sema::InstantiatingTemplate InstTemplate(
1123 SemaRef, D->getBeginLoc(), D,
1124 D->getTemplateDepth() >= TemplateArgs.getNumLevels()
1126 : (TemplateArgs.begin() + TemplateArgs.getNumLevels() - 1 -
1128 ->Args);
1129 if (InstTemplate.isInvalid())
1130 return nullptr;
1131
1132 TypeAliasTemplateDecl *PrevAliasTemplate = nullptr;
1133 if (getPreviousDeclForInstantiation<TypedefNameDecl>(Pattern)) {
1135 if (!Found.empty()) {
1136 PrevAliasTemplate = dyn_cast<TypeAliasTemplateDecl>(Found.front());
1137 }
1138 }
1139
1140 TypeAliasDecl *AliasInst = cast_or_null<TypeAliasDecl>(
1141 InstantiateTypedefNameDecl(Pattern, /*IsTypeAlias=*/true));
1142 if (!AliasInst)
1143 return nullptr;
1144
1147 D->getDeclName(), InstParams, AliasInst);
1148 AliasInst->setDescribedAliasTemplate(Inst);
1149 if (PrevAliasTemplate)
1150 Inst->setPreviousDecl(PrevAliasTemplate);
1151
1152 Inst->setAccess(D->getAccess());
1153
1154 if (!PrevAliasTemplate)
1156
1157 return Inst;
1158}
1159
1160Decl *
1161TemplateDeclInstantiator::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) {
1163 if (Inst)
1164 Owner->addDecl(Inst);
1165
1166 return Inst;
1167}
1168
1169Decl *TemplateDeclInstantiator::VisitBindingDecl(BindingDecl *D) {
1170 auto *NewBD = BindingDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1171 D->getIdentifier(), D->getType());
1172 NewBD->setReferenced(D->isReferenced());
1174
1175 return NewBD;
1176}
1177
1178Decl *TemplateDeclInstantiator::VisitDecompositionDecl(DecompositionDecl *D) {
1179 // Transform the bindings first.
1180 // The transformed DD will have all of the concrete BindingDecls.
1182 ResolvedUnexpandedPackExpr *OldResolvedPack = nullptr;
1183 for (auto *OldBD : D->bindings()) {
1184 Expr *BindingExpr = OldBD->getBinding();
1185 if (auto *RP =
1186 dyn_cast_if_present<ResolvedUnexpandedPackExpr>(BindingExpr)) {
1187 assert(!OldResolvedPack && "no more than one pack is allowed");
1188 OldResolvedPack = RP;
1189 }
1190 NewBindings.push_back(cast<BindingDecl>(VisitBindingDecl(OldBD)));
1191 }
1192 ArrayRef<BindingDecl*> NewBindingArray = NewBindings;
1193
1194 auto *NewDD = cast_if_present<DecompositionDecl>(
1195 VisitVarDecl(D, /*InstantiatingVarTemplate=*/false, &NewBindingArray));
1196
1197 if (!NewDD || NewDD->isInvalidDecl())
1198 for (auto *NewBD : NewBindings)
1199 NewBD->setInvalidDecl();
1200
1201 if (OldResolvedPack) {
1202 // Mark the holding vars (if any) in the pack as instantiated since
1203 // they are created implicitly.
1204 auto Bindings = NewDD->bindings();
1205 auto BPack = llvm::find_if(
1206 Bindings, [](BindingDecl *D) -> bool { return D->isParameterPack(); });
1207 auto *NewResolvedPack =
1208 cast<ResolvedUnexpandedPackExpr>((*BPack)->getBinding());
1209 auto OldExprs = OldResolvedPack->getExprs();
1210 auto NewExprs = NewResolvedPack->getExprs();
1211 assert(OldExprs.size() == NewExprs.size());
1212 for (unsigned I = 0; I < OldResolvedPack->getNumExprs(); I++) {
1213 DeclRefExpr *OldDRE = cast<DeclRefExpr>(OldExprs[I]);
1214 BindingDecl *OldNestedBD = cast<BindingDecl>(OldDRE->getDecl());
1215 DeclRefExpr *NewDRE = cast<DeclRefExpr>(NewExprs[I]);
1216 BindingDecl *NewNestedBD = cast<BindingDecl>(NewDRE->getDecl());
1217 SemaRef.CurrentInstantiationScope->InstantiatedLocal(OldNestedBD,
1218 NewNestedBD);
1219 }
1220 }
1221
1222 return NewDD;
1223}
1224
1226 return VisitVarDecl(D, /*InstantiatingVarTemplate=*/false);
1227}
1228
1230 bool InstantiatingVarTemplate,
1232
1233 // Do substitution on the type of the declaration
1234 TypeSourceInfo *DI = SemaRef.SubstType(
1235 D->getTypeSourceInfo(), TemplateArgs, D->getTypeSpecStartLoc(),
1236 D->getDeclName(), /*AllowDeducedTST*/true);
1237 if (!DI)
1238 return nullptr;
1239
1240 if (DI->getType()->isFunctionType()) {
1241 SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function)
1242 << D->isStaticDataMember() << DI->getType();
1243 return nullptr;
1244 }
1245
1246 DeclContext *DC = Owner;
1247 if (D->isLocalExternDecl())
1249
1250 // Build the instantiated declaration.
1251 VarDecl *Var;
1252 if (Bindings)
1253 Var = DecompositionDecl::Create(SemaRef.Context, DC, D->getInnerLocStart(),
1254 D->getLocation(), DI->getType(), DI,
1255 D->getStorageClass(), *Bindings);
1256 else
1257 Var = VarDecl::Create(SemaRef.Context, DC, D->getInnerLocStart(),
1258 D->getLocation(), D->getIdentifier(), DI->getType(),
1259 DI, D->getStorageClass());
1260
1261 // In ARC, infer 'retaining' for variables of retainable type.
1262 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
1263 SemaRef.ObjC().inferObjCARCLifetime(Var))
1264 Var->setInvalidDecl();
1265
1266 if (SemaRef.getLangOpts().OpenCL)
1267 SemaRef.deduceOpenCLAddressSpace(Var);
1268
1269 // Substitute the nested name specifier, if any.
1270 if (SubstQualifier(D, Var))
1271 return nullptr;
1272
1273 SemaRef.BuildVariableInstantiation(Var, D, TemplateArgs, LateAttrs, Owner,
1274 StartingScope, InstantiatingVarTemplate);
1275 if (D->isNRVOVariable() && !Var->isInvalidDecl()) {
1276 QualType RT;
1277 if (auto *F = dyn_cast<FunctionDecl>(DC))
1278 RT = F->getReturnType();
1279 else if (isa<BlockDecl>(DC))
1280 RT = cast<FunctionType>(SemaRef.getCurBlock()->FunctionType)
1281 ->getReturnType();
1282 else
1283 llvm_unreachable("Unknown context type");
1284
1285 // This is the last chance we have of checking copy elision eligibility
1286 // for functions in dependent contexts. The sema actions for building
1287 // the return statement during template instantiation will have no effect
1288 // regarding copy elision, since NRVO propagation runs on the scope exit
1289 // actions, and these are not run on instantiation.
1290 // This might run through some VarDecls which were returned from non-taken
1291 // 'if constexpr' branches, and these will end up being constructed on the
1292 // return slot even if they will never be returned, as a sort of accidental
1293 // 'optimization'. Notably, functions with 'auto' return types won't have it
1294 // deduced by this point. Coupled with the limitation described
1295 // previously, this makes it very hard to support copy elision for these.
1296 Sema::NamedReturnInfo Info = SemaRef.getNamedReturnInfo(Var);
1297 bool NRVO = SemaRef.getCopyElisionCandidate(Info, RT) != nullptr;
1298 Var->setNRVOVariable(NRVO);
1299 }
1300
1301 Var->setImplicit(D->isImplicit());
1302
1303 if (Var->isStaticLocal())
1304 SemaRef.CheckStaticLocalForDllExport(Var);
1305
1306 if (Var->getTLSKind())
1308
1309 return Var;
1310}
1311
1312Decl *TemplateDeclInstantiator::VisitAccessSpecDecl(AccessSpecDecl *D) {
1313 AccessSpecDecl* AD
1314 = AccessSpecDecl::Create(SemaRef.Context, D->getAccess(), Owner,
1315 D->getAccessSpecifierLoc(), D->getColonLoc());
1316 Owner->addHiddenDecl(AD);
1317 return AD;
1318}
1319
1320Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) {
1321 bool Invalid = false;
1322 TypeSourceInfo *DI = D->getTypeSourceInfo();
1325 DI = SemaRef.SubstType(DI, TemplateArgs,
1326 D->getLocation(), D->getDeclName());
1327 if (!DI) {
1328 DI = D->getTypeSourceInfo();
1329 Invalid = true;
1330 } else if (DI->getType()->isFunctionType()) {
1331 // C++ [temp.arg.type]p3:
1332 // If a declaration acquires a function type through a type
1333 // dependent on a template-parameter and this causes a
1334 // declaration that does not use the syntactic form of a
1335 // function declarator to have function type, the program is
1336 // ill-formed.
1337 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
1338 << DI->getType();
1339 Invalid = true;
1340 }
1341 } else {
1343 }
1344
1345 Expr *BitWidth = D->getBitWidth();
1346 if (Invalid)
1347 BitWidth = nullptr;
1348 else if (BitWidth) {
1349 // The bit-width expression is a constant expression.
1352
1353 ExprResult InstantiatedBitWidth
1354 = SemaRef.SubstExpr(BitWidth, TemplateArgs);
1355 if (InstantiatedBitWidth.isInvalid()) {
1356 Invalid = true;
1357 BitWidth = nullptr;
1358 } else
1359 BitWidth = InstantiatedBitWidth.getAs<Expr>();
1360 }
1361
1362 FieldDecl *Field = SemaRef.CheckFieldDecl(D->getDeclName(),
1363 DI->getType(), DI,
1364 cast<RecordDecl>(Owner),
1365 D->getLocation(),
1366 D->isMutable(),
1367 BitWidth,
1368 D->getInClassInitStyle(),
1369 D->getInnerLocStart(),
1370 D->getAccess(),
1371 nullptr);
1372 if (!Field) {
1373 cast<Decl>(Owner)->setInvalidDecl();
1374 return nullptr;
1375 }
1376
1377 SemaRef.InstantiateAttrs(TemplateArgs, D, Field, LateAttrs, StartingScope);
1378
1379 if (Field->hasAttrs())
1380 SemaRef.CheckAlignasUnderalignment(Field);
1381
1382 if (Invalid)
1383 Field->setInvalidDecl();
1384
1385 if (!Field->getDeclName() || Field->isPlaceholderVar(SemaRef.getLangOpts())) {
1386 // Keep track of where this decl came from.
1388 }
1389 if (CXXRecordDecl *Parent= dyn_cast<CXXRecordDecl>(Field->getDeclContext())) {
1390 if (Parent->isAnonymousStructOrUnion() &&
1391 Parent->getRedeclContext()->isFunctionOrMethod())
1393 }
1394
1395 Field->setImplicit(D->isImplicit());
1396 Field->setAccess(D->getAccess());
1397 Owner->addDecl(Field);
1398
1399 return Field;
1400}
1401
1402Decl *TemplateDeclInstantiator::VisitMSPropertyDecl(MSPropertyDecl *D) {
1403 bool Invalid = false;
1404 TypeSourceInfo *DI = D->getTypeSourceInfo();
1405
1406 if (DI->getType()->isVariablyModifiedType()) {
1407 SemaRef.Diag(D->getLocation(), diag::err_property_is_variably_modified)
1408 << D;
1409 Invalid = true;
1410 } else if (DI->getType()->isInstantiationDependentType()) {
1411 DI = SemaRef.SubstType(DI, TemplateArgs,
1412 D->getLocation(), D->getDeclName());
1413 if (!DI) {
1414 DI = D->getTypeSourceInfo();
1415 Invalid = true;
1416 } else if (DI->getType()->isFunctionType()) {
1417 // C++ [temp.arg.type]p3:
1418 // If a declaration acquires a function type through a type
1419 // dependent on a template-parameter and this causes a
1420 // declaration that does not use the syntactic form of a
1421 // function declarator to have function type, the program is
1422 // ill-formed.
1423 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
1424 << DI->getType();
1425 Invalid = true;
1426 }
1427 } else {
1429 }
1430
1432 SemaRef.Context, Owner, D->getLocation(), D->getDeclName(), DI->getType(),
1433 DI, D->getBeginLoc(), D->getGetterId(), D->getSetterId());
1434
1435 SemaRef.InstantiateAttrs(TemplateArgs, D, Property, LateAttrs,
1436 StartingScope);
1437
1438 if (Invalid)
1439 Property->setInvalidDecl();
1440
1441 Property->setAccess(D->getAccess());
1442 Owner->addDecl(Property);
1443
1444 return Property;
1445}
1446
1447Decl *TemplateDeclInstantiator::VisitIndirectFieldDecl(IndirectFieldDecl *D) {
1448 NamedDecl **NamedChain =
1449 new (SemaRef.Context)NamedDecl*[D->getChainingSize()];
1450
1451 int i = 0;
1452 for (auto *PI : D->chain()) {
1453 NamedDecl *Next = SemaRef.FindInstantiatedDecl(D->getLocation(), PI,
1454 TemplateArgs);
1455 if (!Next)
1456 return nullptr;
1457
1458 NamedChain[i++] = Next;
1459 }
1460
1461 QualType T = cast<FieldDecl>(NamedChain[i-1])->getType();
1463 SemaRef.Context, Owner, D->getLocation(), D->getIdentifier(), T,
1464 {NamedChain, D->getChainingSize()});
1465
1466 for (const auto *Attr : D->attrs())
1467 IndirectField->addAttr(Attr->clone(SemaRef.Context));
1468
1469 IndirectField->setImplicit(D->isImplicit());
1470 IndirectField->setAccess(D->getAccess());
1471 Owner->addDecl(IndirectField);
1472 return IndirectField;
1473}
1474
1475Decl *TemplateDeclInstantiator::VisitFriendDecl(FriendDecl *D) {
1476 // Handle friend type expressions by simply substituting template
1477 // parameters into the pattern type and checking the result.
1478 if (TypeSourceInfo *Ty = D->getFriendType()) {
1479 TypeSourceInfo *InstTy;
1480 // If this is an unsupported friend, don't bother substituting template
1481 // arguments into it. The actual type referred to won't be used by any
1482 // parts of Clang, and may not be valid for instantiating. Just use the
1483 // same info for the instantiated friend.
1484 if (D->isUnsupportedFriend()) {
1485 InstTy = Ty;
1486 } else {
1487 if (D->isPackExpansion()) {
1489 SemaRef.collectUnexpandedParameterPacks(Ty->getTypeLoc(), Unexpanded);
1490 assert(!Unexpanded.empty() && "Pack expansion without packs");
1491
1492 bool ShouldExpand = true;
1493 bool RetainExpansion = false;
1494 std::optional<unsigned> NumExpansions;
1496 D->getEllipsisLoc(), D->getSourceRange(), Unexpanded,
1497 TemplateArgs, ShouldExpand, RetainExpansion, NumExpansions))
1498 return nullptr;
1499
1500 assert(!RetainExpansion &&
1501 "should never retain an expansion for a variadic friend decl");
1502
1503 if (ShouldExpand) {
1505 for (unsigned I = 0; I != *NumExpansions; I++) {
1506 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
1507 TypeSourceInfo *TSI = SemaRef.SubstType(
1508 Ty, TemplateArgs, D->getEllipsisLoc(), DeclarationName());
1509 if (!TSI)
1510 return nullptr;
1511
1512 auto FD =
1513 FriendDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1514 TSI, D->getFriendLoc());
1515
1516 FD->setAccess(AS_public);
1517 Owner->addDecl(FD);
1518 Decls.push_back(FD);
1519 }
1520
1521 // Just drop this node; we have no use for it anymore.
1522 return nullptr;
1523 }
1524 }
1525
1526 InstTy = SemaRef.SubstType(Ty, TemplateArgs, D->getLocation(),
1527 DeclarationName());
1528 }
1529 if (!InstTy)
1530 return nullptr;
1531
1533 SemaRef.Context, Owner, D->getLocation(), InstTy, D->getFriendLoc());
1534 FD->setAccess(AS_public);
1535 FD->setUnsupportedFriend(D->isUnsupportedFriend());
1536 Owner->addDecl(FD);
1537 return FD;
1538 }
1539
1540 NamedDecl *ND = D->getFriendDecl();
1541 assert(ND && "friend decl must be a decl or a type!");
1542
1543 // All of the Visit implementations for the various potential friend
1544 // declarations have to be carefully written to work for friend
1545 // objects, with the most important detail being that the target
1546 // decl should almost certainly not be placed in Owner.
1547 Decl *NewND = Visit(ND);
1548 if (!NewND) return nullptr;
1549
1550 FriendDecl *FD =
1551 FriendDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1552 cast<NamedDecl>(NewND), D->getFriendLoc());
1553 FD->setAccess(AS_public);
1554 FD->setUnsupportedFriend(D->isUnsupportedFriend());
1555 Owner->addDecl(FD);
1556 return FD;
1557}
1558
1559Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) {
1560 Expr *AssertExpr = D->getAssertExpr();
1561
1562 // The expression in a static assertion is a constant expression.
1565
1566 ExprResult InstantiatedAssertExpr
1567 = SemaRef.SubstExpr(AssertExpr, TemplateArgs);
1568 if (InstantiatedAssertExpr.isInvalid())
1569 return nullptr;
1570
1571 ExprResult InstantiatedMessageExpr =
1572 SemaRef.SubstExpr(D->getMessage(), TemplateArgs);
1573 if (InstantiatedMessageExpr.isInvalid())
1574 return nullptr;
1575
1576 return SemaRef.BuildStaticAssertDeclaration(
1577 D->getLocation(), InstantiatedAssertExpr.get(),
1578 InstantiatedMessageExpr.get(), D->getRParenLoc(), D->isFailed());
1579}
1580
1581Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) {
1582 EnumDecl *PrevDecl = nullptr;
1583 if (EnumDecl *PatternPrev = getPreviousDeclForInstantiation(D)) {
1584 NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
1585 PatternPrev,
1586 TemplateArgs);
1587 if (!Prev) return nullptr;
1588 PrevDecl = cast<EnumDecl>(Prev);
1589 }
1590
1591 EnumDecl *Enum =
1592 EnumDecl::Create(SemaRef.Context, Owner, D->getBeginLoc(),
1593 D->getLocation(), D->getIdentifier(), PrevDecl,
1594 D->isScoped(), D->isScopedUsingClassTag(), D->isFixed());
1595 if (D->isFixed()) {
1596 if (TypeSourceInfo *TI = D->getIntegerTypeSourceInfo()) {
1597 // If we have type source information for the underlying type, it means it
1598 // has been explicitly set by the user. Perform substitution on it before
1599 // moving on.
1600 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
1601 TypeSourceInfo *NewTI = SemaRef.SubstType(TI, TemplateArgs, UnderlyingLoc,
1602 DeclarationName());
1603 if (!NewTI || SemaRef.CheckEnumUnderlyingType(NewTI))
1604 Enum->setIntegerType(SemaRef.Context.IntTy);
1605 else
1606 Enum->setIntegerTypeSourceInfo(NewTI);
1607
1608 // C++23 [conv.prom]p4
1609 // if integral promotion can be applied to its underlying type, a prvalue
1610 // of an unscoped enumeration type whose underlying type is fixed can also
1611 // be converted to a prvalue of the promoted underlying type.
1612 //
1613 // FIXME: that logic is already implemented in ActOnEnumBody, factor out
1614 // into (Re)BuildEnumBody.
1615 QualType UnderlyingType = Enum->getIntegerType();
1616 Enum->setPromotionType(
1617 SemaRef.Context.isPromotableIntegerType(UnderlyingType)
1618 ? SemaRef.Context.getPromotedIntegerType(UnderlyingType)
1619 : UnderlyingType);
1620 } else {
1621 assert(!D->getIntegerType()->isDependentType()
1622 && "Dependent type without type source info");
1623 Enum->setIntegerType(D->getIntegerType());
1624 }
1625 }
1626
1627 SemaRef.InstantiateAttrs(TemplateArgs, D, Enum);
1628
1629 Enum->setInstantiationOfMemberEnum(D, TSK_ImplicitInstantiation);
1630 Enum->setAccess(D->getAccess());
1631 // Forward the mangling number from the template to the instantiated decl.
1633 // See if the old tag was defined along with a declarator.
1634 // If it did, mark the new tag as being associated with that declarator.
1637 // See if the old tag was defined along with a typedef.
1638 // If it did, mark the new tag as being associated with that typedef.
1641 if (SubstQualifier(D, Enum)) return nullptr;
1642 Owner->addDecl(Enum);
1643
1644 EnumDecl *Def = D->getDefinition();
1645 if (Def && Def != D) {
1646 // If this is an out-of-line definition of an enum member template, check
1647 // that the underlying types match in the instantiation of both
1648 // declarations.
1649 if (TypeSourceInfo *TI = Def->getIntegerTypeSourceInfo()) {
1650 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
1651 QualType DefnUnderlying =
1652 SemaRef.SubstType(TI->getType(), TemplateArgs,
1653 UnderlyingLoc, DeclarationName());
1654 SemaRef.CheckEnumRedeclaration(Def->getLocation(), Def->isScoped(),
1655 DefnUnderlying, /*IsFixed=*/true, Enum);
1656 }
1657 }
1658
1659 // C++11 [temp.inst]p1: The implicit instantiation of a class template
1660 // specialization causes the implicit instantiation of the declarations, but
1661 // not the definitions of scoped member enumerations.
1662 //
1663 // DR1484 clarifies that enumeration definitions inside a template
1664 // declaration aren't considered entities that can be separately instantiated
1665 // from the rest of the entity they are declared inside.
1666 if (isDeclWithinFunction(D) ? D == Def : Def && !Enum->isScoped()) {
1667 // Prevent redundant instantiation of the enumerator-definition if the
1668 // definition has already been instantiated due to a prior
1669 // opaque-enum-declaration.
1670 if (PrevDecl == nullptr) {
1673 }
1674 }
1675
1676 return Enum;
1677}
1678
1680 EnumDecl *Enum, EnumDecl *Pattern) {
1681 Enum->startDefinition();
1682
1683 // Update the location to refer to the definition.
1684 Enum->setLocation(Pattern->getLocation());
1685
1686 SmallVector<Decl*, 4> Enumerators;
1687
1688 EnumConstantDecl *LastEnumConst = nullptr;
1689 for (auto *EC : Pattern->enumerators()) {
1690 // The specified value for the enumerator.
1691 ExprResult Value((Expr *)nullptr);
1692 if (Expr *UninstValue = EC->getInitExpr()) {
1693 // The enumerator's value expression is a constant expression.
1696
1697 Value = SemaRef.SubstExpr(UninstValue, TemplateArgs);
1698 }
1699
1700 // Drop the initial value and continue.
1701 bool isInvalid = false;
1702 if (Value.isInvalid()) {
1703 Value = nullptr;
1704 isInvalid = true;
1705 }
1706
1707 EnumConstantDecl *EnumConst
1708 = SemaRef.CheckEnumConstant(Enum, LastEnumConst,
1709 EC->getLocation(), EC->getIdentifier(),
1710 Value.get());
1711
1712 if (isInvalid) {
1713 if (EnumConst)
1714 EnumConst->setInvalidDecl();
1715 Enum->setInvalidDecl();
1716 }
1717
1718 if (EnumConst) {
1719 SemaRef.InstantiateAttrs(TemplateArgs, EC, EnumConst);
1720
1721 EnumConst->setAccess(Enum->getAccess());
1722 Enum->addDecl(EnumConst);
1723 Enumerators.push_back(EnumConst);
1724 LastEnumConst = EnumConst;
1725
1726 if (Pattern->getDeclContext()->isFunctionOrMethod() &&
1727 !Enum->isScoped()) {
1728 // If the enumeration is within a function or method, record the enum
1729 // constant as a local.
1730 SemaRef.CurrentInstantiationScope->InstantiatedLocal(EC, EnumConst);
1731 }
1732 }
1733 }
1734
1735 SemaRef.ActOnEnumBody(Enum->getLocation(), Enum->getBraceRange(), Enum,
1736 Enumerators, nullptr, ParsedAttributesView());
1737}
1738
1739Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) {
1740 llvm_unreachable("EnumConstantDecls can only occur within EnumDecls.");
1741}
1742
1743Decl *
1744TemplateDeclInstantiator::VisitBuiltinTemplateDecl(BuiltinTemplateDecl *D) {
1745 llvm_unreachable("BuiltinTemplateDecls cannot be instantiated.");
1746}
1747
1748Decl *TemplateDeclInstantiator::VisitClassTemplateDecl(ClassTemplateDecl *D) {
1749 bool isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
1750
1751 // Create a local instantiation scope for this class template, which
1752 // will contain the instantiations of the template parameters.
1754 TemplateParameterList *TempParams = D->getTemplateParameters();
1755 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1756 if (!InstParams)
1757 return nullptr;
1758
1759 CXXRecordDecl *Pattern = D->getTemplatedDecl();
1760
1761 // Instantiate the qualifier. We have to do this first in case
1762 // we're a friend declaration, because if we are then we need to put
1763 // the new declaration in the appropriate context.
1764 NestedNameSpecifierLoc QualifierLoc = Pattern->getQualifierLoc();
1765 if (QualifierLoc) {
1766 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
1767 TemplateArgs);
1768 if (!QualifierLoc)
1769 return nullptr;
1770 }
1771
1772 CXXRecordDecl *PrevDecl = nullptr;
1773 ClassTemplateDecl *PrevClassTemplate = nullptr;
1774
1775 if (!isFriend && getPreviousDeclForInstantiation(Pattern)) {
1777 if (!Found.empty()) {
1778 PrevClassTemplate = dyn_cast<ClassTemplateDecl>(Found.front());
1779 if (PrevClassTemplate)
1780 PrevDecl = PrevClassTemplate->getTemplatedDecl();
1781 }
1782 }
1783
1784 // If this isn't a friend, then it's a member template, in which
1785 // case we just want to build the instantiation in the
1786 // specialization. If it is a friend, we want to build it in
1787 // the appropriate context.
1788 DeclContext *DC = Owner;
1789 if (isFriend) {
1790 if (QualifierLoc) {
1791 CXXScopeSpec SS;
1792 SS.Adopt(QualifierLoc);
1793 DC = SemaRef.computeDeclContext(SS);
1794 if (!DC) return nullptr;
1795 } else {
1796 DC = SemaRef.FindInstantiatedContext(Pattern->getLocation(),
1797 Pattern->getDeclContext(),
1798 TemplateArgs);
1799 }
1800
1801 // Look for a previous declaration of the template in the owning
1802 // context.
1803 LookupResult R(SemaRef, Pattern->getDeclName(), Pattern->getLocation(),
1806 SemaRef.LookupQualifiedName(R, DC);
1807
1808 if (R.isSingleResult()) {
1809 PrevClassTemplate = R.getAsSingle<ClassTemplateDecl>();
1810 if (PrevClassTemplate)
1811 PrevDecl = PrevClassTemplate->getTemplatedDecl();
1812 }
1813
1814 if (!PrevClassTemplate && QualifierLoc) {
1815 SemaRef.Diag(Pattern->getLocation(), diag::err_not_tag_in_scope)
1816 << llvm::to_underlying(D->getTemplatedDecl()->getTagKind())
1817 << Pattern->getDeclName() << DC << QualifierLoc.getSourceRange();
1818 return nullptr;
1819 }
1820 }
1821
1823 SemaRef.Context, Pattern->getTagKind(), DC, Pattern->getBeginLoc(),
1824 Pattern->getLocation(), Pattern->getIdentifier(), PrevDecl,
1825 /*DelayTypeCreation=*/true);
1826 if (QualifierLoc)
1827 RecordInst->setQualifierInfo(QualifierLoc);
1828
1829 SemaRef.InstantiateAttrsForDecl(TemplateArgs, Pattern, RecordInst, LateAttrs,
1830 StartingScope);
1831
1832 ClassTemplateDecl *Inst
1834 D->getIdentifier(), InstParams, RecordInst);
1835 RecordInst->setDescribedClassTemplate(Inst);
1836
1837 if (isFriend) {
1838 assert(!Owner->isDependentContext());
1839 Inst->setLexicalDeclContext(Owner);
1840 RecordInst->setLexicalDeclContext(Owner);
1841 Inst->setObjectOfFriendDecl();
1842
1843 if (PrevClassTemplate) {
1844 Inst->setCommonPtr(PrevClassTemplate->getCommonPtr());
1845 RecordInst->setTypeForDecl(
1846 PrevClassTemplate->getTemplatedDecl()->getTypeForDecl());
1847 const ClassTemplateDecl *MostRecentPrevCT =
1848 PrevClassTemplate->getMostRecentDecl();
1849 TemplateParameterList *PrevParams =
1850 MostRecentPrevCT->getTemplateParameters();
1851
1852 // Make sure the parameter lists match.
1853 if (!SemaRef.TemplateParameterListsAreEqual(
1854 RecordInst, InstParams, MostRecentPrevCT->getTemplatedDecl(),
1855 PrevParams, true, Sema::TPL_TemplateMatch))
1856 return nullptr;
1857
1858 // Do some additional validation, then merge default arguments
1859 // from the existing declarations.
1860 if (SemaRef.CheckTemplateParameterList(InstParams, PrevParams,
1862 return nullptr;
1863
1864 Inst->setAccess(PrevClassTemplate->getAccess());
1865 } else {
1866 Inst->setAccess(D->getAccess());
1867 }
1868
1869 Inst->setObjectOfFriendDecl();
1870 // TODO: do we want to track the instantiation progeny of this
1871 // friend target decl?
1872 } else {
1873 Inst->setAccess(D->getAccess());
1874 if (!PrevClassTemplate)
1876 }
1877
1878 Inst->setPreviousDecl(PrevClassTemplate);
1879
1880 // Trigger creation of the type for the instantiation.
1882 RecordInst, Inst->getInjectedClassNameSpecialization());
1883
1884 // Finish handling of friends.
1885 if (isFriend) {
1886 DC->makeDeclVisibleInContext(Inst);
1887 return Inst;
1888 }
1889
1890 if (D->isOutOfLine()) {
1893 }
1894
1895 Owner->addDecl(Inst);
1896
1897 if (!PrevClassTemplate) {
1898 // Queue up any out-of-line partial specializations of this member
1899 // class template; the client will force their instantiation once
1900 // the enclosing class has been instantiated.
1902 D->getPartialSpecializations(PartialSpecs);
1903 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
1904 if (PartialSpecs[I]->getFirstDecl()->isOutOfLine())
1905 OutOfLinePartialSpecs.push_back(std::make_pair(Inst, PartialSpecs[I]));
1906 }
1907
1908 return Inst;
1909}
1910
1911Decl *
1912TemplateDeclInstantiator::VisitClassTemplatePartialSpecializationDecl(
1914 ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
1915
1916 // Lookup the already-instantiated declaration in the instantiation
1917 // of the class template and return that.
1919 = Owner->lookup(ClassTemplate->getDeclName());
1920 if (Found.empty())
1921 return nullptr;
1922
1923 ClassTemplateDecl *InstClassTemplate
1924 = dyn_cast<ClassTemplateDecl>(Found.front());
1925 if (!InstClassTemplate)
1926 return nullptr;
1927
1929 = InstClassTemplate->findPartialSpecInstantiatedFromMember(D))
1930 return Result;
1931
1932 return InstantiateClassTemplatePartialSpecialization(InstClassTemplate, D);
1933}
1934
1935Decl *TemplateDeclInstantiator::VisitVarTemplateDecl(VarTemplateDecl *D) {
1936 assert(D->getTemplatedDecl()->isStaticDataMember() &&
1937 "Only static data member templates are allowed.");
1938
1939 // Create a local instantiation scope for this variable template, which
1940 // will contain the instantiations of the template parameters.
1942 TemplateParameterList *TempParams = D->getTemplateParameters();
1943 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1944 if (!InstParams)
1945 return nullptr;
1946
1947 VarDecl *Pattern = D->getTemplatedDecl();
1948 VarTemplateDecl *PrevVarTemplate = nullptr;
1949
1950 if (getPreviousDeclForInstantiation(Pattern)) {
1952 if (!Found.empty())
1953 PrevVarTemplate = dyn_cast<VarTemplateDecl>(Found.front());
1954 }
1955
1956 VarDecl *VarInst =
1957 cast_or_null<VarDecl>(VisitVarDecl(Pattern,
1958 /*InstantiatingVarTemplate=*/true));
1959 if (!VarInst) return nullptr;
1960
1961 DeclContext *DC = Owner;
1962
1964 SemaRef.Context, DC, D->getLocation(), D->getIdentifier(), InstParams,
1965 VarInst);
1966 VarInst->setDescribedVarTemplate(Inst);
1967 Inst->setPreviousDecl(PrevVarTemplate);
1968
1969 Inst->setAccess(D->getAccess());
1970 if (!PrevVarTemplate)
1972
1973 if (D->isOutOfLine()) {
1976 }
1977
1978 Owner->addDecl(Inst);
1979
1980 if (!PrevVarTemplate) {
1981 // Queue up any out-of-line partial specializations of this member
1982 // variable template; the client will force their instantiation once
1983 // the enclosing class has been instantiated.
1985 D->getPartialSpecializations(PartialSpecs);
1986 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
1987 if (PartialSpecs[I]->getFirstDecl()->isOutOfLine())
1988 OutOfLineVarPartialSpecs.push_back(
1989 std::make_pair(Inst, PartialSpecs[I]));
1990 }
1991
1992 return Inst;
1993}
1994
1995Decl *TemplateDeclInstantiator::VisitVarTemplatePartialSpecializationDecl(
1997 assert(D->isStaticDataMember() &&
1998 "Only static data member templates are allowed.");
1999
2000 VarTemplateDecl *VarTemplate = D->getSpecializedTemplate();
2001
2002 // Lookup the already-instantiated declaration and return that.
2003 DeclContext::lookup_result Found = Owner->lookup(VarTemplate->getDeclName());
2004 assert(!Found.empty() && "Instantiation found nothing?");
2005
2006 VarTemplateDecl *InstVarTemplate = dyn_cast<VarTemplateDecl>(Found.front());
2007 assert(InstVarTemplate && "Instantiation did not find a variable template?");
2008
2010 InstVarTemplate->findPartialSpecInstantiatedFromMember(D))
2011 return Result;
2012
2013 return InstantiateVarTemplatePartialSpecialization(InstVarTemplate, D);
2014}
2015
2016Decl *
2017TemplateDeclInstantiator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
2018 // Create a local instantiation scope for this function template, which
2019 // will contain the instantiations of the template parameters and then get
2020 // merged with the local instantiation scope for the function template
2021 // itself.
2024
2025 TemplateParameterList *TempParams = D->getTemplateParameters();
2026 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
2027 if (!InstParams)
2028 return nullptr;
2029
2030 FunctionDecl *Instantiated = nullptr;
2031 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(D->getTemplatedDecl()))
2032 Instantiated = cast_or_null<FunctionDecl>(VisitCXXMethodDecl(DMethod,
2033 InstParams));
2034 else
2035 Instantiated = cast_or_null<FunctionDecl>(VisitFunctionDecl(
2036 D->getTemplatedDecl(),
2037 InstParams));
2038
2039 if (!Instantiated)
2040 return nullptr;
2041
2042 // Link the instantiated function template declaration to the function
2043 // template from which it was instantiated.
2044 FunctionTemplateDecl *InstTemplate
2045 = Instantiated->getDescribedFunctionTemplate();
2046 InstTemplate->setAccess(D->getAccess());
2047 assert(InstTemplate &&
2048 "VisitFunctionDecl/CXXMethodDecl didn't create a template!");
2049
2050 bool isFriend = (InstTemplate->getFriendObjectKind() != Decl::FOK_None);
2051
2052 // Link the instantiation back to the pattern *unless* this is a
2053 // non-definition friend declaration.
2054 if (!InstTemplate->getInstantiatedFromMemberTemplate() &&
2055 !(isFriend && !D->getTemplatedDecl()->isThisDeclarationADefinition()))
2056 InstTemplate->setInstantiatedFromMemberTemplate(D);
2057
2058 // Make declarations visible in the appropriate context.
2059 if (!isFriend) {
2060 Owner->addDecl(InstTemplate);
2061 } else if (InstTemplate->getDeclContext()->isRecord() &&
2063 SemaRef.CheckFriendAccess(InstTemplate);
2064 }
2065
2066 return InstTemplate;
2067}
2068
2069Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) {
2070 CXXRecordDecl *PrevDecl = nullptr;
2071 if (CXXRecordDecl *PatternPrev = getPreviousDeclForInstantiation(D)) {
2072 NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
2073 PatternPrev,
2074 TemplateArgs);
2075 if (!Prev) return nullptr;
2076 PrevDecl = cast<CXXRecordDecl>(Prev);
2077 }
2078
2079 CXXRecordDecl *Record = nullptr;
2080 bool IsInjectedClassName = D->isInjectedClassName();
2081 if (D->isLambda())
2083 SemaRef.Context, Owner, D->getLambdaTypeInfo(), D->getLocation(),
2084 D->getLambdaDependencyKind(), D->isGenericLambda(),
2085 D->getLambdaCaptureDefault());
2086 else
2087 Record = CXXRecordDecl::Create(SemaRef.Context, D->getTagKind(), Owner,
2088 D->getBeginLoc(), D->getLocation(),
2089 D->getIdentifier(), PrevDecl,
2090 /*DelayTypeCreation=*/IsInjectedClassName);
2091 // Link the type of the injected-class-name to that of the outer class.
2092 if (IsInjectedClassName)
2093 (void)SemaRef.Context.getTypeDeclType(Record, cast<CXXRecordDecl>(Owner));
2094
2095 // Substitute the nested name specifier, if any.
2096 if (SubstQualifier(D, Record))
2097 return nullptr;
2098
2099 SemaRef.InstantiateAttrsForDecl(TemplateArgs, D, Record, LateAttrs,
2100 StartingScope);
2101
2102 Record->setImplicit(D->isImplicit());
2103 // FIXME: Check against AS_none is an ugly hack to work around the issue that
2104 // the tag decls introduced by friend class declarations don't have an access
2105 // specifier. Remove once this area of the code gets sorted out.
2106 if (D->getAccess() != AS_none)
2107 Record->setAccess(D->getAccess());
2108 if (!IsInjectedClassName)
2109 Record->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
2110
2111 // If the original function was part of a friend declaration,
2112 // inherit its namespace state.
2113 if (D->getFriendObjectKind())
2114 Record->setObjectOfFriendDecl();
2115
2116 // Make sure that anonymous structs and unions are recorded.
2117 if (D->isAnonymousStructOrUnion())
2118 Record->setAnonymousStructOrUnion(true);
2119
2120 if (D->isLocalClass())
2122
2123 // Forward the mangling number from the template to the instantiated decl.
2125 SemaRef.Context.getManglingNumber(D));
2126
2127 // See if the old tag was defined along with a declarator.
2128 // If it did, mark the new tag as being associated with that declarator.
2131
2132 // See if the old tag was defined along with a typedef.
2133 // If it did, mark the new tag as being associated with that typedef.
2136
2137 Owner->addDecl(Record);
2138
2139 // DR1484 clarifies that the members of a local class are instantiated as part
2140 // of the instantiation of their enclosing entity.
2141 if (D->isCompleteDefinition() && D->isLocalClass()) {
2142 Sema::LocalEagerInstantiationScope LocalInstantiations(SemaRef);
2143
2144 SemaRef.InstantiateClass(D->getLocation(), Record, D, TemplateArgs,
2146 /*Complain=*/true);
2147
2148 // For nested local classes, we will instantiate the members when we
2149 // reach the end of the outermost (non-nested) local class.
2150 if (!D->isCXXClassMember())
2151 SemaRef.InstantiateClassMembers(D->getLocation(), Record, TemplateArgs,
2153
2154 // This class may have local implicit instantiations that need to be
2155 // performed within this scope.
2156 LocalInstantiations.perform();
2157 }
2158
2160
2161 if (IsInjectedClassName)
2162 assert(Record->isInjectedClassName() && "Broken injected-class-name");
2163
2164 return Record;
2165}
2166
2167/// Adjust the given function type for an instantiation of the
2168/// given declaration, to cope with modifications to the function's type that
2169/// aren't reflected in the type-source information.
2170///
2171/// \param D The declaration we're instantiating.
2172/// \param TInfo The already-instantiated type.
2174 FunctionDecl *D,
2175 TypeSourceInfo *TInfo) {
2176 const FunctionProtoType *OrigFunc
2177 = D->getType()->castAs<FunctionProtoType>();
2178 const FunctionProtoType *NewFunc
2179 = TInfo->getType()->castAs<FunctionProtoType>();
2180 if (OrigFunc->getExtInfo() == NewFunc->getExtInfo())
2181 return TInfo->getType();
2182
2183 FunctionProtoType::ExtProtoInfo NewEPI = NewFunc->getExtProtoInfo();
2184 NewEPI.ExtInfo = OrigFunc->getExtInfo();
2185 return Context.getFunctionType(NewFunc->getReturnType(),
2186 NewFunc->getParamTypes(), NewEPI);
2187}
2188
2189/// Normal class members are of more specific types and therefore
2190/// don't make it here. This function serves three purposes:
2191/// 1) instantiating function templates
2192/// 2) substituting friend and local function declarations
2193/// 3) substituting deduction guide declarations for nested class templates
2195 FunctionDecl *D, TemplateParameterList *TemplateParams,
2196 RewriteKind FunctionRewriteKind) {
2197 // Check whether there is already a function template specialization for
2198 // this declaration.
2199 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
2200 bool isFriend;
2201 if (FunctionTemplate)
2202 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
2203 else
2204 isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
2205
2206 // Friend function defined withing class template may stop being function
2207 // definition during AST merges from different modules, in this case decl
2208 // with function body should be used for instantiation.
2209 if (isFriend) {
2210 const FunctionDecl *Defn = nullptr;
2211 if (D->hasBody(Defn)) {
2212 D = const_cast<FunctionDecl *>(Defn);
2213 FunctionTemplate = Defn->getDescribedFunctionTemplate();
2214 }
2215 }
2216
2217 if (FunctionTemplate && !TemplateParams) {
2218 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
2219
2220 void *InsertPos = nullptr;
2221 FunctionDecl *SpecFunc
2222 = FunctionTemplate->findSpecialization(Innermost, InsertPos);
2223
2224 // If we already have a function template specialization, return it.
2225 if (SpecFunc)
2226 return SpecFunc;
2227 }
2228
2229 bool MergeWithParentScope = (TemplateParams != nullptr) ||
2230 Owner->isFunctionOrMethod() ||
2231 !(isa<Decl>(Owner) &&
2232 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
2233 LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
2234
2235 ExplicitSpecifier InstantiatedExplicitSpecifier;
2236 if (auto *DGuide = dyn_cast<CXXDeductionGuideDecl>(D)) {
2237 InstantiatedExplicitSpecifier = SemaRef.instantiateExplicitSpecifier(
2238 TemplateArgs, DGuide->getExplicitSpecifier());
2239 if (InstantiatedExplicitSpecifier.isInvalid())
2240 return nullptr;
2241 }
2242
2244 TypeSourceInfo *TInfo = SubstFunctionType(D, Params);
2245 if (!TInfo)
2246 return nullptr;
2248
2249 if (TemplateParams && TemplateParams->size()) {
2250 auto *LastParam =
2251 dyn_cast<TemplateTypeParmDecl>(TemplateParams->asArray().back());
2252 if (LastParam && LastParam->isImplicit() &&
2253 LastParam->hasTypeConstraint()) {
2254 // In abbreviated templates, the type-constraints of invented template
2255 // type parameters are instantiated with the function type, invalidating
2256 // the TemplateParameterList which relied on the template type parameter
2257 // not having a type constraint. Recreate the TemplateParameterList with
2258 // the updated parameter list.
2259 TemplateParams = TemplateParameterList::Create(
2260 SemaRef.Context, TemplateParams->getTemplateLoc(),
2261 TemplateParams->getLAngleLoc(), TemplateParams->asArray(),
2262 TemplateParams->getRAngleLoc(), TemplateParams->getRequiresClause());
2263 }
2264 }
2265
2266 NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
2267 if (QualifierLoc) {
2268 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
2269 TemplateArgs);
2270 if (!QualifierLoc)
2271 return nullptr;
2272 }
2273
2274 Expr *TrailingRequiresClause = D->getTrailingRequiresClause();
2275
2276 // If we're instantiating a local function declaration, put the result
2277 // in the enclosing namespace; otherwise we need to find the instantiated
2278 // context.
2279 DeclContext *DC;
2280 if (D->isLocalExternDecl()) {
2281 DC = Owner;
2283 } else if (isFriend && QualifierLoc) {
2284 CXXScopeSpec SS;
2285 SS.Adopt(QualifierLoc);
2286 DC = SemaRef.computeDeclContext(SS);
2287 if (!DC) return nullptr;
2288 } else {
2290 TemplateArgs);
2291 }
2292
2293 DeclarationNameInfo NameInfo
2294 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
2295
2296 if (FunctionRewriteKind != RewriteKind::None)
2297 adjustForRewrite(FunctionRewriteKind, D, T, TInfo, NameInfo);
2298
2300 if (auto *DGuide = dyn_cast<CXXDeductionGuideDecl>(D)) {
2302 SemaRef.Context, DC, D->getInnerLocStart(),
2303 InstantiatedExplicitSpecifier, NameInfo, T, TInfo,
2304 D->getSourceRange().getEnd(), DGuide->getCorrespondingConstructor(),
2305 DGuide->getDeductionCandidateKind(), TrailingRequiresClause,
2306 DGuide->getSourceDeductionGuide(),
2307 DGuide->getSourceDeductionGuideKind());
2308 Function->setAccess(D->getAccess());
2309 } else {
2311 SemaRef.Context, DC, D->getInnerLocStart(), NameInfo, T, TInfo,
2312 D->getCanonicalDecl()->getStorageClass(), D->UsesFPIntrin(),
2313 D->isInlineSpecified(), D->hasWrittenPrototype(), D->getConstexprKind(),
2314 TrailingRequiresClause);
2315 Function->setFriendConstraintRefersToEnclosingTemplate(
2316 D->FriendConstraintRefersToEnclosingTemplate());
2317 Function->setRangeEnd(D->getSourceRange().getEnd());
2318 }
2319
2320 if (D->isInlined())
2321 Function->setImplicitlyInline();
2322
2323 if (QualifierLoc)
2324 Function->setQualifierInfo(QualifierLoc);
2325
2326 if (D->isLocalExternDecl())
2327 Function->setLocalExternDecl();
2328
2329 DeclContext *LexicalDC = Owner;
2330 if (!isFriend && D->isOutOfLine() && !D->isLocalExternDecl()) {
2331 assert(D->getDeclContext()->isFileContext());
2332 LexicalDC = D->getDeclContext();
2333 }
2334 else if (D->isLocalExternDecl()) {
2335 LexicalDC = SemaRef.CurContext;
2336 }
2337
2338 Function->setLexicalDeclContext(LexicalDC);
2339
2340 // Attach the parameters
2341 for (unsigned P = 0; P < Params.size(); ++P)
2342 if (Params[P])
2343 Params[P]->setOwningFunction(Function);
2344 Function->setParams(Params);
2345
2346 if (TrailingRequiresClause)
2347 Function->setTrailingRequiresClause(TrailingRequiresClause);
2348
2349 if (TemplateParams) {
2350 // Our resulting instantiation is actually a function template, since we
2351 // are substituting only the outer template parameters. For example, given
2352 //
2353 // template<typename T>
2354 // struct X {
2355 // template<typename U> friend void f(T, U);
2356 // };
2357 //
2358 // X<int> x;
2359 //
2360 // We are instantiating the friend function template "f" within X<int>,
2361 // which means substituting int for T, but leaving "f" as a friend function
2362 // template.
2363 // Build the function template itself.
2364 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, DC,
2365 Function->getLocation(),
2366 Function->getDeclName(),
2367 TemplateParams, Function);
2368 Function->setDescribedFunctionTemplate(FunctionTemplate);
2369
2370 FunctionTemplate->setLexicalDeclContext(LexicalDC);
2371
2372 if (isFriend && D->isThisDeclarationADefinition()) {
2373 FunctionTemplate->setInstantiatedFromMemberTemplate(
2374 D->getDescribedFunctionTemplate());
2375 }
2376 } else if (FunctionTemplate &&
2377 SemaRef.CodeSynthesisContexts.back().Kind !=
2379 // Record this function template specialization.
2380 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
2381 Function->setFunctionTemplateSpecialization(FunctionTemplate,
2383 Innermost),
2384 /*InsertPos=*/nullptr);
2385 } else if (FunctionRewriteKind == RewriteKind::None) {
2386 if (isFriend && D->isThisDeclarationADefinition()) {
2387 // Do not connect the friend to the template unless it's actually a
2388 // definition. We don't want non-template functions to be marked as being
2389 // template instantiations.
2390 Function->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
2391 } else if (!isFriend) {
2392 // If this is not a function template, and this is not a friend (that is,
2393 // this is a locally declared function), save the instantiation
2394 // relationship for the purposes of constraint instantiation.
2395 Function->setInstantiatedFromDecl(D);
2396 }
2397 }
2398
2399 if (isFriend) {
2400 Function->setObjectOfFriendDecl();
2401 if (FunctionTemplateDecl *FT = Function->getDescribedFunctionTemplate())
2402 FT->setObjectOfFriendDecl();
2403 }
2404
2406 Function->setInvalidDecl();
2407
2408 bool IsExplicitSpecialization = false;
2409
2411 SemaRef, Function->getDeclName(), SourceLocation(),
2414 D->isLocalExternDecl() ? RedeclarationKind::ForExternalRedeclaration
2415 : SemaRef.forRedeclarationInCurContext());
2416
2418 D->getDependentSpecializationInfo()) {
2419 assert(isFriend && "dependent specialization info on "
2420 "non-member non-friend function?");
2421
2422 // Instantiate the explicit template arguments.
2423 TemplateArgumentListInfo ExplicitArgs;
2424 if (const auto *ArgsWritten = DFTSI->TemplateArgumentsAsWritten) {
2425 ExplicitArgs.setLAngleLoc(ArgsWritten->getLAngleLoc());
2426 ExplicitArgs.setRAngleLoc(ArgsWritten->getRAngleLoc());
2427 if (SemaRef.SubstTemplateArguments(ArgsWritten->arguments(), TemplateArgs,
2428 ExplicitArgs))
2429 return nullptr;
2430 }
2431
2432 // Map the candidates for the primary template to their instantiations.
2433 for (FunctionTemplateDecl *FTD : DFTSI->getCandidates()) {
2434 if (NamedDecl *ND =
2435 SemaRef.FindInstantiatedDecl(D->getLocation(), FTD, TemplateArgs))
2436 Previous.addDecl(ND);
2437 else
2438 return nullptr;
2439 }
2440
2442 Function,
2443 DFTSI->TemplateArgumentsAsWritten ? &ExplicitArgs : nullptr,
2444 Previous))
2445 Function->setInvalidDecl();
2446
2447 IsExplicitSpecialization = true;
2448 } else if (const ASTTemplateArgumentListInfo *ArgsWritten =
2449 D->getTemplateSpecializationArgsAsWritten()) {
2450 // The name of this function was written as a template-id.
2451 SemaRef.LookupQualifiedName(Previous, DC);
2452
2453 // Instantiate the explicit template arguments.
2454 TemplateArgumentListInfo ExplicitArgs(ArgsWritten->getLAngleLoc(),
2455 ArgsWritten->getRAngleLoc());
2456 if (SemaRef.SubstTemplateArguments(ArgsWritten->arguments(), TemplateArgs,
2457 ExplicitArgs))
2458 return nullptr;
2459
2461 &ExplicitArgs,
2462 Previous))
2463 Function->setInvalidDecl();
2464
2465 IsExplicitSpecialization = true;
2466 } else if (TemplateParams || !FunctionTemplate) {
2467 // Look only into the namespace where the friend would be declared to
2468 // find a previous declaration. This is the innermost enclosing namespace,
2469 // as described in ActOnFriendFunctionDecl.
2471
2472 // In C++, the previous declaration we find might be a tag type
2473 // (class or enum). In this case, the new declaration will hide the
2474 // tag type. Note that this does not apply if we're declaring a
2475 // typedef (C++ [dcl.typedef]p4).
2476 if (Previous.isSingleTagDecl())
2477 Previous.clear();
2478
2479 // Filter out previous declarations that don't match the scope. The only
2480 // effect this has is to remove declarations found in inline namespaces
2481 // for friend declarations with unqualified names.
2482 if (isFriend && !QualifierLoc) {
2483 SemaRef.FilterLookupForScope(Previous, DC, /*Scope=*/ nullptr,
2484 /*ConsiderLinkage=*/ true,
2485 QualifierLoc.hasQualifier());
2486 }
2487 }
2488
2489 // Per [temp.inst], default arguments in function declarations at local scope
2490 // are instantiated along with the enclosing declaration. For example:
2491 //
2492 // template<typename T>
2493 // void ft() {
2494 // void f(int = []{ return T::value; }());
2495 // }
2496 // template void ft<int>(); // error: type 'int' cannot be used prior
2497 // to '::' because it has no members
2498 //
2499 // The error is issued during instantiation of ft<int>() because substitution
2500 // into the default argument fails; the default argument is instantiated even
2501 // though it is never used.
2502 if (Function->isLocalExternDecl()) {
2503 for (ParmVarDecl *PVD : Function->parameters()) {
2504 if (!PVD->hasDefaultArg())
2505 continue;
2506 if (SemaRef.SubstDefaultArgument(D->getInnerLocStart(), PVD, TemplateArgs)) {
2507 // If substitution fails, the default argument is set to a
2508 // RecoveryExpr that wraps the uninstantiated default argument so
2509 // that downstream diagnostics are omitted.
2510 Expr *UninstExpr = PVD->getUninstantiatedDefaultArg();
2511 ExprResult ErrorResult = SemaRef.CreateRecoveryExpr(
2512 UninstExpr->getBeginLoc(), UninstExpr->getEndLoc(),
2513 { UninstExpr }, UninstExpr->getType());
2514 if (ErrorResult.isUsable())
2515 PVD->setDefaultArg(ErrorResult.get());
2516 }
2517 }
2518 }
2519
2520 SemaRef.CheckFunctionDeclaration(/*Scope*/ nullptr, Function, Previous,
2521 IsExplicitSpecialization,
2522 Function->isThisDeclarationADefinition());
2523
2524 // Check the template parameter list against the previous declaration. The
2525 // goal here is to pick up default arguments added since the friend was
2526 // declared; we know the template parameter lists match, since otherwise
2527 // we would not have picked this template as the previous declaration.
2528 if (isFriend && TemplateParams && FunctionTemplate->getPreviousDecl()) {
2530 TemplateParams,
2531 FunctionTemplate->getPreviousDecl()->getTemplateParameters(),
2532 Function->isThisDeclarationADefinition()
2535 }
2536
2537 // If we're introducing a friend definition after the first use, trigger
2538 // instantiation.
2539 // FIXME: If this is a friend function template definition, we should check
2540 // to see if any specializations have been used.
2541 if (isFriend && D->isThisDeclarationADefinition() && Function->isUsed(false)) {
2542 if (MemberSpecializationInfo *MSInfo =
2543 Function->getMemberSpecializationInfo()) {
2544 if (MSInfo->getPointOfInstantiation().isInvalid()) {
2545 SourceLocation Loc = D->getLocation(); // FIXME
2546 MSInfo->setPointOfInstantiation(Loc);
2547 SemaRef.PendingLocalImplicitInstantiations.push_back(
2548 std::make_pair(Function, Loc));
2549 }
2550 }
2551 }
2552
2553 if (D->isExplicitlyDefaulted()) {
2555 return nullptr;
2556 }
2557 if (D->isDeleted())
2558 SemaRef.SetDeclDeleted(Function, D->getLocation(), D->getDeletedMessage());
2559
2560 NamedDecl *PrincipalDecl =
2561 (TemplateParams ? cast<NamedDecl>(FunctionTemplate) : Function);
2562
2563 // If this declaration lives in a different context from its lexical context,
2564 // add it to the corresponding lookup table.
2565 if (isFriend ||
2566 (Function->isLocalExternDecl() && !Function->getPreviousDecl()))
2567 DC->makeDeclVisibleInContext(PrincipalDecl);
2568
2569 if (Function->isOverloadedOperator() && !DC->isRecord() &&
2571 PrincipalDecl->setNonMemberOperator();
2572
2573 return Function;
2574}
2575
2577 CXXMethodDecl *D, TemplateParameterList *TemplateParams,
2578 RewriteKind FunctionRewriteKind) {
2579 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
2580 if (FunctionTemplate && !TemplateParams) {
2581 // We are creating a function template specialization from a function
2582 // template. Check whether there is already a function template
2583 // specialization for this particular set of template arguments.
2584 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
2585
2586 void *InsertPos = nullptr;
2587 FunctionDecl *SpecFunc
2588 = FunctionTemplate->findSpecialization(Innermost, InsertPos);
2589
2590 // If we already have a function template specialization, return it.
2591 if (SpecFunc)
2592 return SpecFunc;
2593 }
2594
2595 bool isFriend;
2596 if (FunctionTemplate)
2597 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
2598 else
2599 isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
2600
2601 bool MergeWithParentScope = (TemplateParams != nullptr) ||
2602 !(isa<Decl>(Owner) &&
2603 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
2604 LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
2605
2607 SemaRef, const_cast<CXXMethodDecl *>(D), TemplateArgs, Scope);
2608
2609 // Instantiate enclosing template arguments for friends.
2611 unsigned NumTempParamLists = 0;
2612 if (isFriend && (NumTempParamLists = D->getNumTemplateParameterLists())) {
2613 TempParamLists.resize(NumTempParamLists);
2614 for (unsigned I = 0; I != NumTempParamLists; ++I) {
2615 TemplateParameterList *TempParams = D->getTemplateParameterList(I);
2616 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
2617 if (!InstParams)
2618 return nullptr;
2619 TempParamLists[I] = InstParams;
2620 }
2621 }
2622
2623 auto InstantiatedExplicitSpecifier = ExplicitSpecifier::getFromDecl(D);
2624 // deduction guides need this
2625 const bool CouldInstantiate =
2626 InstantiatedExplicitSpecifier.getExpr() == nullptr ||
2627 !InstantiatedExplicitSpecifier.getExpr()->isValueDependent();
2628
2629 // Delay the instantiation of the explicit-specifier until after the
2630 // constraints are checked during template argument deduction.
2631 if (CouldInstantiate ||
2632 SemaRef.CodeSynthesisContexts.back().Kind !=
2634 InstantiatedExplicitSpecifier = SemaRef.instantiateExplicitSpecifier(
2635 TemplateArgs, InstantiatedExplicitSpecifier);
2636
2637 if (InstantiatedExplicitSpecifier.isInvalid())
2638 return nullptr;
2639 } else {
2640 InstantiatedExplicitSpecifier.setKind(ExplicitSpecKind::Unresolved);
2641 }
2642
2643 // Implicit destructors/constructors created for local classes in
2644 // DeclareImplicit* (see SemaDeclCXX.cpp) might not have an associated TSI.
2645 // Unfortunately there isn't enough context in those functions to
2646 // conditionally populate the TSI without breaking non-template related use
2647 // cases. Populate TSIs prior to calling SubstFunctionType to make sure we get
2648 // a proper transformation.
2649 if (isLambdaMethod(D) && !D->getTypeSourceInfo() &&
2650 isa<CXXConstructorDecl, CXXDestructorDecl>(D)) {
2651 TypeSourceInfo *TSI =
2652 SemaRef.Context.getTrivialTypeSourceInfo(D->getType());
2653 D->setTypeSourceInfo(TSI);
2654 }
2655
2657 TypeSourceInfo *TInfo = SubstFunctionType(D, Params);
2658 if (!TInfo)
2659 return nullptr;
2661
2662 if (TemplateParams && TemplateParams->size()) {
2663 auto *LastParam =
2664 dyn_cast<TemplateTypeParmDecl>(TemplateParams->asArray().back());
2665 if (LastParam && LastParam->isImplicit() &&
2666 LastParam->hasTypeConstraint()) {
2667 // In abbreviated templates, the type-constraints of invented template
2668 // type parameters are instantiated with the function type, invalidating
2669 // the TemplateParameterList which relied on the template type parameter
2670 // not having a type constraint. Recreate the TemplateParameterList with
2671 // the updated parameter list.
2672 TemplateParams = TemplateParameterList::Create(
2673 SemaRef.Context, TemplateParams->getTemplateLoc(),
2674 TemplateParams->getLAngleLoc(), TemplateParams->asArray(),
2675 TemplateParams->getRAngleLoc(), TemplateParams->getRequiresClause());
2676 }
2677 }
2678
2679 NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
2680 if (QualifierLoc) {
2681 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
2682 TemplateArgs);
2683 if (!QualifierLoc)
2684 return nullptr;
2685 }
2686
2687 DeclContext *DC = Owner;
2688 if (isFriend) {
2689 if (QualifierLoc) {
2690 CXXScopeSpec SS;
2691 SS.Adopt(QualifierLoc);
2692 DC = SemaRef.computeDeclContext(SS);
2693
2694 if (DC && SemaRef.RequireCompleteDeclContext(SS, DC))
2695 return nullptr;
2696 } else {
2697 DC = SemaRef.FindInstantiatedContext(D->getLocation(),
2698 D->getDeclContext(),
2699 TemplateArgs);
2700 }
2701 if (!DC) return nullptr;
2702 }
2703
2704 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
2705 Expr *TrailingRequiresClause = D->getTrailingRequiresClause();
2706
2707 DeclarationNameInfo NameInfo
2708 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
2709
2710 if (FunctionRewriteKind != RewriteKind::None)
2711 adjustForRewrite(FunctionRewriteKind, D, T, TInfo, NameInfo);
2712
2713 // Build the instantiated method declaration.
2714 CXXMethodDecl *Method = nullptr;
2715
2716 SourceLocation StartLoc = D->getInnerLocStart();
2717 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
2719 SemaRef.Context, Record, StartLoc, NameInfo, T, TInfo,
2720 InstantiatedExplicitSpecifier, Constructor->UsesFPIntrin(),
2721 Constructor->isInlineSpecified(), false,
2722 Constructor->getConstexprKind(), InheritedConstructor(),
2723 TrailingRequiresClause);
2724 Method->setRangeEnd(Constructor->getEndLoc());
2725 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
2727 SemaRef.Context, Record, StartLoc, NameInfo, T, TInfo,
2728 Destructor->UsesFPIntrin(), Destructor->isInlineSpecified(), false,
2729 Destructor->getConstexprKind(), TrailingRequiresClause);
2730 Method->setIneligibleOrNotSelected(true);
2731 Method->setRangeEnd(Destructor->getEndLoc());
2733 SemaRef.Context.getCanonicalType(
2734 SemaRef.Context.getTypeDeclType(Record))));
2735 } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) {
2737 SemaRef.Context, Record, StartLoc, NameInfo, T, TInfo,
2738 Conversion->UsesFPIntrin(), Conversion->isInlineSpecified(),
2739 InstantiatedExplicitSpecifier, Conversion->getConstexprKind(),
2740 Conversion->getEndLoc(), TrailingRequiresClause);
2741 } else {
2742 StorageClass SC = D->isStatic() ? SC_Static : SC_None;
2743 Method = CXXMethodDecl::Create(
2744 SemaRef.Context, Record, StartLoc, NameInfo, T, TInfo, SC,
2745 D->UsesFPIntrin(), D->isInlineSpecified(), D->getConstexprKind(),
2746 D->getEndLoc(), TrailingRequiresClause);
2747 }
2748
2749 if (D->isInlined())
2750 Method->setImplicitlyInline();
2751
2752 if (QualifierLoc)
2753 Method->setQualifierInfo(QualifierLoc);
2754
2755 if (TemplateParams) {
2756 // Our resulting instantiation is actually a function template, since we
2757 // are substituting only the outer template parameters. For example, given
2758 //
2759 // template<typename T>
2760 // struct X {
2761 // template<typename U> void f(T, U);
2762 // };
2763 //
2764 // X<int> x;
2765 //
2766 // We are instantiating the member template "f" within X<int>, which means
2767 // substituting int for T, but leaving "f" as a member function template.
2768 // Build the function template itself.
2769 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Record,
2770 Method->getLocation(),
2771 Method->getDeclName(),
2772 TemplateParams, Method);
2773 if (isFriend) {
2774 FunctionTemplate->setLexicalDeclContext(Owner);
2775 FunctionTemplate->setObjectOfFriendDecl();
2776 } else if (D->isOutOfLine())
2777 FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
2778 Method->setDescribedFunctionTemplate(FunctionTemplate);
2779 } else if (FunctionTemplate) {
2780 // Record this function template specialization.
2781 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
2782 Method->setFunctionTemplateSpecialization(FunctionTemplate,
2784 Innermost),
2785 /*InsertPos=*/nullptr);
2786 } else if (!isFriend && FunctionRewriteKind == RewriteKind::None) {
2787 // Record that this is an instantiation of a member function.
2789 }
2790
2791 // If we are instantiating a member function defined
2792 // out-of-line, the instantiation will have the same lexical
2793 // context (which will be a namespace scope) as the template.
2794 if (isFriend) {
2795 if (NumTempParamLists)
2797 SemaRef.Context,
2798 llvm::ArrayRef(TempParamLists.data(), NumTempParamLists));
2799
2800 Method->setLexicalDeclContext(Owner);
2801 Method->setObjectOfFriendDecl();
2802 } else if (D->isOutOfLine())
2804
2805 // Attach the parameters
2806 for (unsigned P = 0; P < Params.size(); ++P)
2807 Params[P]->setOwningFunction(Method);
2808 Method->setParams(Params);
2809
2810 if (InitMethodInstantiation(Method, D))
2811 Method->setInvalidDecl();
2812
2814 RedeclarationKind::ForExternalRedeclaration);
2815
2816 bool IsExplicitSpecialization = false;
2817
2818 // If the name of this function was written as a template-id, instantiate
2819 // the explicit template arguments.
2821 D->getDependentSpecializationInfo()) {
2822 // Instantiate the explicit template arguments.
2823 TemplateArgumentListInfo ExplicitArgs;
2824 if (const auto *ArgsWritten = DFTSI->TemplateArgumentsAsWritten) {
2825 ExplicitArgs.setLAngleLoc(ArgsWritten->getLAngleLoc());
2826 ExplicitArgs.setRAngleLoc(ArgsWritten->getRAngleLoc());
2827 if (SemaRef.SubstTemplateArguments(ArgsWritten->arguments(), TemplateArgs,
2828 ExplicitArgs))
2829 return nullptr;
2830 }
2831
2832 // Map the candidates for the primary template to their instantiations.
2833 for (FunctionTemplateDecl *FTD : DFTSI->getCandidates()) {
2834 if (NamedDecl *ND =
2835 SemaRef.FindInstantiatedDecl(D->getLocation(), FTD, TemplateArgs))
2836 Previous.addDecl(ND);
2837 else
2838 return nullptr;
2839 }
2840
2842 Method, DFTSI->TemplateArgumentsAsWritten ? &ExplicitArgs : nullptr,
2843 Previous))
2844 Method->setInvalidDecl();
2845
2846 IsExplicitSpecialization = true;
2847 } else if (const ASTTemplateArgumentListInfo *ArgsWritten =
2848 D->getTemplateSpecializationArgsAsWritten()) {
2849 SemaRef.LookupQualifiedName(Previous, DC);
2850
2851 TemplateArgumentListInfo ExplicitArgs(ArgsWritten->getLAngleLoc(),
2852 ArgsWritten->getRAngleLoc());
2853
2854 if (SemaRef.SubstTemplateArguments(ArgsWritten->arguments(), TemplateArgs,
2855 ExplicitArgs))
2856 return nullptr;
2857
2858 if (SemaRef.CheckFunctionTemplateSpecialization(Method,
2859 &ExplicitArgs,
2860 Previous))
2861 Method->setInvalidDecl();
2862
2863 IsExplicitSpecialization = true;
2864 } else if (!FunctionTemplate || TemplateParams || isFriend) {
2866
2867 // In C++, the previous declaration we find might be a tag type
2868 // (class or enum). In this case, the new declaration will hide the
2869 // tag type. Note that this does not apply if we're declaring a
2870 // typedef (C++ [dcl.typedef]p4).
2871 if (Previous.isSingleTagDecl())
2872 Previous.clear();
2873 }
2874
2875 // Per [temp.inst], default arguments in member functions of local classes
2876 // are instantiated along with the member function declaration. For example:
2877 //
2878 // template<typename T>
2879 // void ft() {
2880 // struct lc {
2881 // int operator()(int p = []{ return T::value; }());
2882 // };
2883 // }
2884 // template void ft<int>(); // error: type 'int' cannot be used prior
2885 // to '::'because it has no members
2886 //
2887 // The error is issued during instantiation of ft<int>()::lc::operator()
2888 // because substitution into the default argument fails; the default argument
2889 // is instantiated even though it is never used.
2891 for (unsigned P = 0; P < Params.size(); ++P) {
2892 if (!Params[P]->hasDefaultArg())
2893 continue;
2894 if (SemaRef.SubstDefaultArgument(StartLoc, Params[P], TemplateArgs)) {
2895 // If substitution fails, the default argument is set to a
2896 // RecoveryExpr that wraps the uninstantiated default argument so
2897 // that downstream diagnostics are omitted.
2898 Expr *UninstExpr = Params[P]->getUninstantiatedDefaultArg();
2899 ExprResult ErrorResult = SemaRef.CreateRecoveryExpr(
2900 UninstExpr->getBeginLoc(), UninstExpr->getEndLoc(),
2901 { UninstExpr }, UninstExpr->getType());
2902 if (ErrorResult.isUsable())
2903 Params[P]->setDefaultArg(ErrorResult.get());
2904 }
2905 }
2906 }
2907
2908 SemaRef.CheckFunctionDeclaration(nullptr, Method, Previous,
2909 IsExplicitSpecialization,
2911
2912 if (D->isPureVirtual())
2913 SemaRef.CheckPureMethod(Method, SourceRange());
2914
2915 // Propagate access. For a non-friend declaration, the access is
2916 // whatever we're propagating from. For a friend, it should be the
2917 // previous declaration we just found.
2918 if (isFriend && Method->getPreviousDecl())
2919 Method->setAccess(Method->getPreviousDecl()->getAccess());
2920 else
2921 Method->setAccess(D->getAccess());
2922 if (FunctionTemplate)
2923 FunctionTemplate->setAccess(Method->getAccess());
2924
2925 SemaRef.CheckOverrideControl(Method);
2926
2927 // If a function is defined as defaulted or deleted, mark it as such now.
2928 if (D->isExplicitlyDefaulted()) {
2929 if (SubstDefaultedFunction(Method, D))
2930 return nullptr;
2931 }
2932 if (D->isDeletedAsWritten())
2933 SemaRef.SetDeclDeleted(Method, Method->getLocation(),
2934 D->getDeletedMessage());
2935
2936 // If this is an explicit specialization, mark the implicitly-instantiated
2937 // template specialization as being an explicit specialization too.
2938 // FIXME: Is this necessary?
2939 if (IsExplicitSpecialization && !isFriend)
2940 SemaRef.CompleteMemberSpecialization(Method, Previous);
2941
2942 // If the method is a special member function, we need to mark it as
2943 // ineligible so that Owner->addDecl() won't mark the class as non trivial.
2944 // At the end of the class instantiation, we calculate eligibility again and
2945 // then we adjust trivility if needed.
2946 // We need this check to happen only after the method parameters are set,
2947 // because being e.g. a copy constructor depends on the instantiated
2948 // arguments.
2949 if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Method)) {
2950 if (Constructor->isDefaultConstructor() ||
2951 Constructor->isCopyOrMoveConstructor())
2952 Method->setIneligibleOrNotSelected(true);
2953 } else if (Method->isCopyAssignmentOperator() ||
2954 Method->isMoveAssignmentOperator()) {
2955 Method->setIneligibleOrNotSelected(true);
2956 }
2957
2958 // If there's a function template, let our caller handle it.
2959 if (FunctionTemplate) {
2960 // do nothing
2961
2962 // Don't hide a (potentially) valid declaration with an invalid one.
2963 } else if (Method->isInvalidDecl() && !Previous.empty()) {
2964 // do nothing
2965
2966 // Otherwise, check access to friends and make them visible.
2967 } else if (isFriend) {
2968 // We only need to re-check access for methods which we didn't
2969 // manage to match during parsing.
2970 if (!D->getPreviousDecl())
2971 SemaRef.CheckFriendAccess(Method);
2972
2973 Record->makeDeclVisibleInContext(Method);
2974
2975 // Otherwise, add the declaration. We don't need to do this for
2976 // class-scope specializations because we'll have matched them with
2977 // the appropriate template.
2978 } else {
2979 Owner->addDecl(Method);
2980 }
2981
2982 // PR17480: Honor the used attribute to instantiate member function
2983 // definitions
2984 if (Method->hasAttr<UsedAttr>()) {
2985 if (const auto *A = dyn_cast<CXXRecordDecl>(Owner)) {
2987 if (const MemberSpecializationInfo *MSInfo =
2988 A->getMemberSpecializationInfo())
2989 Loc = MSInfo->getPointOfInstantiation();
2990 else if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(A))
2991 Loc = Spec->getPointOfInstantiation();
2992 SemaRef.MarkFunctionReferenced(Loc, Method);
2993 }
2994 }
2995
2996 return Method;
2997}
2998
2999Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
3000 return VisitCXXMethodDecl(D);
3001}
3002
3003Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
3004 return VisitCXXMethodDecl(D);
3005}
3006
3007Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
3008 return VisitCXXMethodDecl(D);
3009}
3010
3011Decl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
3012 return SemaRef.SubstParmVarDecl(D, TemplateArgs, /*indexAdjustment*/ 0,
3013 std::nullopt,
3014 /*ExpectParameterPack=*/false);
3015}
3016
3017Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl(
3019 assert(D->getTypeForDecl()->isTemplateTypeParmType());
3020
3021 std::optional<unsigned> NumExpanded;
3022
3023 if (const TypeConstraint *TC = D->getTypeConstraint()) {
3024 if (D->isPackExpansion() && !D->isExpandedParameterPack()) {
3025 assert(TC->getTemplateArgsAsWritten() &&
3026 "type parameter can only be an expansion when explicit arguments "
3027 "are specified");
3028 // The template type parameter pack's type is a pack expansion of types.
3029 // Determine whether we need to expand this parameter pack into separate
3030 // types.
3032 for (auto &ArgLoc : TC->getTemplateArgsAsWritten()->arguments())
3033 SemaRef.collectUnexpandedParameterPacks(ArgLoc, Unexpanded);
3034
3035 // Determine whether the set of unexpanded parameter packs can and should
3036 // be expanded.
3037 bool Expand = true;
3038 bool RetainExpansion = false;
3040 cast<CXXFoldExpr>(TC->getImmediatelyDeclaredConstraint())
3041 ->getEllipsisLoc(),
3042 SourceRange(TC->getConceptNameLoc(),
3043 TC->hasExplicitTemplateArgs() ?
3044 TC->getTemplateArgsAsWritten()->getRAngleLoc() :
3045 TC->getConceptNameInfo().getEndLoc()),
3046 Unexpanded, TemplateArgs, Expand, RetainExpansion, NumExpanded))
3047 return nullptr;
3048 }
3049 }
3050
3052 SemaRef.Context, Owner, D->getBeginLoc(), D->getLocation(),
3053 D->getDepth() - TemplateArgs.getNumSubstitutedLevels(), D->getIndex(),
3054 D->getIdentifier(), D->wasDeclaredWithTypename(), D->isParameterPack(),
3055 D->hasTypeConstraint(), NumExpanded);
3056
3057 Inst->setAccess(AS_public);
3058 Inst->setImplicit(D->isImplicit());
3059 if (auto *TC = D->getTypeConstraint()) {
3060 if (!D->isImplicit()) {
3061 // Invented template parameter type constraints will be instantiated
3062 // with the corresponding auto-typed parameter as it might reference
3063 // other parameters.
3064 if (SemaRef.SubstTypeConstraint(Inst, TC, TemplateArgs,
3065 EvaluateConstraints))
3066 return nullptr;
3067 }
3068 }
3069 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited()) {
3070 TemplateArgumentLoc Output;
3071 if (!SemaRef.SubstTemplateArgument(D->getDefaultArgument(), TemplateArgs,
3072 Output))
3073 Inst->setDefaultArgument(SemaRef.getASTContext(), Output);
3074 }
3075
3076 // Introduce this template parameter's instantiation into the instantiation
3077 // scope.
3079
3080 return Inst;
3081}
3082
3083Decl *TemplateDeclInstantiator::VisitNonTypeTemplateParmDecl(
3085 // Substitute into the type of the non-type template parameter.
3086 TypeLoc TL = D->getTypeSourceInfo()->getTypeLoc();
3087 SmallVector<TypeSourceInfo *, 4> ExpandedParameterPackTypesAsWritten;
3088 SmallVector<QualType, 4> ExpandedParameterPackTypes;
3089 bool IsExpandedParameterPack = false;
3090 TypeSourceInfo *DI;
3091 QualType T;
3092 bool Invalid = false;
3093
3094 if (D->isExpandedParameterPack()) {
3095 // The non-type template parameter pack is an already-expanded pack
3096 // expansion of types. Substitute into each of the expanded types.
3097 ExpandedParameterPackTypes.reserve(D->getNumExpansionTypes());
3098 ExpandedParameterPackTypesAsWritten.reserve(D->getNumExpansionTypes());
3099 for (unsigned I = 0, N = D->getNumExpansionTypes(); I != N; ++I) {
3100 TypeSourceInfo *NewDI =
3101 SemaRef.SubstType(D->getExpansionTypeSourceInfo(I), TemplateArgs,
3102 D->getLocation(), D->getDeclName());
3103 if (!NewDI)
3104 return nullptr;
3105
3106 QualType NewT =
3108 if (NewT.isNull())
3109 return nullptr;
3110
3111 ExpandedParameterPackTypesAsWritten.push_back(NewDI);
3112 ExpandedParameterPackTypes.push_back(NewT);
3113 }
3114
3115 IsExpandedParameterPack = true;
3116 DI = D->getTypeSourceInfo();
3117 T = DI->getType();
3118 } else if (D->isPackExpansion()) {
3119 // The non-type template parameter pack's type is a pack expansion of types.
3120 // Determine whether we need to expand this parameter pack into separate
3121 // types.
3123 TypeLoc Pattern = Expansion.getPatternLoc();
3125 SemaRef.collectUnexpandedParameterPacks(Pattern, Unexpanded);
3126
3127 // Determine whether the set of unexpanded parameter packs can and should
3128 // be expanded.
3129 bool Expand = true;
3130 bool RetainExpansion = false;
3131 std::optional<unsigned> OrigNumExpansions =
3132 Expansion.getTypePtr()->getNumExpansions();
3133 std::optional<unsigned> NumExpansions = OrigNumExpansions;
3134 if (SemaRef.CheckParameterPacksForExpansion(Expansion.getEllipsisLoc(),
3135 Pattern.getSourceRange(),
3136 Unexpanded,
3137 TemplateArgs,
3138 Expand, RetainExpansion,
3139 NumExpansions))
3140 return nullptr;
3141
3142 if (Expand) {
3143 for (unsigned I = 0; I != *NumExpansions; ++I) {
3144 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
3145 TypeSourceInfo *NewDI = SemaRef.SubstType(Pattern, TemplateArgs,
3146 D->getLocation(),
3147 D->getDeclName());
3148 if (!NewDI)
3149 return nullptr;
3150
3151 QualType NewT =
3153 if (NewT.isNull())
3154 return nullptr;
3155
3156 ExpandedParameterPackTypesAsWritten.push_back(NewDI);
3157 ExpandedParameterPackTypes.push_back(NewT);
3158 }
3159
3160 // Note that we have an expanded parameter pack. The "type" of this
3161 // expanded parameter pack is the original expansion type, but callers
3162 // will end up using the expanded parameter pack types for type-checking.
3163 IsExpandedParameterPack = true;
3164 DI = D->getTypeSourceInfo();
3165 T = DI->getType();
3166 } else {
3167 // We cannot fully expand the pack expansion now, so substitute into the
3168 // pattern and create a new pack expansion type.
3169 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
3170 TypeSourceInfo *NewPattern = SemaRef.SubstType(Pattern, TemplateArgs,
3171 D->getLocation(),
3172 D->getDeclName());
3173 if (!NewPattern)
3174 return nullptr;
3175
3176 SemaRef.CheckNonTypeTemplateParameterType(NewPattern, D->getLocation());
3177 DI = SemaRef.CheckPackExpansion(NewPattern, Expansion.getEllipsisLoc(),
3178 NumExpansions);
3179 if (!DI)
3180 return nullptr;
3181
3182 T = DI->getType();
3183 }
3184 } else {
3185 // Simple case: substitution into a parameter that is not a parameter pack.
3186 DI = SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs,
3187 D->getLocation(), D->getDeclName());
3188 if (!DI)
3189 return nullptr;
3190
3191 // Check that this type is acceptable for a non-type template parameter.
3193 if (T.isNull()) {
3194 T = SemaRef.Context.IntTy;
3195 Invalid = true;
3196 }
3197 }
3198
3200 if (IsExpandedParameterPack)
3202 SemaRef.Context, Owner, D->getInnerLocStart(), D->getLocation(),
3203 D->getDepth() - TemplateArgs.getNumSubstitutedLevels(),
3204 D->getPosition(), D->getIdentifier(), T, DI, ExpandedParameterPackTypes,
3205 ExpandedParameterPackTypesAsWritten);
3206 else
3208 SemaRef.Context, Owner, D->getInnerLocStart(), D->getLocation(),
3209 D->getDepth() - TemplateArgs.getNumSubstitutedLevels(),
3210 D->getPosition(), D->getIdentifier(), T, D->isParameterPack(), DI);
3211
3212 if (AutoTypeLoc AutoLoc = DI->getTypeLoc().getContainedAutoTypeLoc())
3213 if (AutoLoc.isConstrained()) {
3214 SourceLocation EllipsisLoc;
3215 if (IsExpandedParameterPack)
3216 EllipsisLoc =
3217 DI->getTypeLoc().getAs<PackExpansionTypeLoc>().getEllipsisLoc();
3218 else if (auto *Constraint = dyn_cast_if_present<CXXFoldExpr>(
3219 D->getPlaceholderTypeConstraint()))
3220 EllipsisLoc = Constraint->getEllipsisLoc();
3221 // Note: We attach the uninstantiated constriant here, so that it can be
3222 // instantiated relative to the top level, like all our other
3223 // constraints.
3224 if (SemaRef.AttachTypeConstraint(AutoLoc, /*NewConstrainedParm=*/Param,
3225 /*OrigConstrainedParm=*/D, EllipsisLoc))
3226 Invalid = true;
3227 }
3228
3229 Param->setAccess(AS_public);
3230 Param->setImplicit(D->isImplicit());
3231 if (Invalid)
3232 Param->setInvalidDecl();
3233
3234 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited()) {
3235 EnterExpressionEvaluationContext ConstantEvaluated(
3238 if (!SemaRef.SubstTemplateArgument(D->getDefaultArgument(), TemplateArgs,
3239 Result))
3240 Param->setDefaultArgument(SemaRef.Context, Result);
3241 }
3242
3243 // Introduce this template parameter's instantiation into the instantiation
3244 // scope.
3246 return Param;
3247}
3248
3250 Sema &S,
3251 TemplateParameterList *Params,
3253 for (const auto &P : *Params) {
3254 if (P->isTemplateParameterPack())
3255 continue;
3256 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P))
3257 S.collectUnexpandedParameterPacks(NTTP->getTypeSourceInfo()->getTypeLoc(),
3258 Unexpanded);
3259 if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(P))
3260 collectUnexpandedParameterPacks(S, TTP->getTemplateParameters(),
3261 Unexpanded);
3262 }
3263}
3264
3265Decl *
3266TemplateDeclInstantiator::VisitTemplateTemplateParmDecl(
3268 // Instantiate the template parameter list of the template template parameter.
3269 TemplateParameterList *TempParams = D->getTemplateParameters();
3270 TemplateParameterList *InstParams;
3272
3273 bool IsExpandedParameterPack = false;
3274
3275 if (D->isExpandedParameterPack()) {
3276 // The template template parameter pack is an already-expanded pack
3277 // expansion of template parameters. Substitute into each of the expanded
3278 // parameters.
3279 ExpandedParams.reserve(D->getNumExpansionTemplateParameters());
3280 for (unsigned I = 0, N = D->getNumExpansionTemplateParameters();
3281 I != N; ++I) {
3283 TemplateParameterList *Expansion =
3284 SubstTemplateParams(D->getExpansionTemplateParameters(I));
3285 if (!Expansion)
3286 return nullptr;
3287 ExpandedParams.push_back(Expansion);
3288 }
3289
3290 IsExpandedParameterPack = true;
3291 InstParams = TempParams;
3292 } else if (D->isPackExpansion()) {
3293 // The template template parameter pack expands to a pack of template
3294 // template parameters. Determine whether we need to expand this parameter
3295 // pack into separate parameters.
3297 collectUnexpandedParameterPacks(SemaRef, D->getTemplateParameters(),
3298 Unexpanded);
3299
3300 // Determine whether the set of unexpanded parameter packs can and should
3301 // be expanded.
3302 bool Expand = true;
3303 bool RetainExpansion = false;
3304 std::optional<unsigned> NumExpansions;
3306 TempParams->getSourceRange(),
3307 Unexpanded,
3308 TemplateArgs,
3309 Expand, RetainExpansion,
3310 NumExpansions))
3311 return nullptr;
3312
3313 if (Expand) {
3314 for (unsigned I = 0; I != *NumExpansions; ++I) {
3315 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
3317 TemplateParameterList *Expansion = SubstTemplateParams(TempParams);
3318 if (!Expansion)
3319 return nullptr;
3320 ExpandedParams.push_back(Expansion);
3321 }
3322
3323 // Note that we have an expanded parameter pack. The "type" of this
3324 // expanded parameter pack is the original expansion type, but callers
3325 // will end up using the expanded parameter pack types for type-checking.
3326 IsExpandedParameterPack = true;
3327 InstParams = TempParams;
3328 } else {
3329 // We cannot fully expand the pack expansion now, so just substitute
3330 // into the pattern.
3331 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
3332
3334 InstParams = SubstTemplateParams(TempParams);
3335 if (!InstParams)
3336 return nullptr;
3337 }
3338 } else {
3339 // Perform the actual substitution of template parameters within a new,
3340 // local instantiation scope.
3342 InstParams = SubstTemplateParams(TempParams);
3343 if (!InstParams)
3344 return nullptr;
3345 }
3346
3347 // Build the template template parameter.
3349 if (IsExpandedParameterPack)
3351 SemaRef.Context, Owner, D->getLocation(),
3352 D->getDepth() - TemplateArgs.getNumSubstitutedLevels(),
3353 D->getPosition(), D->getIdentifier(), D->wasDeclaredWithTypename(),
3354 InstParams, ExpandedParams);
3355 else
3357 SemaRef.Context, Owner, D->getLocation(),
3358 D->getDepth() - TemplateArgs.getNumSubstitutedLevels(),
3359 D->getPosition(), D->isParameterPack(), D->getIdentifier(),
3360 D->wasDeclaredWithTypename(), InstParams);
3361 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited()) {
3362 NestedNameSpecifierLoc QualifierLoc =
3363 D->getDefaultArgument().getTemplateQualifierLoc();
3364 QualifierLoc =
3365 SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgs);
3366 TemplateName TName = SemaRef.SubstTemplateName(
3367 QualifierLoc, D->getDefaultArgument().getArgument().getAsTemplate(),
3368 D->getDefaultArgument().getTemplateNameLoc(), TemplateArgs);
3369 if (!TName.isNull())
3370 Param->setDefaultArgument(
3371 SemaRef.Context,
3373 D->getDefaultArgument().getTemplateQualifierLoc(),
3374 D->getDefaultArgument().getTemplateNameLoc()));
3375 }
3376 Param->setAccess(AS_public);
3377 Param->setImplicit(D->isImplicit());
3378
3379 // Introduce this template parameter's instantiation into the instantiation
3380 // scope.
3382
3383 return Param;
3384}
3385
3386Decl *TemplateDeclInstantiator::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
3387 // Using directives are never dependent (and never contain any types or
3388 // expressions), so they require no explicit instantiation work.
3389
3390 UsingDirectiveDecl *Inst
3391 = UsingDirectiveDecl::Create(SemaRef.Context, Owner, D->getLocation(),
3392 D->getNamespaceKeyLocation(),
3393 D->getQualifierLoc(),
3394 D->getIdentLocation(),
3395 D->getNominatedNamespace(),
3396 D->getCommonAncestor());
3397
3398 // Add the using directive to its declaration context
3399 // only if this is not a function or method.
3400 if (!Owner->isFunctionOrMethod())
3401 Owner->addDecl(Inst);
3402
3403 return Inst;
3404}
3405
3407 BaseUsingDecl *Inst,
3408 LookupResult *Lookup) {
3409
3410 bool isFunctionScope = Owner->isFunctionOrMethod();
3411
3412 for (auto *Shadow : D->shadows()) {
3413 // FIXME: UsingShadowDecl doesn't preserve its immediate target, so
3414 // reconstruct it in the case where it matters. Hm, can we extract it from
3415 // the DeclSpec when parsing and save it in the UsingDecl itself?
3416 NamedDecl *OldTarget = Shadow->getTargetDecl();
3417 if (auto *CUSD = dyn_cast<ConstructorUsingShadowDecl>(Shadow))
3418 if (auto *BaseShadow = CUSD->getNominatedBaseClassShadowDecl())
3419 OldTarget = BaseShadow;
3420
3421 NamedDecl *InstTarget = nullptr;
3422 if (auto *EmptyD =
3423 dyn_cast<UnresolvedUsingIfExistsDecl>(Shadow->getTargetDecl())) {
3425 SemaRef.Context, Owner, EmptyD->getLocation(), EmptyD->getDeclName());
3426 } else {
3427 InstTarget = cast_or_null<NamedDecl>(SemaRef.FindInstantiatedDecl(
3428 Shadow->getLocation(), OldTarget, TemplateArgs));
3429 }
3430 if (!InstTarget)
3431 return nullptr;
3432
3433 UsingShadowDecl *PrevDecl = nullptr;
3434 if (Lookup &&
3435 SemaRef.CheckUsingShadowDecl(Inst, InstTarget, *Lookup, PrevDecl))
3436 continue;
3437
3438 if (UsingShadowDecl *OldPrev = getPreviousDeclForInstantiation(Shadow))
3439 PrevDecl = cast_or_null<UsingShadowDecl>(SemaRef.FindInstantiatedDecl(
3440 Shadow->getLocation(), OldPrev, TemplateArgs));
3441
3442 UsingShadowDecl *InstShadow = SemaRef.BuildUsingShadowDecl(
3443 /*Scope*/ nullptr, Inst, InstTarget, PrevDecl);
3444 SemaRef.Context.setInstantiatedFromUsingShadowDecl(InstShadow, Shadow);
3445
3446 if (isFunctionScope)
3447 SemaRef.CurrentInstantiationScope->InstantiatedLocal(Shadow, InstShadow);
3448 }
3449
3450 return Inst;
3451}
3452
3453Decl *TemplateDeclInstantiator::VisitUsingDecl(UsingDecl *D) {
3454
3455 // The nested name specifier may be dependent, for example
3456 // template <typename T> struct t {
3457 // struct s1 { T f1(); };
3458 // struct s2 : s1 { using s1::f1; };
3459 // };
3460 // template struct t<int>;
3461 // Here, in using s1::f1, s1 refers to t<T>::s1;
3462 // we need to substitute for t<int>::s1.
3463 NestedNameSpecifierLoc QualifierLoc
3464 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
3465 TemplateArgs);
3466 if (!QualifierLoc)
3467 return nullptr;
3468
3469 // For an inheriting constructor declaration, the name of the using
3470 // declaration is the name of a constructor in this class, not in the
3471 // base class.
3472 DeclarationNameInfo NameInfo = D->getNameInfo();
3474 if (auto *RD = dyn_cast<CXXRecordDecl>(SemaRef.CurContext))
3476 SemaRef.Context.getCanonicalType(SemaRef.Context.getRecordType(RD))));
3477
3478 // We only need to do redeclaration lookups if we're in a class scope (in
3479 // fact, it's not really even possible in non-class scopes).
3480 bool CheckRedeclaration = Owner->isRecord();
3481 LookupResult Prev(SemaRef, NameInfo, Sema::LookupUsingDeclName,
3482 RedeclarationKind::ForVisibleRedeclaration);
3483
3484 UsingDecl *NewUD = UsingDecl::Create(SemaRef.Context, Owner,
3485 D->getUsingLoc(),
3486 QualifierLoc,
3487 NameInfo,
3488 D->hasTypename());
3489
3490 CXXScopeSpec SS;
3491 SS.Adopt(QualifierLoc);
3492 if (CheckRedeclaration) {
3493 Prev.setHideTags(false);
3494 SemaRef.LookupQualifiedName(Prev, Owner);
3495
3496 // Check for invalid redeclarations.
3497 if (SemaRef.CheckUsingDeclRedeclaration(D->getUsingLoc(),
3498 D->hasTypename(), SS,
3499 D->getLocation(), Prev))
3500 NewUD->setInvalidDecl();
3501 }
3502
3503 if (!NewUD->isInvalidDecl() &&
3504 SemaRef.CheckUsingDeclQualifier(D->getUsingLoc(), D->hasTypename(), SS,
3505 NameInfo, D->getLocation(), nullptr, D))
3506 NewUD->setInvalidDecl();
3507
3508 SemaRef.Context.setInstantiatedFromUsingDecl(NewUD, D);
3509 NewUD->setAccess(D->getAccess());
3510 Owner->addDecl(NewUD);
3511
3512 // Don't process the shadow decls for an invalid decl.
3513 if (NewUD->isInvalidDecl())
3514 return NewUD;
3515
3516 // If the using scope was dependent, or we had dependent bases, we need to
3517 // recheck the inheritance
3520
3521 return VisitBaseUsingDecls(D, NewUD, CheckRedeclaration ? &Prev : nullptr);
3522}
3523
3524Decl *TemplateDeclInstantiator::VisitUsingEnumDecl(UsingEnumDecl *D) {
3525 // Cannot be a dependent type, but still could be an instantiation
3526 EnumDecl *EnumD = cast_or_null<EnumDecl>(SemaRef.FindInstantiatedDecl(
3527 D->getLocation(), D->getEnumDecl(), TemplateArgs));
3528
3529 if (SemaRef.RequireCompleteEnumDecl(EnumD, EnumD->getLocation()))
3530 return nullptr;
3531
3532 TypeSourceInfo *TSI = SemaRef.SubstType(D->getEnumType(), TemplateArgs,
3533 D->getLocation(), D->getDeclName());
3534
3535 if (!TSI)
3536 return nullptr;
3537
3538 UsingEnumDecl *NewUD =
3539 UsingEnumDecl::Create(SemaRef.Context, Owner, D->getUsingLoc(),
3540 D->getEnumLoc(), D->getLocation(), TSI);
3541
3543 NewUD->setAccess(D->getAccess());
3544 Owner->addDecl(NewUD);
3545
3546 // Don't process the shadow decls for an invalid decl.
3547 if (NewUD->isInvalidDecl())
3548 return NewUD;
3549
3550 // We don't have to recheck for duplication of the UsingEnumDecl itself, as it
3551 // cannot be dependent, and will therefore have been checked during template
3552 // definition.
3553
3554 return VisitBaseUsingDecls(D, NewUD, nullptr);
3555}
3556
3557Decl *TemplateDeclInstantiator::VisitUsingShadowDecl(UsingShadowDecl *D) {
3558 // Ignore these; we handle them in bulk when processing the UsingDecl.
3559 return nullptr;
3560}
3561
3562Decl *TemplateDeclInstantiator::VisitConstructorUsingShadowDecl(
3564 // Ignore these; we handle them in bulk when processing the UsingDecl.
3565 return nullptr;
3566}
3567
3568template <typename T>
3569Decl *TemplateDeclInstantiator::instantiateUnresolvedUsingDecl(
3570 T *D, bool InstantiatingPackElement) {
3571 // If this is a pack expansion, expand it now.
3572 if (D->isPackExpansion() && !InstantiatingPackElement) {
3574 SemaRef.collectUnexpandedParameterPacks(D->getQualifierLoc(), Unexpanded);
3575 SemaRef.collectUnexpandedParameterPacks(D->getNameInfo(), Unexpanded);
3576
3577 // Determine whether the set of unexpanded parameter packs can and should
3578 // be expanded.
3579 bool Expand = true;
3580 bool RetainExpansion = false;
3581 std::optional<unsigned> NumExpansions;
3583 D->getEllipsisLoc(), D->getSourceRange(), Unexpanded, TemplateArgs,
3584 Expand, RetainExpansion, NumExpansions))
3585 return nullptr;
3586
3587 // This declaration cannot appear within a function template signature,
3588 // so we can't have a partial argument list for a parameter pack.
3589 assert(!RetainExpansion &&
3590 "should never need to retain an expansion for UsingPackDecl");
3591
3592 if (!Expand) {
3593 // We cannot fully expand the pack expansion now, so substitute into the
3594 // pattern and create a new pack expansion.
3595 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
3596 return instantiateUnresolvedUsingDecl(D, true);
3597 }
3598
3599 // Within a function, we don't have any normal way to check for conflicts
3600 // between shadow declarations from different using declarations in the
3601 // same pack expansion, but this is always ill-formed because all expansions
3602 // must produce (conflicting) enumerators.
3603 //
3604 // Sadly we can't just reject this in the template definition because it
3605 // could be valid if the pack is empty or has exactly one expansion.
3606 if (D->getDeclContext()->isFunctionOrMethod() && *NumExpansions > 1) {
3607 SemaRef.Diag(D->getEllipsisLoc(),
3608 diag::err_using_decl_redeclaration_expansion);
3609 return nullptr;
3610 }
3611
3612 // Instantiate the slices of this pack and build a UsingPackDecl.
3613 SmallVector<NamedDecl*, 8> Expansions;
3614 for (unsigned I = 0; I != *NumExpansions; ++I) {
3615 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
3616 Decl *Slice = instantiateUnresolvedUsingDecl(D, true);
3617 if (!Slice)
3618 return nullptr;
3619 // Note that we can still get unresolved using declarations here, if we
3620 // had arguments for all packs but the pattern also contained other
3621 // template arguments (this only happens during partial substitution, eg
3622 // into the body of a generic lambda in a function template).
3623 Expansions.push_back(cast<NamedDecl>(Slice));
3624 }
3625
3626 auto *NewD = SemaRef.BuildUsingPackDecl(D, Expansions);
3629 return NewD;
3630 }
3631
3632 UnresolvedUsingTypenameDecl *TD = dyn_cast<UnresolvedUsingTypenameDecl>(D);
3633 SourceLocation TypenameLoc = TD ? TD->getTypenameLoc() : SourceLocation();
3634
3635 NestedNameSpecifierLoc QualifierLoc
3636 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
3637 TemplateArgs);
3638 if (!QualifierLoc)
3639 return nullptr;
3640
3641 CXXScopeSpec SS;
3642 SS.Adopt(QualifierLoc);
3643
3644 DeclarationNameInfo NameInfo
3645 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
3646
3647 // Produce a pack expansion only if we're not instantiating a particular
3648 // slice of a pack expansion.
3649 bool InstantiatingSlice = D->getEllipsisLoc().isValid() &&
3650 SemaRef.ArgumentPackSubstitutionIndex != -1;
3651 SourceLocation EllipsisLoc =
3652 InstantiatingSlice ? SourceLocation() : D->getEllipsisLoc();
3653
3654 bool IsUsingIfExists = D->template hasAttr<UsingIfExistsAttr>();
3655 NamedDecl *UD = SemaRef.BuildUsingDeclaration(
3656 /*Scope*/ nullptr, D->getAccess(), D->getUsingLoc(),
3657 /*HasTypename*/ TD, TypenameLoc, SS, NameInfo, EllipsisLoc,
3659 /*IsInstantiation*/ true, IsUsingIfExists);
3660 if (UD) {
3661 SemaRef.InstantiateAttrs(TemplateArgs, D, UD);
3663 }
3664
3665 return UD;
3666}
3667
3668Decl *TemplateDeclInstantiator::VisitUnresolvedUsingTypenameDecl(
3670 return instantiateUnresolvedUsingDecl(D);
3671}
3672
3673Decl *TemplateDeclInstantiator::VisitUnresolvedUsingValueDecl(
3675 return instantiateUnresolvedUsingDecl(D);
3676}
3677
3678Decl *TemplateDeclInstantiator::VisitUnresolvedUsingIfExistsDecl(
3680 llvm_unreachable("referring to unresolved decl out of UsingShadowDecl");
3681}
3682
3683Decl *TemplateDeclInstantiator::VisitUsingPackDecl(UsingPackDecl *D) {
3684 SmallVector<NamedDecl*, 8> Expansions;
3685 for (auto *UD : D->expansions()) {
3686 if (NamedDecl *NewUD =
3687 SemaRef.FindInstantiatedDecl(D->getLocation(), UD, TemplateArgs))
3688 Expansions.push_back(NewUD);
3689 else
3690 return nullptr;
3691 }
3692
3693 auto *NewD = SemaRef.BuildUsingPackDecl(D, Expansions);
3696 return NewD;
3697}
3698
3699Decl *TemplateDeclInstantiator::VisitOMPThreadPrivateDecl(
3702 for (auto *I : D->varlist()) {
3703 Expr *Var = SemaRef.SubstExpr(I, TemplateArgs).get();
3704 assert(isa<DeclRefExpr>(Var) && "threadprivate arg is not a DeclRefExpr");
3705 Vars.push_back(Var);
3706 }
3707
3709 SemaRef.OpenMP().CheckOMPThreadPrivateDecl(D->getLocation(), Vars);
3710
3711 TD->setAccess(AS_public);
3712 Owner->addDecl(TD);
3713
3714 return TD;
3715}
3716
3717Decl *TemplateDeclInstantiator::VisitOMPAllocateDecl(OMPAllocateDecl *D) {
3719 for (auto *I : D->varlist()) {
3720 Expr *Var = SemaRef.SubstExpr(I, TemplateArgs).get();
3721 assert(isa<DeclRefExpr>(Var) && "allocate arg is not a DeclRefExpr");
3722 Vars.push_back(Var);
3723 }
3725 // Copy map clauses from the original mapper.
3726 for (OMPClause *C : D->clauselists()) {
3727 OMPClause *IC = nullptr;
3728 if (auto *AC = dyn_cast<OMPAllocatorClause>(C)) {
3729 ExprResult NewE = SemaRef.SubstExpr(AC->getAllocator(), TemplateArgs);
3730 if (!NewE.isUsable())
3731 continue;
3732 IC = SemaRef.OpenMP().ActOnOpenMPAllocatorClause(
3733 NewE.get(), AC->getBeginLoc(), AC->getLParenLoc(), AC->getEndLoc());
3734 } else if (auto *AC = dyn_cast<OMPAlignClause>(C)) {
3735 ExprResult NewE = SemaRef.SubstExpr(AC->getAlignment(), TemplateArgs);
3736 if (!NewE.isUsable())
3737 continue;
3738 IC = SemaRef.OpenMP().ActOnOpenMPAlignClause(
3739 NewE.get(), AC->getBeginLoc(), AC->getLParenLoc(), AC->getEndLoc());
3740 // If align clause value ends up being invalid, this can end up null.
3741 if (!IC)
3742 continue;
3743 }
3744 Clauses.push_back(IC);
3745 }
3746
3748 D->getLocation(), Vars, Clauses, Owner);
3749 if (Res.get().isNull())
3750 return nullptr;
3751 return Res.get().getSingleDecl();
3752}
3753
3754Decl *TemplateDeclInstantiator::VisitOMPRequiresDecl(OMPRequiresDecl *D) {
3755 llvm_unreachable(
3756 "Requires directive cannot be instantiated within a dependent context");
3757}
3758
3759Decl *TemplateDeclInstantiator::VisitOMPDeclareReductionDecl(
3761 // Instantiate type and check if it is allowed.
3762 const bool RequiresInstantiation =
3763 D->getType()->isDependentType() ||
3764 D->getType()->isInstantiationDependentType() ||
3765 D->getType()->containsUnexpandedParameterPack();
3766 QualType SubstReductionType;
3767 if (RequiresInstantiation) {
3768 SubstReductionType = SemaRef.OpenMP().ActOnOpenMPDeclareReductionType(
3769 D->getLocation(),
3771 D->getType(), TemplateArgs, D->getLocation(), DeclarationName())));
3772 } else {
3773 SubstReductionType = D->getType();
3774 }
3775 if (SubstReductionType.isNull())
3776 return nullptr;
3777 Expr *Combiner = D->getCombiner();
3778 Expr *Init = D->getInitializer();
3779 bool IsCorrect = true;
3780 // Create instantiated copy.
3781 std::pair<QualType, SourceLocation> ReductionTypes[] = {
3782 std::make_pair(SubstReductionType, D->getLocation())};
3783 auto *PrevDeclInScope = D->getPrevDeclInScope();
3784 if (PrevDeclInScope && !PrevDeclInScope->isInvalidDecl()) {
3785 PrevDeclInScope = cast<OMPDeclareReductionDecl>(
3786 cast<Decl *>(*SemaRef.CurrentInstantiationScope->findInstantiationOf(
3787 PrevDeclInScope)));
3788 }
3790 /*S=*/nullptr, Owner, D->getDeclName(), ReductionTypes, D->getAccess(),
3791 PrevDeclInScope);
3792 auto *NewDRD = cast<OMPDeclareReductionDecl>(DRD.get().getSingleDecl());
3794 Expr *SubstCombiner = nullptr;
3795 Expr *SubstInitializer = nullptr;
3796 // Combiners instantiation sequence.
3797 if (Combiner) {
3799 /*S=*/nullptr, NewDRD);
3801 cast<DeclRefExpr>(D->getCombinerIn())->getDecl(),
3802 cast<DeclRefExpr>(NewDRD->getCombinerIn())->getDecl());
3804 cast<DeclRefExpr>(D->getCombinerOut())->getDecl(),
3805 cast<DeclRefExpr>(NewDRD->getCombinerOut())->getDecl());
3806 auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(Owner);
3807 Sema::CXXThisScopeRAII ThisScope(SemaRef, ThisContext, Qualifiers(),
3808 ThisContext);
3809 SubstCombiner = SemaRef.SubstExpr(Combiner, TemplateArgs).get();
3811 SubstCombiner);
3812 }
3813 // Initializers instantiation sequence.
3814 if (Init) {
3815 VarDecl *OmpPrivParm =
3817 /*S=*/nullptr, NewDRD);
3819 cast<DeclRefExpr>(D->getInitOrig())->getDecl(),
3820 cast<DeclRefExpr>(NewDRD->getInitOrig())->getDecl());
3822 cast<DeclRefExpr>(D->getInitPriv())->getDecl(),
3823 cast<DeclRefExpr>(NewDRD->getInitPriv())->getDecl());
3824 if (D->getInitializerKind() == OMPDeclareReductionInitKind::Call) {
3825 SubstInitializer = SemaRef.SubstExpr(Init, TemplateArgs).get();
3826 } else {
3827 auto *OldPrivParm =
3828 cast<VarDecl>(cast<DeclRefExpr>(D->getInitPriv())->getDecl());
3829 IsCorrect = IsCorrect && OldPrivParm->hasInit();
3830 if (IsCorrect)
3831 SemaRef.InstantiateVariableInitializer(OmpPrivParm, OldPrivParm,
3832 TemplateArgs);
3833 }
3835 NewDRD, SubstInitializer, OmpPrivParm);
3836 }
3837 IsCorrect = IsCorrect && SubstCombiner &&
3838 (!Init ||
3839 (D->getInitializerKind() == OMPDeclareReductionInitKind::Call &&
3840 SubstInitializer) ||
3841 (D->getInitializerKind() != OMPDeclareReductionInitKind::Call &&
3842 !SubstInitializer));
3843
3845 /*S=*/nullptr, DRD, IsCorrect && !D->isInvalidDecl());
3846
3847 return NewDRD;
3848}
3849
3850Decl *
3851TemplateDeclInstantiator::VisitOMPDeclareMapperDecl(OMPDeclareMapperDecl *D) {
3852 // Instantiate type and check if it is allowed.
3853 const bool RequiresInstantiation =
3854 D->getType()->isDependentType() ||
3855 D->getType()->isInstantiationDependentType() ||
3856 D->getType()->containsUnexpandedParameterPack();
3857 QualType SubstMapperTy;
3858 DeclarationName VN = D->getVarName();
3859 if (RequiresInstantiation) {
3860 SubstMapperTy = SemaRef.OpenMP().ActOnOpenMPDeclareMapperType(
3861 D->getLocation(),
3862 ParsedType::make(SemaRef.SubstType(D->getType(), TemplateArgs,
3863 D->getLocation(), VN)));
3864 } else {
3865 SubstMapperTy = D->getType();
3866 }
3867 if (SubstMapperTy.isNull())
3868 return nullptr;
3869 // Create an instantiated copy of mapper.
3870 auto *PrevDeclInScope = D->getPrevDeclInScope();
3871 if (PrevDeclInScope && !PrevDeclInScope->isInvalidDecl()) {
3872 PrevDeclInScope = cast<OMPDeclareMapperDecl>(
3873 cast<Decl *>(*SemaRef.CurrentInstantiationScope->findInstantiationOf(
3874 PrevDeclInScope)));
3875 }
3876 bool IsCorrect = true;
3878 // Instantiate the mapper variable.
3879 DeclarationNameInfo DirName;
3880 SemaRef.OpenMP().StartOpenMPDSABlock(llvm::omp::OMPD_declare_mapper, DirName,
3881 /*S=*/nullptr,
3882 (*D->clauselist_begin())->getBeginLoc());
3883 ExprResult MapperVarRef =
3885 /*S=*/nullptr, SubstMapperTy, D->getLocation(), VN);
3887 cast<DeclRefExpr>(D->getMapperVarRef())->getDecl(),
3888 cast<DeclRefExpr>(MapperVarRef.get())->getDecl());
3889 auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(Owner);
3890 Sema::CXXThisScopeRAII ThisScope(SemaRef, ThisContext, Qualifiers(),
3891 ThisContext);
3892 // Instantiate map clauses.
3893 for (OMPClause *C : D->clauselists()) {
3894 auto *OldC = cast<OMPMapClause>(C);
3895 SmallVector<Expr *, 4> NewVars;
3896 for (Expr *OE : OldC->varlist()) {
3897 Expr *NE = SemaRef.SubstExpr(OE, TemplateArgs).get();
3898 if (!NE) {
3899 IsCorrect = false;
3900 break;
3901 }
3902 NewVars.push_back(NE);
3903 }
3904 if (!IsCorrect)
3905 break;
3906 NestedNameSpecifierLoc NewQualifierLoc =
3907 SemaRef.SubstNestedNameSpecifierLoc(OldC->getMapperQualifierLoc(),
3908 TemplateArgs);
3909 CXXScopeSpec SS;
3910 SS.Adopt(NewQualifierLoc);
3911 DeclarationNameInfo NewNameInfo =
3912 SemaRef.SubstDeclarationNameInfo(OldC->getMapperIdInfo(), TemplateArgs);
3913 OMPVarListLocTy Locs(OldC->getBeginLoc(), OldC->getLParenLoc(),
3914 OldC->getEndLoc());
3915 OMPClause *NewC = SemaRef.OpenMP().ActOnOpenMPMapClause(
3916 OldC->getIteratorModifier(), OldC->getMapTypeModifiers(),
3917 OldC->getMapTypeModifiersLoc(), SS, NewNameInfo, OldC->getMapType(),
3918 OldC->isImplicitMapType(), OldC->getMapLoc(), OldC->getColonLoc(),
3919 NewVars, Locs);
3920 Clauses.push_back(NewC);
3921 }
3922 SemaRef.OpenMP().EndOpenMPDSABlock(nullptr);
3923 if (!IsCorrect)
3924 return nullptr;
3926 /*S=*/nullptr, Owner, D->getDeclName(), SubstMapperTy, D->getLocation(),
3927 VN, D->getAccess(), MapperVarRef.get(), Clauses, PrevDeclInScope);
3928 Decl *NewDMD = DG.get().getSingleDecl();
3930 return NewDMD;
3931}
3932
3933Decl *TemplateDeclInstantiator::VisitOMPCapturedExprDecl(
3934 OMPCapturedExprDecl * /*D*/) {
3935 llvm_unreachable("Should not be met in templates");
3936}
3937
3939 return VisitFunctionDecl(D, nullptr);
3940}
3941
3942Decl *
3943TemplateDeclInstantiator::VisitCXXDeductionGuideDecl(CXXDeductionGuideDecl *D) {
3944 Decl *Inst = VisitFunctionDecl(D, nullptr);
3945 if (Inst && !D->getDescribedFunctionTemplate())
3946 Owner->addDecl(Inst);
3947 return Inst;
3948}
3949
3951 return VisitCXXMethodDecl(D, nullptr);
3952}
3953
3954Decl *TemplateDeclInstantiator::VisitRecordDecl(RecordDecl *D) {
3955 llvm_unreachable("There are only CXXRecordDecls in C++");
3956}
3957
3958Decl *
3959TemplateDeclInstantiator::VisitClassTemplateSpecializationDecl(
3961 // As a MS extension, we permit class-scope explicit specialization
3962 // of member class templates.
3963 ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
3964 assert(ClassTemplate->getDeclContext()->isRecord() &&
3965 D->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
3966 "can only instantiate an explicit specialization "
3967 "for a member class template");
3968
3969 // Lookup the already-instantiated declaration in the instantiation
3970 // of the class template.
3971 ClassTemplateDecl *InstClassTemplate =
3972 cast_or_null<ClassTemplateDecl>(SemaRef.FindInstantiatedDecl(
3973 D->getLocation(), ClassTemplate, TemplateArgs));
3974 if (!InstClassTemplate)
3975 return nullptr;
3976
3977 // Substitute into the template arguments of the class template explicit
3978 // specialization.
3979 TemplateArgumentListInfo InstTemplateArgs;
3980 if (const ASTTemplateArgumentListInfo *TemplateArgsInfo =
3981 D->getTemplateArgsAsWritten()) {
3982 InstTemplateArgs.setLAngleLoc(TemplateArgsInfo->getLAngleLoc());
3983 InstTemplateArgs.setRAngleLoc(TemplateArgsInfo->getRAngleLoc());
3984
3985 if (SemaRef.SubstTemplateArguments(TemplateArgsInfo->arguments(),
3986 TemplateArgs, InstTemplateArgs))
3987 return nullptr;
3988 }
3989
3990 // Check that the template argument list is well-formed for this
3991 // class template.
3993 if (SemaRef.CheckTemplateArgumentList(
3994 InstClassTemplate, D->getLocation(), InstTemplateArgs,
3995 /*DefaultArgs=*/{}, /*PartialTemplateArgs=*/false, CTAI,
3996 /*UpdateArgsWithConversions=*/true))
3997 return nullptr;
3998
3999 // Figure out where to insert this class template explicit specialization
4000 // in the member template's set of class template explicit specializations.
4001 void *InsertPos = nullptr;
4003 InstClassTemplate->findSpecialization(CTAI.CanonicalConverted, InsertPos);
4004
4005 // Check whether we've already seen a conflicting instantiation of this
4006 // declaration (for instance, if there was a prior implicit instantiation).
4007 bool Ignored;
4008 if (PrevDecl &&
4010 D->getSpecializationKind(),
4011 PrevDecl,
4012 PrevDecl->getSpecializationKind(),
4013 PrevDecl->getPointOfInstantiation(),
4014 Ignored))
4015 return nullptr;
4016
4017 // If PrevDecl was a definition and D is also a definition, diagnose.
4018 // This happens in cases like:
4019 //
4020 // template<typename T, typename U>
4021 // struct Outer {
4022 // template<typename X> struct Inner;
4023 // template<> struct Inner<T> {};
4024 // template<> struct Inner<U> {};
4025 // };
4026 //
4027 // Outer<int, int> outer; // error: the explicit specializations of Inner
4028 // // have the same signature.
4029 if (PrevDecl && PrevDecl->getDefinition() &&
4030 D->isThisDeclarationADefinition()) {
4031 SemaRef.Diag(D->getLocation(), diag::err_redefinition) << PrevDecl;
4032 SemaRef.Diag(PrevDecl->getDefinition()->getLocation(),
4033 diag::note_previous_definition);
4034 return nullptr;
4035 }
4036
4037 // Create the class template partial specialization declaration.
4040 SemaRef.Context, D->getTagKind(), Owner, D->getBeginLoc(),
4041 D->getLocation(), InstClassTemplate, CTAI.CanonicalConverted,
4042 PrevDecl);
4043 InstD->setTemplateArgsAsWritten(InstTemplateArgs);
4044
4045 // Add this partial specialization to the set of class template partial
4046 // specializations.
4047 if (!PrevDecl)
4048 InstClassTemplate->AddSpecialization(InstD, InsertPos);
4049
4050 // Substitute the nested name specifier, if any.
4051 if (SubstQualifier(D, InstD))
4052 return nullptr;
4053
4054 InstD->setAccess(D->getAccess());
4056 InstD->setSpecializationKind(D->getSpecializationKind());
4057 InstD->setExternKeywordLoc(D->getExternKeywordLoc());
4058 InstD->setTemplateKeywordLoc(D->getTemplateKeywordLoc());
4059
4060 Owner->addDecl(InstD);
4061
4062 // Instantiate the members of the class-scope explicit specialization eagerly.
4063 // We don't have support for lazy instantiation of an explicit specialization
4064 // yet, and MSVC eagerly instantiates in this case.
4065 // FIXME: This is wrong in standard C++.
4066 if (D->isThisDeclarationADefinition() &&
4067 SemaRef.InstantiateClass(D->getLocation(), InstD, D, TemplateArgs,
4069 /*Complain=*/true))
4070 return nullptr;
4071
4072 return InstD;
4073}
4074
4077
4078 TemplateArgumentListInfo VarTemplateArgsInfo;
4079 VarTemplateDecl *VarTemplate = D->getSpecializedTemplate();
4080 assert(VarTemplate &&
4081 "A template specialization without specialized template?");
4082
4083 VarTemplateDecl *InstVarTemplate =
4084 cast_or_null<VarTemplateDecl>(SemaRef.FindInstantiatedDecl(
4085 D->getLocation(), VarTemplate, TemplateArgs));
4086 if (!InstVarTemplate)
4087 return nullptr;
4088
4089 // Substitute the current template arguments.
4090 if (const ASTTemplateArgumentListInfo *TemplateArgsInfo =
4091 D->getTemplateArgsAsWritten()) {
4092 VarTemplateArgsInfo.setLAngleLoc(TemplateArgsInfo->getLAngleLoc());
4093 VarTemplateArgsInfo.setRAngleLoc(TemplateArgsInfo->getRAngleLoc());
4094
4095 if (SemaRef.SubstTemplateArguments(TemplateArgsInfo->arguments(),
4096 TemplateArgs, VarTemplateArgsInfo))
4097 return nullptr;
4098 }
4099
4100 // Check that the template argument list is well-formed for this template.
4102 if (SemaRef.CheckTemplateArgumentList(
4103 InstVarTemplate, D->getLocation(), VarTemplateArgsInfo,
4104 /*DefaultArgs=*/{}, /*PartialTemplateArgs=*/false, CTAI,
4105 /*UpdateArgsWithConversions=*/true))
4106 return nullptr;
4107
4108 // Check whether we've already seen a declaration of this specialization.
4109 void *InsertPos = nullptr;
4111 InstVarTemplate->findSpecialization(CTAI.CanonicalConverted, InsertPos);
4112
4113 // Check whether we've already seen a conflicting instantiation of this
4114 // declaration (for instance, if there was a prior implicit instantiation).
4115 bool Ignored;
4116 if (PrevDecl && SemaRef.CheckSpecializationInstantiationRedecl(
4117 D->getLocation(), D->getSpecializationKind(), PrevDecl,
4118 PrevDecl->getSpecializationKind(),
4119 PrevDecl->getPointOfInstantiation(), Ignored))
4120 return nullptr;
4121
4122 return VisitVarTemplateSpecializationDecl(InstVarTemplate, D,
4123 VarTemplateArgsInfo,
4124 CTAI.CanonicalConverted, PrevDecl);
4125}
4126
4128 VarTemplateDecl *VarTemplate, VarDecl *D,
4129 const TemplateArgumentListInfo &TemplateArgsInfo,
4132
4133 // Do substitution on the type of the declaration
4134 TypeSourceInfo *DI =
4135 SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs,
4136 D->getTypeSpecStartLoc(), D->getDeclName());
4137 if (!DI)
4138 return nullptr;
4139
4140 if (DI->getType()->isFunctionType()) {
4141 SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function)
4142 << D->isStaticDataMember() << DI->getType();
4143 return nullptr;
4144 }
4145
4146 // Build the instantiated declaration
4148 SemaRef.Context, Owner, D->getInnerLocStart(), D->getLocation(),
4149 VarTemplate, DI->getType(), DI, D->getStorageClass(), Converted);
4150 Var->setTemplateArgsAsWritten(TemplateArgsInfo);
4151 if (!PrevDecl) {
4152 void *InsertPos = nullptr;
4153 VarTemplate->findSpecialization(Converted, InsertPos);
4154 VarTemplate->AddSpecialization(Var, InsertPos);
4155 }
4156
4157 if (SemaRef.getLangOpts().OpenCL)
4158 SemaRef.deduceOpenCLAddressSpace(Var);
4159
4160 // Substitute the nested name specifier, if any.
4161 if (SubstQualifier(D, Var))
4162 return nullptr;
4163
4164 SemaRef.BuildVariableInstantiation(Var, D, TemplateArgs, LateAttrs, Owner,
4165 StartingScope, false, PrevDecl);
4166
4167 return Var;
4168}
4169
4170Decl *TemplateDeclInstantiator::VisitObjCAtDefsFieldDecl(ObjCAtDefsFieldDecl *D) {
4171 llvm_unreachable("@defs is not supported in Objective-C++");
4172}
4173
4174Decl *TemplateDeclInstantiator::VisitFriendTemplateDecl(FriendTemplateDecl *D) {
4175 // FIXME: We need to be able to instantiate FriendTemplateDecls.
4176 unsigned DiagID = SemaRef.getDiagnostics().getCustomDiagID(
4178 "cannot instantiate %0 yet");
4179 SemaRef.Diag(D->getLocation(), DiagID)
4180 << D->getDeclKindName();
4181
4182 return nullptr;
4183}
4184
4185Decl *TemplateDeclInstantiator::VisitConceptDecl(ConceptDecl *D) {
4186 llvm_unreachable("Concept definitions cannot reside inside a template");
4187}
4188
4189Decl *TemplateDeclInstantiator::VisitImplicitConceptSpecializationDecl(
4191 llvm_unreachable("Concept specializations cannot reside inside a template");
4192}
4193
4194Decl *
4195TemplateDeclInstantiator::VisitRequiresExprBodyDecl(RequiresExprBodyDecl *D) {
4197 D->getBeginLoc());
4198}
4199
4201 llvm_unreachable("Unexpected decl");
4202}
4203
4205 const MultiLevelTemplateArgumentList &TemplateArgs) {
4206 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
4207 if (D->isInvalidDecl())
4208 return nullptr;
4209
4210 Decl *SubstD;
4212 SubstD = Instantiator.Visit(D);
4213 });
4214 return SubstD;
4215}
4216
4218 FunctionDecl *Orig, QualType &T,
4219 TypeSourceInfo *&TInfo,
4220 DeclarationNameInfo &NameInfo) {
4222
4223 // C++2a [class.compare.default]p3:
4224 // the return type is replaced with bool
4225 auto *FPT = T->castAs<FunctionProtoType>();
4226 T = SemaRef.Context.getFunctionType(
4227 SemaRef.Context.BoolTy, FPT->getParamTypes(), FPT->getExtProtoInfo());
4228
4229 // Update the return type in the source info too. The most straightforward
4230 // way is to create new TypeSourceInfo for the new type. Use the location of
4231 // the '= default' as the location of the new type.
4232 //
4233 // FIXME: Set the correct return type when we initially transform the type,
4234 // rather than delaying it to now.
4235 TypeSourceInfo *NewTInfo =
4236 SemaRef.Context.getTrivialTypeSourceInfo(T, Orig->getEndLoc());
4237 auto OldLoc = TInfo->getTypeLoc().getAsAdjusted<FunctionProtoTypeLoc>();
4238 assert(OldLoc && "type of function is not a function type?");
4239 auto NewLoc = NewTInfo->getTypeLoc().castAs<FunctionProtoTypeLoc>();
4240 for (unsigned I = 0, N = OldLoc.getNumParams(); I != N; ++I)
4241 NewLoc.setParam(I, OldLoc.getParam(I));
4242 TInfo = NewTInfo;
4243
4244 // and the declarator-id is replaced with operator==
4245 NameInfo.setName(
4246 SemaRef.Context.DeclarationNames.getCXXOperatorName(OO_EqualEqual));
4247}
4248
4250 FunctionDecl *Spaceship) {
4251 if (Spaceship->isInvalidDecl())
4252 return nullptr;
4253
4254 // C++2a [class.compare.default]p3:
4255 // an == operator function is declared implicitly [...] with the same
4256 // access and function-definition and in the same class scope as the
4257 // three-way comparison operator function
4258 MultiLevelTemplateArgumentList NoTemplateArgs;
4260 NoTemplateArgs.addOuterRetainedLevels(RD->getTemplateDepth());
4261 TemplateDeclInstantiator Instantiator(*this, RD, NoTemplateArgs);
4262 Decl *R;
4263 if (auto *MD = dyn_cast<CXXMethodDecl>(Spaceship)) {
4264 R = Instantiator.VisitCXXMethodDecl(
4265 MD, /*TemplateParams=*/nullptr,
4267 } else {
4268 assert(Spaceship->getFriendObjectKind() &&
4269 "defaulted spaceship is neither a member nor a friend");
4270
4271 R = Instantiator.VisitFunctionDecl(
4272 Spaceship, /*TemplateParams=*/nullptr,
4274 if (!R)
4275 return nullptr;
4276
4277 FriendDecl *FD =
4278 FriendDecl::Create(Context, RD, Spaceship->getLocation(),
4279 cast<NamedDecl>(R), Spaceship->getBeginLoc());
4280 FD->setAccess(AS_public);
4281 RD->addDecl(FD);
4282 }
4283 return cast_or_null<FunctionDecl>(R);
4284}
4285
4286/// Instantiates a nested template parameter list in the current
4287/// instantiation context.
4288///
4289/// \param L The parameter list to instantiate
4290///
4291/// \returns NULL if there was an error
4294 // Get errors for all the parameters before bailing out.
4295 bool Invalid = false;
4296
4297 unsigned N = L->size();
4298 typedef SmallVector<NamedDecl *, 8> ParamVector;
4299 ParamVector Params;
4300 Params.reserve(N);
4301 for (auto &P : *L) {
4302 NamedDecl *D = cast_or_null<NamedDecl>(Visit(P));
4303 Params.push_back(D);
4304 Invalid = Invalid || !D || D->isInvalidDecl();
4305 }
4306
4307 // Clean up if we had an error.
4308 if (Invalid)
4309 return nullptr;
4310
4311 Expr *InstRequiresClause = L->getRequiresClause();
4312
4315 L->getLAngleLoc(), Params,
4316 L->getRAngleLoc(), InstRequiresClause);
4317 return InstL;
4318}
4319
4322 const MultiLevelTemplateArgumentList &TemplateArgs,
4323 bool EvaluateConstraints) {
4324 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
4325 Instantiator.setEvaluateConstraints(EvaluateConstraints);
4326 return Instantiator.SubstTemplateParams(Params);
4327}
4328
4329/// Instantiate the declaration of a class template partial
4330/// specialization.
4331///
4332/// \param ClassTemplate the (instantiated) class template that is partially
4333// specialized by the instantiation of \p PartialSpec.
4334///
4335/// \param PartialSpec the (uninstantiated) class template partial
4336/// specialization that we are instantiating.
4337///
4338/// \returns The instantiated partial specialization, if successful; otherwise,
4339/// NULL to indicate an error.
4342 ClassTemplateDecl *ClassTemplate,
4344 // Create a local instantiation scope for this class template partial
4345 // specialization, which will contain the instantiations of the template
4346 // parameters.
4348
4349 // Substitute into the template parameters of the class template partial
4350 // specialization.
4351 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
4352 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
4353 if (!InstParams)
4354 return nullptr;
4355
4356 // Substitute into the template arguments of the class template partial
4357 // specialization.
4358 const ASTTemplateArgumentListInfo *TemplArgInfo
4359 = PartialSpec->getTemplateArgsAsWritten();
4360 TemplateArgumentListInfo InstTemplateArgs(TemplArgInfo->LAngleLoc,
4361 TemplArgInfo->RAngleLoc);
4362 if (SemaRef.SubstTemplateArguments(TemplArgInfo->arguments(), TemplateArgs,
4363 InstTemplateArgs))
4364 return nullptr;
4365
4366 // Check that the template argument list is well-formed for this
4367 // class template.
4369 if (SemaRef.CheckTemplateArgumentList(
4370 ClassTemplate, PartialSpec->getLocation(), InstTemplateArgs,
4371 /*DefaultArgs=*/{},
4372 /*PartialTemplateArgs=*/false, CTAI))
4373 return nullptr;
4374
4375 // Check these arguments are valid for a template partial specialization.
4377 PartialSpec->getLocation(), ClassTemplate, InstTemplateArgs.size(),
4378 CTAI.CanonicalConverted))
4379 return nullptr;
4380
4381 // Figure out where to insert this class template partial specialization
4382 // in the member template's set of class template partial specializations.
4383 void *InsertPos = nullptr;
4386 InstParams, InsertPos);
4387
4388 // Build the canonical type that describes the converted template
4389 // arguments of the class template partial specialization.
4391 TemplateName(ClassTemplate), CTAI.CanonicalConverted);
4392
4393 // Create the class template partial specialization declaration.
4396 SemaRef.Context, PartialSpec->getTagKind(), Owner,
4397 PartialSpec->getBeginLoc(), PartialSpec->getLocation(), InstParams,
4398 ClassTemplate, CTAI.CanonicalConverted, CanonType,
4399 /*PrevDecl=*/nullptr);
4400
4401 InstPartialSpec->setTemplateArgsAsWritten(InstTemplateArgs);
4402
4403 // Substitute the nested name specifier, if any.
4404 if (SubstQualifier(PartialSpec, InstPartialSpec))
4405 return nullptr;
4406
4407 InstPartialSpec->setInstantiatedFromMember(PartialSpec);
4408
4409 if (PrevDecl) {
4410 // We've already seen a partial specialization with the same template
4411 // parameters and template arguments. This can happen, for example, when
4412 // substituting the outer template arguments ends up causing two
4413 // class template partial specializations of a member class template
4414 // to have identical forms, e.g.,
4415 //
4416 // template<typename T, typename U>
4417 // struct Outer {
4418 // template<typename X, typename Y> struct Inner;
4419 // template<typename Y> struct Inner<T, Y>;
4420 // template<typename Y> struct Inner<U, Y>;
4421 // };
4422 //
4423 // Outer<int, int> outer; // error: the partial specializations of Inner
4424 // // have the same signature.
4425 SemaRef.Diag(InstPartialSpec->getLocation(),
4426 diag::err_partial_spec_redeclared)
4427 << InstPartialSpec;
4428 SemaRef.Diag(PrevDecl->getLocation(), diag::note_prev_partial_spec_here)
4429 << SemaRef.Context.getTypeDeclType(PrevDecl);
4430 return nullptr;
4431 }
4432
4433 // Check the completed partial specialization.
4434 SemaRef.CheckTemplatePartialSpecialization(InstPartialSpec);
4435
4436 // Add this partial specialization to the set of class template partial
4437 // specializations.
4438 ClassTemplate->AddPartialSpecialization(InstPartialSpec,
4439 /*InsertPos=*/nullptr);
4440 return InstPartialSpec;
4441}
4442
4443/// Instantiate the declaration of a variable template partial
4444/// specialization.
4445///
4446/// \param VarTemplate the (instantiated) variable template that is partially
4447/// specialized by the instantiation of \p PartialSpec.
4448///
4449/// \param PartialSpec the (uninstantiated) variable template partial
4450/// specialization that we are instantiating.
4451///
4452/// \returns The instantiated partial specialization, if successful; otherwise,
4453/// NULL to indicate an error.
4456 VarTemplateDecl *VarTemplate,
4458 // Create a local instantiation scope for this variable template partial
4459 // specialization, which will contain the instantiations of the template
4460 // parameters.
4462
4463 // Substitute into the template parameters of the variable template partial
4464 // specialization.
4465 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
4466 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
4467 if (!InstParams)
4468 return nullptr;
4469
4470 // Substitute into the template arguments of the variable template partial
4471 // specialization.
4472 const ASTTemplateArgumentListInfo *TemplArgInfo
4473 = PartialSpec->getTemplateArgsAsWritten();
4474 TemplateArgumentListInfo InstTemplateArgs(TemplArgInfo->LAngleLoc,
4475 TemplArgInfo->RAngleLoc);
4476 if (SemaRef.SubstTemplateArguments(TemplArgInfo->arguments(), TemplateArgs,
4477 InstTemplateArgs))
4478 return nullptr;
4479
4480 // Check that the template argument list is well-formed for this
4481 // class template.
4483 if (SemaRef.CheckTemplateArgumentList(VarTemplate, PartialSpec->getLocation(),
4484 InstTemplateArgs, /*DefaultArgs=*/{},
4485 /*PartialTemplateArgs=*/false, CTAI))
4486 return nullptr;
4487
4488 // Check these arguments are valid for a template partial specialization.
4490 PartialSpec->getLocation(), VarTemplate, InstTemplateArgs.size(),
4491 CTAI.CanonicalConverted))
4492 return nullptr;
4493
4494 // Figure out where to insert this variable template partial specialization
4495 // in the member template's set of variable template partial specializations.
4496 void *InsertPos = nullptr;
4499 InstParams, InsertPos);
4500
4501 // Do substitution on the type of the declaration
4502 TypeSourceInfo *DI = SemaRef.SubstType(
4503 PartialSpec->getTypeSourceInfo(), TemplateArgs,
4504 PartialSpec->getTypeSpecStartLoc(), PartialSpec->getDeclName());
4505 if (!DI)
4506 return nullptr;
4507
4508 if (DI->getType()->isFunctionType()) {
4509 SemaRef.Diag(PartialSpec->getLocation(),
4510 diag::err_variable_instantiates_to_function)
4511 << PartialSpec->isStaticDataMember() << DI->getType();
4512 return nullptr;
4513 }
4514
4515 // Create the variable template partial specialization declaration.
4516 VarTemplatePartialSpecializationDecl *InstPartialSpec =
4518 SemaRef.Context, Owner, PartialSpec->getInnerLocStart(),
4519 PartialSpec->getLocation(), InstParams, VarTemplate, DI->getType(),
4520 DI, PartialSpec->getStorageClass(), CTAI.CanonicalConverted);
4521
4522 InstPartialSpec->setTemplateArgsAsWritten(InstTemplateArgs);
4523
4524 // Substitute the nested name specifier, if any.
4525 if (SubstQualifier(PartialSpec, InstPartialSpec))
4526 return nullptr;
4527
4528 InstPartialSpec->setInstantiatedFromMember(PartialSpec);
4529
4530 if (PrevDecl) {
4531 // We've already seen a partial specialization with the same template
4532 // parameters and template arguments. This can happen, for example, when
4533 // substituting the outer template arguments ends up causing two
4534 // variable template partial specializations of a member variable template
4535 // to have identical forms, e.g.,
4536 //
4537 // template<typename T, typename U>
4538 // struct Outer {
4539 // template<typename X, typename Y> pair<X,Y> p;
4540 // template<typename Y> pair<T, Y> p;
4541 // template<typename Y> pair<U, Y> p;
4542 // };
4543 //
4544 // Outer<int, int> outer; // error: the partial specializations of Inner
4545 // // have the same signature.
4546 SemaRef.Diag(PartialSpec->getLocation(),
4547 diag::err_var_partial_spec_redeclared)
4548 << InstPartialSpec;
4549 SemaRef.Diag(PrevDecl->getLocation(),
4550 diag::note_var_prev_partial_spec_here);
4551 return nullptr;
4552 }
4553 // Check the completed partial specialization.
4554 SemaRef.CheckTemplatePartialSpecialization(InstPartialSpec);
4555
4556 // Add this partial specialization to the set of variable template partial
4557 // specializations. The instantiation of the initializer is not necessary.
4558 VarTemplate->AddPartialSpecialization(InstPartialSpec, /*InsertPos=*/nullptr);
4559
4560 SemaRef.BuildVariableInstantiation(InstPartialSpec, PartialSpec, TemplateArgs,
4561 LateAttrs, Owner, StartingScope);
4562
4563 return InstPartialSpec;
4564}
4565
4569 TypeSourceInfo *OldTInfo = D->getTypeSourceInfo();
4570 assert(OldTInfo && "substituting function without type source info");
4571 assert(Params.empty() && "parameter vector is non-empty at start");
4572
4573 CXXRecordDecl *ThisContext = nullptr;
4574 Qualifiers ThisTypeQuals;
4575 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
4576 ThisContext = cast<CXXRecordDecl>(Owner);
4577 ThisTypeQuals = Method->getFunctionObjectParameterType().getQualifiers();
4578 }
4579
4580 TypeSourceInfo *NewTInfo = SemaRef.SubstFunctionDeclType(
4581 OldTInfo, TemplateArgs, D->getTypeSpecStartLoc(), D->getDeclName(),
4582 ThisContext, ThisTypeQuals, EvaluateConstraints);
4583 if (!NewTInfo)
4584 return nullptr;
4585
4586 TypeLoc OldTL = OldTInfo->getTypeLoc().IgnoreParens();
4587 if (FunctionProtoTypeLoc OldProtoLoc = OldTL.getAs<FunctionProtoTypeLoc>()) {
4588 if (NewTInfo != OldTInfo) {
4589 // Get parameters from the new type info.
4590 TypeLoc NewTL = NewTInfo->getTypeLoc().IgnoreParens();
4591 FunctionProtoTypeLoc NewProtoLoc = NewTL.castAs<FunctionProtoTypeLoc>();
4592 unsigned NewIdx = 0;
4593 for (unsigned OldIdx = 0, NumOldParams = OldProtoLoc.getNumParams();
4594 OldIdx != NumOldParams; ++OldIdx) {
4595 ParmVarDecl *OldParam = OldProtoLoc.getParam(OldIdx);
4596 if (!OldParam)
4597 return nullptr;
4598
4600
4601 std::optional<unsigned> NumArgumentsInExpansion;
4602 if (OldParam->isParameterPack())
4603 NumArgumentsInExpansion =
4604 SemaRef.getNumArgumentsInExpansion(OldParam->getType(),
4605 TemplateArgs);
4606 if (!NumArgumentsInExpansion) {
4607 // Simple case: normal parameter, or a parameter pack that's
4608 // instantiated to a (still-dependent) parameter pack.
4609 ParmVarDecl *NewParam = NewProtoLoc.getParam(NewIdx++);
4610 Params.push_back(NewParam);
4611 Scope->InstantiatedLocal(OldParam, NewParam);
4612 } else {
4613 // Parameter pack expansion: make the instantiation an argument pack.
4614 Scope->MakeInstantiatedLocalArgPack(OldParam);
4615 for (unsigned I = 0; I != *NumArgumentsInExpansion; ++I) {
4616 ParmVarDecl *NewParam = NewProtoLoc.getParam(NewIdx++);
4617 Params.push_back(NewParam);
4618 Scope->InstantiatedLocalPackArg(OldParam, NewParam);
4619 }
4620 }
4621 }
4622 } else {
4623 // The function type itself was not dependent and therefore no
4624 // substitution occurred. However, we still need to instantiate
4625 // the function parameters themselves.
4626 const FunctionProtoType *OldProto =
4627 cast<FunctionProtoType>(OldProtoLoc.getType());
4628 for (unsigned i = 0, i_end = OldProtoLoc.getNumParams(); i != i_end;
4629 ++i) {
4630 ParmVarDecl *OldParam = OldProtoLoc.getParam(i);
4631 if (!OldParam) {
4632 Params.push_back(SemaRef.BuildParmVarDeclForTypedef(
4633 D, D->getLocation(), OldProto->getParamType(i)));
4634 continue;
4635 }
4636
4637 ParmVarDecl *Parm =
4638 cast_or_null<ParmVarDecl>(VisitParmVarDecl(OldParam));
4639 if (!Parm)
4640 return nullptr;
4641 Params.push_back(Parm);
4642 }
4643 }
4644 } else {
4645 // If the type of this function, after ignoring parentheses, is not
4646 // *directly* a function type, then we're instantiating a function that
4647 // was declared via a typedef or with attributes, e.g.,
4648 //
4649 // typedef int functype(int, int);
4650 // functype func;
4651 // int __cdecl meth(int, int);
4652 //
4653 // In this case, we'll just go instantiate the ParmVarDecls that we
4654 // synthesized in the method declaration.
4655 SmallVector<QualType, 4> ParamTypes;
4656 Sema::ExtParameterInfoBuilder ExtParamInfos;
4657 if (SemaRef.SubstParmTypes(D->getLocation(), D->parameters(), nullptr,
4658 TemplateArgs, ParamTypes, &Params,
4659 ExtParamInfos))
4660 return nullptr;
4661 }
4662
4663 return NewTInfo;
4664}
4665
4666void Sema::addInstantiatedLocalVarsToScope(FunctionDecl *Function,
4667 const FunctionDecl *PatternDecl,
4669 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(getFunctionScopes().back());
4670
4671 for (auto *decl : PatternDecl->decls()) {
4672 if (!isa<VarDecl>(decl) || isa<ParmVarDecl>(decl))
4673 continue;
4674
4675 VarDecl *VD = cast<VarDecl>(decl);
4676 IdentifierInfo *II = VD->getIdentifier();
4677
4678 auto it = llvm::find_if(Function->decls(), [&](Decl *inst) {
4679 VarDecl *InstVD = dyn_cast<VarDecl>(inst);
4680 return InstVD && InstVD->isLocalVarDecl() &&
4681 InstVD->getIdentifier() == II;
4682 });
4683
4684 if (it == Function->decls().end())
4685 continue;
4686
4687 Scope.InstantiatedLocal(VD, *it);
4688 LSI->addCapture(cast<VarDecl>(*it), /*isBlock=*/false, /*isByref=*/false,
4689 /*isNested=*/false, VD->getLocation(), SourceLocation(),
4690 VD->getType(), /*Invalid=*/false);
4691 }
4692}
4693
4694bool Sema::addInstantiatedParametersToScope(
4695 FunctionDecl *Function, const FunctionDecl *PatternDecl,
4697 const MultiLevelTemplateArgumentList &TemplateArgs) {
4698 unsigned FParamIdx = 0;
4699 for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I) {
4700 const ParmVarDecl *PatternParam = PatternDecl->getParamDecl(I);
4701 if (!PatternParam->isParameterPack()) {
4702 // Simple case: not a parameter pack.
4703 assert(FParamIdx < Function->getNumParams());
4704 ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
4705 FunctionParam->setDeclName(PatternParam->getDeclName());
4706 // If the parameter's type is not dependent, update it to match the type
4707 // in the pattern. They can differ in top-level cv-qualifiers, and we want
4708 // the pattern's type here. If the type is dependent, they can't differ,
4709 // per core issue 1668. Substitute into the type from the pattern, in case
4710 // it's instantiation-dependent.
4711 // FIXME: Updating the type to work around this is at best fragile.
4712 if (!PatternDecl->getType()->isDependentType()) {
4713 QualType T = SubstType(PatternParam->getType(), TemplateArgs,
4714 FunctionParam->getLocation(),
4715 FunctionParam->getDeclName());
4716 if (T.isNull())
4717 return true;
4718 FunctionParam->setType(T);
4719 }
4720
4721 Scope.InstantiatedLocal(PatternParam, FunctionParam);
4722 ++FParamIdx;
4723 continue;
4724 }
4725
4726 // Expand the parameter pack.
4727 Scope.MakeInstantiatedLocalArgPack(PatternParam);
4728 std::optional<unsigned> NumArgumentsInExpansion =
4729 getNumArgumentsInExpansion(PatternParam->getType(), TemplateArgs);
4730 if (NumArgumentsInExpansion) {
4731 QualType PatternType =
4732 PatternParam->getType()->castAs<PackExpansionType>()->getPattern();
4733 for (unsigned Arg = 0; Arg < *NumArgumentsInExpansion; ++Arg) {
4734 ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
4735 FunctionParam->setDeclName(PatternParam->getDeclName());
4736 if (!PatternDecl->getType()->isDependentType()) {
4737 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, Arg);
4738 QualType T =
4739 SubstType(PatternType, TemplateArgs, FunctionParam->getLocation(),
4740 FunctionParam->getDeclName());
4741 if (T.isNull())
4742 return true;
4743 FunctionParam->setType(T);
4744 }
4745
4746 Scope.InstantiatedLocalPackArg(PatternParam, FunctionParam);
4747 ++FParamIdx;
4748 }
4749 }
4750 }
4751
4752 return false;
4753}
4754
4756 ParmVarDecl *Param) {
4757 assert(Param->hasUninstantiatedDefaultArg());
4758
4759 // FIXME: We don't track member specialization info for non-defining
4760 // friend declarations, so we will not be able to later find the function
4761 // pattern. As a workaround, don't instantiate the default argument in this
4762 // case. This is correct per the standard and only an issue for recovery
4763 // purposes. [dcl.fct.default]p4:
4764 // if a friend declaration D specifies a default argument expression,
4765 // that declaration shall be a definition.
4766 if (FD->getFriendObjectKind() != Decl::FOK_None &&
4768 return true;
4769
4770 // Instantiate the expression.
4771 //
4772 // FIXME: Pass in a correct Pattern argument, otherwise
4773 // getTemplateInstantiationArgs uses the lexical context of FD, e.g.
4774 //
4775 // template<typename T>
4776 // struct A {
4777 // static int FooImpl();
4778 //
4779 // template<typename Tp>
4780 // // bug: default argument A<T>::FooImpl() is evaluated with 2-level
4781 // // template argument list [[T], [Tp]], should be [[Tp]].
4782 // friend A<Tp> Foo(int a);
4783 // };
4784 //
4785 // template<typename T>
4786 // A<T> Foo(int a = A<T>::FooImpl());
4788 FD, FD->getLexicalDeclContext(),
4789 /*Final=*/false, /*Innermost=*/std::nullopt,
4790 /*RelativeToPrimary=*/true, /*Pattern=*/nullptr,
4791 /*ForConstraintInstantiation=*/false, /*SkipForSpecialization=*/false,
4792 /*ForDefaultArgumentSubstitution=*/true);
4793
4794 if (SubstDefaultArgument(CallLoc, Param, TemplateArgs, /*ForCallExpr*/ true))
4795 return true;
4796
4798 L->DefaultArgumentInstantiated(Param);
4799
4800 return false;
4801}
4802
4804 FunctionDecl *Decl) {
4805 const FunctionProtoType *Proto = Decl->getType()->castAs<FunctionProtoType>();
4807 return;
4808
4809 InstantiatingTemplate Inst(*this, PointOfInstantiation, Decl,
4811 if (Inst.isInvalid()) {
4812 // We hit the instantiation depth limit. Clear the exception specification
4813 // so that our callers don't have to cope with EST_Uninstantiated.
4815 return;
4816 }
4817 if (Inst.isAlreadyInstantiating()) {
4818 // This exception specification indirectly depends on itself. Reject.
4819 // FIXME: Corresponding rule in the standard?
4820 Diag(PointOfInstantiation, diag::err_exception_spec_cycle) << Decl;
4822 return;
4823 }
4824
4825 // Enter the scope of this instantiation. We don't use
4826 // PushDeclContext because we don't have a scope.
4827 Sema::ContextRAII savedContext(*this, Decl);
4829
4830 MultiLevelTemplateArgumentList TemplateArgs =
4832 /*Final=*/false, /*Innermost=*/std::nullopt,
4833 /*RelativeToPrimary*/ true);
4834
4835 // FIXME: We can't use getTemplateInstantiationPattern(false) in general
4836 // here, because for a non-defining friend declaration in a class template,
4837 // we don't store enough information to map back to the friend declaration in
4838 // the template.
4839 FunctionDecl *Template = Proto->getExceptionSpecTemplate();
4840 if (addInstantiatedParametersToScope(Decl, Template, Scope, TemplateArgs)) {
4842 return;
4843 }
4844
4845 // The noexcept specification could reference any lambda captures. Ensure
4846 // those are added to the LocalInstantiationScope.
4848 *this, Decl, TemplateArgs, Scope,
4849 /*ShouldAddDeclsFromParentScope=*/false);
4850
4852 TemplateArgs);
4853}
4854
4855/// Initializes the common fields of an instantiation function
4856/// declaration (New) from the corresponding fields of its template (Tmpl).
4857///
4858/// \returns true if there was an error
4859bool
4861 FunctionDecl *Tmpl) {
4862 New->setImplicit(Tmpl->isImplicit());
4863
4864 // Forward the mangling number from the template to the instantiated decl.
4865 SemaRef.Context.setManglingNumber(New,
4866 SemaRef.Context.getManglingNumber(Tmpl));
4867
4868 // If we are performing substituting explicitly-specified template arguments
4869 // or deduced template arguments into a function template and we reach this
4870 // point, we are now past the point where SFINAE applies and have committed
4871 // to keeping the new function template specialization. We therefore
4872 // convert the active template instantiation for the function template
4873 // into a template instantiation for this specific function template
4874 // specialization, which is not a SFINAE context, so that we diagnose any
4875 // further errors in the declaration itself.
4876 //
4877 // FIXME: This is a hack.
4878 typedef Sema::CodeSynthesisContext ActiveInstType;
4879 ActiveInstType &ActiveInst = SemaRef.CodeSynthesisContexts.back();
4880 if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution ||
4881 ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) {
4882 if (isa<FunctionTemplateDecl>(ActiveInst.Entity)) {
4883 SemaRef.InstantiatingSpecializations.erase(
4884 {ActiveInst.Entity->getCanonicalDecl(), ActiveInst.Kind});
4885 atTemplateEnd(SemaRef.TemplateInstCallbacks, SemaRef, ActiveInst);
4886 ActiveInst.Kind = ActiveInstType::TemplateInstantiation;
4887 ActiveInst.Entity = New;
4888 atTemplateBegin(SemaRef.TemplateInstCallbacks, SemaRef, ActiveInst);
4889 }
4890 }
4891
4892 const FunctionProtoType *Proto = Tmpl->getType()->getAs<FunctionProtoType>();
4893 assert(Proto && "Function template without prototype?");
4894
4895 if (Proto->hasExceptionSpec() || Proto->getNoReturnAttr()) {
4897
4898 // DR1330: In C++11, defer instantiation of a non-trivial
4899 // exception specification.
4900 // DR1484: Local classes and their members are instantiated along with the
4901 // containing function.
4902 if (SemaRef.getLangOpts().CPlusPlus11 &&
4903 EPI.ExceptionSpec.Type != EST_None &&
4907 FunctionDecl *ExceptionSpecTemplate = Tmpl;
4909 ExceptionSpecTemplate = EPI.ExceptionSpec.SourceTemplate;
4912 NewEST = EST_Unevaluated;
4913
4914 // Mark the function has having an uninstantiated exception specification.
4915 const FunctionProtoType *NewProto
4916 = New->getType()->getAs<FunctionProtoType>();
4917 assert(NewProto && "Template instantiation without function prototype?");
4918 EPI = NewProto->getExtProtoInfo();
4919 EPI.ExceptionSpec.Type = NewEST;
4920 EPI.ExceptionSpec.SourceDecl = New;
4921 EPI.ExceptionSpec.SourceTemplate = ExceptionSpecTemplate;
4922 New->setType(SemaRef.Context.getFunctionType(
4923 NewProto->getReturnType(), NewProto->getParamTypes(), EPI));
4924 } else {
4925 Sema::ContextRAII SwitchContext(SemaRef, New);
4926 SemaRef.SubstExceptionSpec(New, Proto, TemplateArgs);
4927 }
4928 }
4929
4930 // Get the definition. Leaves the variable unchanged if undefined.
4931 const FunctionDecl *Definition = Tmpl;
4932 Tmpl->isDefined(Definition);
4933
4934 SemaRef.InstantiateAttrs(TemplateArgs, Definition, New,
4935 LateAttrs, StartingScope);
4936
4937 return false;
4938}
4939
4940/// Initializes common fields of an instantiated method
4941/// declaration (New) from the corresponding fields of its template
4942/// (Tmpl).
4943///
4944/// \returns true if there was an error
4945bool
4947 CXXMethodDecl *Tmpl) {
4948 if (InitFunctionInstantiation(New, Tmpl))
4949 return true;
4950
4951 if (isa<CXXDestructorDecl>(New) && SemaRef.getLangOpts().CPlusPlus11)
4952 SemaRef.AdjustDestructorExceptionSpec(cast<CXXDestructorDecl>(New));
4953
4954 New->setAccess(Tmpl->getAccess());
4955 if (Tmpl->isVirtualAsWritten())
4956 New->setVirtualAsWritten(true);
4957
4958 // FIXME: New needs a pointer to Tmpl
4959 return false;
4960}
4961
4963 FunctionDecl *Tmpl) {
4964 // Transfer across any unqualified lookups.
4965 if (auto *DFI = Tmpl->getDefalutedOrDeletedInfo()) {
4967 Lookups.reserve(DFI->getUnqualifiedLookups().size());
4968 bool AnyChanged = false;
4969 for (DeclAccessPair DA : DFI->getUnqualifiedLookups()) {
4970 NamedDecl *D = SemaRef.FindInstantiatedDecl(New->getLocation(),
4971 DA.getDecl(), TemplateArgs);
4972 if (!D)
4973 return true;
4974 AnyChanged |= (D != DA.getDecl());
4975 Lookups.push_back(DeclAccessPair::make(D, DA.getAccess()));
4976 }
4977
4978 // It's unlikely that substitution will change any declarations. Don't
4979 // store an unnecessary copy in that case.
4982 SemaRef.Context, Lookups)
4983 : DFI);
4984 }
4985
4986 SemaRef.SetDeclDefaulted(New, Tmpl->getLocation());
4987 return false;
4988}
4989
4993 FunctionDecl *FD = FTD->getTemplatedDecl();
4994
4996 InstantiatingTemplate Inst(*this, Loc, FTD, Args->asArray(), CSC, Info);
4997 if (Inst.isInvalid())
4998 return nullptr;
4999
5000 ContextRAII SavedContext(*this, FD);
5001 MultiLevelTemplateArgumentList MArgs(FTD, Args->asArray(),
5002 /*Final=*/false);
5003
5004 return cast_or_null<FunctionDecl>(SubstDecl(FD, FD->getParent(), MArgs));
5005}
5006
5009 bool Recursive,
5010 bool DefinitionRequired,
5011 bool AtEndOfTU) {
5012 if (Function->isInvalidDecl() || isa<CXXDeductionGuideDecl>(Function))
5013 return;
5014
5015 // Never instantiate an explicit specialization except if it is a class scope
5016 // explicit specialization.
5018 Function->getTemplateSpecializationKindForInstantiation();
5019 if (TSK == TSK_ExplicitSpecialization)
5020 return;
5021
5022 // Never implicitly instantiate a builtin; we don't actually need a function
5023 // body.
5024 if (Function->getBuiltinID() && TSK == TSK_ImplicitInstantiation &&
5025 !DefinitionRequired)
5026 return;
5027
5028 // Don't instantiate a definition if we already have one.
5029 const FunctionDecl *ExistingDefn = nullptr;
5030 if (Function->isDefined(ExistingDefn,
5031 /*CheckForPendingFriendDefinition=*/true)) {
5032 if (ExistingDefn->isThisDeclarationADefinition())
5033 return;
5034
5035 // If we're asked to instantiate a function whose body comes from an
5036 // instantiated friend declaration, attach the instantiated body to the
5037 // corresponding declaration of the function.
5039 Function = const_cast<FunctionDecl*>(ExistingDefn);
5040 }
5041
5042 // Find the function body that we'll be substituting.
5043 const FunctionDecl *PatternDecl = Function->getTemplateInstantiationPattern();
5044 assert(PatternDecl && "instantiating a non-template");
5045
5046 const FunctionDecl *PatternDef = PatternDecl->getDefinition();
5047 Stmt *Pattern = nullptr;
5048 if (PatternDef) {
5049 Pattern = PatternDef->getBody(PatternDef);
5050 PatternDecl = PatternDef;
5051 if (PatternDef->willHaveBody())
5052 PatternDef = nullptr;
5053 }
5054
5055 // FIXME: We need to track the instantiation stack in order to know which
5056 // definitions should be visible within this instantiation.
5057 if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Function,
5058 Function->getInstantiatedFromMemberFunction(),
5059 PatternDecl, PatternDef, TSK,
5060 /*Complain*/DefinitionRequired)) {
5061 if (DefinitionRequired)
5062 Function->setInvalidDecl();
5063 else if (TSK == TSK_ExplicitInstantiationDefinition ||
5064 (Function->isConstexpr() && !Recursive)) {
5065 // Try again at the end of the translation unit (at which point a
5066 // definition will be required).
5067 assert(!Recursive);
5068 Function->setInstantiationIsPending(true);
5069 PendingInstantiations.push_back(
5070 std::make_pair(Function, PointOfInstantiation));
5071
5072 if (llvm::isTimeTraceVerbose()) {
5073 llvm::timeTraceAddInstantEvent("DeferInstantiation", [&] {
5074 std::string Name;
5075 llvm::raw_string_ostream OS(Name);
5076 Function->getNameForDiagnostic(OS, getPrintingPolicy(),
5077 /*Qualified=*/true);
5078 return Name;
5079 });
5080 }
5081 } else if (TSK == TSK_ImplicitInstantiation) {
5082 if (AtEndOfTU && !getDiagnostics().hasErrorOccurred() &&
5083 !getSourceManager().isInSystemHeader(PatternDecl->getBeginLoc())) {
5084 Diag(PointOfInstantiation, diag::warn_func_template_missing)
5085 << Function;
5086 Diag(PatternDecl->getLocation(), diag::note_forward_template_decl);
5088 Diag(PointOfInstantiation, diag::note_inst_declaration_hint)
5089 << Function;
5090 }
5091 }
5092
5093 return;
5094 }
5095
5096 // Postpone late parsed template instantiations.
5097 if (PatternDecl->isLateTemplateParsed() &&
5099 Function->setInstantiationIsPending(true);
5100 LateParsedInstantiations.push_back(
5101 std::make_pair(Function, PointOfInstantiation));
5102 return;
5103 }
5104
5105 llvm::TimeTraceScope TimeScope("InstantiateFunction", [&]() {
5106 llvm::TimeTraceMetadata M;
5107 llvm::raw_string_ostream OS(M.Detail);
5108 Function->getNameForDiagnostic(OS, getPrintingPolicy(),
5109 /*Qualified=*/true);
5110 if (llvm::isTimeTraceVerbose()) {
5111 auto Loc = SourceMgr.getExpansionLoc(Function->getLocation());
5112 M.File = SourceMgr.getFilename(Loc);
5114 }
5115 return M;
5116 });
5117
5118 // If we're performing recursive template instantiation, create our own
5119 // queue of pending implicit instantiations that we will instantiate later,
5120 // while we're still within our own instantiation context.
5121 // This has to happen before LateTemplateParser below is called, so that
5122 // it marks vtables used in late parsed templates as used.
5123 GlobalEagerInstantiationScope GlobalInstantiations(*this,
5124 /*Enabled=*/Recursive);
5125 LocalEagerInstantiationScope LocalInstantiations(*this);
5126
5127 // Call the LateTemplateParser callback if there is a need to late parse
5128 // a templated function definition.
5129 if (!Pattern && PatternDecl->isLateTemplateParsed() &&
5131 // FIXME: Optimize to allow individual templates to be deserialized.
5132 if (PatternDecl->isFromASTFile())
5133 ExternalSource->ReadLateParsedTemplates(LateParsedTemplateMap);
5134
5135 auto LPTIter = LateParsedTemplateMap.find(PatternDecl);
5136 assert(LPTIter != LateParsedTemplateMap.end() &&
5137 "missing LateParsedTemplate");
5138 LateTemplateParser(OpaqueParser, *LPTIter->second);
5139 Pattern = PatternDecl->getBody(PatternDecl);
5141 }
5142
5143 // Note, we should never try to instantiate a deleted function template.
5144 assert((Pattern || PatternDecl->isDefaulted() ||
5145 PatternDecl->hasSkippedBody()) &&
5146 "unexpected kind of function template definition");
5147
5148 // C++1y [temp.explicit]p10:
5149 // Except for inline functions, declarations with types deduced from their
5150 // initializer or return value, and class template specializations, other
5151 // explicit instantiation declarations have the effect of suppressing the
5152 // implicit instantiation of the entity to which they refer.
5154 !PatternDecl->isInlined() &&
5155 !PatternDecl->getReturnType()->getContainedAutoType())
5156 return;
5157
5158 if (PatternDecl->isInlined()) {
5159 // Function, and all later redeclarations of it (from imported modules,
5160 // for instance), are now implicitly inline.
5161 for (auto *D = Function->getMostRecentDecl(); /**/;
5162 D = D->getPreviousDecl()) {
5163 D->setImplicitlyInline();
5164 if (D == Function)
5165 break;
5166 }
5167 }
5168
5169 InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
5170 if (Inst.isInvalid() || Inst.isAlreadyInstantiating())
5171 return;
5173 "instantiating function definition");
5174
5175 // The instantiation is visible here, even if it was first declared in an
5176 // unimported module.
5177 Function->setVisibleDespiteOwningModule();
5178
5179 // Copy the source locations from the pattern.
5180 Function->setLocation(PatternDecl->getLocation());
5181 Function->setInnerLocStart(PatternDecl->getInnerLocStart());
5182 Function->setRangeEnd(PatternDecl->getEndLoc());
5183 Function->setDeclarationNameLoc(PatternDecl->getNameInfo().getInfo());
5184
5187
5188 Qualifiers ThisTypeQuals;
5189 CXXRecordDecl *ThisContext = nullptr;
5190 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
5191 ThisContext = Method->getParent();
5192 ThisTypeQuals = Method->getMethodQualifiers();
5193 }
5194 CXXThisScopeRAII ThisScope(*this, ThisContext, ThisTypeQuals);
5195
5196 // Introduce a new scope where local variable instantiations will be
5197 // recorded, unless we're actually a member function within a local
5198 // class, in which case we need to merge our results with the parent
5199 // scope (of the enclosing function). The exception is instantiating
5200 // a function template specialization, since the template to be
5201 // instantiated already has references to locals properly substituted.
5202 bool MergeWithParentScope = false;
5203 if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Function->getDeclContext()))
5204 MergeWithParentScope =
5205 Rec->isLocalClass() && !Function->isFunctionTemplateSpecialization();
5206
5207 LocalInstantiationScope Scope(*this, MergeWithParentScope);
5208 auto RebuildTypeSourceInfoForDefaultSpecialMembers = [&]() {
5209 // Special members might get their TypeSourceInfo set up w.r.t the
5210 // PatternDecl context, in which case parameters could still be pointing
5211 // back to the original class, make sure arguments are bound to the
5212 // instantiated record instead.
5213 assert(PatternDecl->isDefaulted() &&
5214 "Special member needs to be defaulted");
5215 auto PatternSM = getDefaultedFunctionKind(PatternDecl).asSpecialMember();
5216 if (!(PatternSM == CXXSpecialMemberKind::CopyConstructor ||
5220 return;
5221
5222 auto *NewRec = dyn_cast<CXXRecordDecl>(Function->getDeclContext());
5223 const auto *PatternRec =
5224 dyn_cast<CXXRecordDecl>(PatternDecl->getDeclContext());
5225 if (!NewRec || !PatternRec)
5226 return;
5227 if (!PatternRec->isLambda())
5228 return;
5229
5230 struct SpecialMemberTypeInfoRebuilder
5231 : TreeTransform<SpecialMemberTypeInfoRebuilder> {
5233 const CXXRecordDecl *OldDecl;
5234 CXXRecordDecl *NewDecl;
5235
5236 SpecialMemberTypeInfoRebuilder(Sema &SemaRef, const CXXRecordDecl *O,
5237 CXXRecordDecl *N)
5238 : TreeTransform(SemaRef), OldDecl(O), NewDecl(N) {}
5239
5240 bool TransformExceptionSpec(SourceLocation Loc,
5242 SmallVectorImpl<QualType> &Exceptions,
5243 bool &Changed) {
5244 return false;
5245 }
5246
5247 QualType TransformRecordType(TypeLocBuilder &TLB, RecordTypeLoc TL) {
5248 const RecordType *T = TL.getTypePtr();
5249 RecordDecl *Record = cast_or_null<RecordDecl>(
5250 getDerived().TransformDecl(TL.getNameLoc(), T->getDecl()));
5251 if (Record != OldDecl)
5252 return Base::TransformRecordType(TLB, TL);
5253
5254 QualType Result = getDerived().RebuildRecordType(NewDecl);
5255 if (Result.isNull())
5256 return QualType();
5257
5258 RecordTypeLoc NewTL = TLB.push<RecordTypeLoc>(Result);
5259 NewTL.setNameLoc(TL.getNameLoc());
5260 return Result;
5261 }
5262 } IR{*this, PatternRec, NewRec};
5263
5264 TypeSourceInfo *NewSI = IR.TransformType(Function->getTypeSourceInfo());
5265 assert(NewSI && "Type Transform failed?");
5266 Function->setType(NewSI->getType());
5267 Function->setTypeSourceInfo(NewSI);
5268
5269 ParmVarDecl *Parm = Function->getParamDecl(0);
5270 TypeSourceInfo *NewParmSI = IR.TransformType(Parm->getTypeSourceInfo());
5271 assert(NewParmSI && "Type transformation failed.");
5272 Parm->setType(NewParmSI->getType());
5273 Parm->setTypeSourceInfo(NewParmSI);
5274 };
5275
5276 if (PatternDecl->isDefaulted()) {
5277 RebuildTypeSourceInfoForDefaultSpecialMembers();
5278 SetDeclDefaulted(Function, PatternDecl->getLocation());
5279 } else {
5280 NamedDecl *ND = Function;
5282 std::optional<ArrayRef<TemplateArgument>> Innermost;
5283 if (auto *Primary = Function->getPrimaryTemplate();
5284 Primary &&
5286 Function->getTemplateSpecializationKind() !=
5288 auto It = llvm::find_if(Primary->redecls(),
5289 [](const RedeclarableTemplateDecl *RTD) {
5290 return cast<FunctionTemplateDecl>(RTD)
5291 ->isCompatibleWithDefinition();
5292 });
5293 assert(It != Primary->redecls().end() &&
5294 "Should't get here without a definition");
5295 DC = (*It)->getLexicalDeclContext();
5296 Innermost.emplace(Function->getTemplateSpecializationArgs()->asArray());
5297 }
5299 Function, DC, /*Final=*/false, Innermost, false, PatternDecl);
5300
5301 // Substitute into the qualifier; we can get a substitution failure here
5302 // through evil use of alias templates.
5303 // FIXME: Is CurContext correct for this? Should we go to the (instantiation
5304 // of the) lexical context of the pattern?
5305 SubstQualifier(*this, PatternDecl, Function, TemplateArgs);
5306
5308
5309 // Enter the scope of this instantiation. We don't use
5310 // PushDeclContext because we don't have a scope.
5311 Sema::ContextRAII savedContext(*this, Function);
5312
5313 FPFeaturesStateRAII SavedFPFeatures(*this);
5315 FpPragmaStack.CurrentValue = FPOptionsOverride();
5316
5317 if (addInstantiatedParametersToScope(Function, PatternDecl, Scope,
5318 TemplateArgs))
5319 return;
5320
5321 StmtResult Body;
5322 if (PatternDecl->hasSkippedBody()) {
5324 Body = nullptr;
5325 } else {
5326 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Function)) {
5327 // If this is a constructor, instantiate the member initializers.
5328 InstantiateMemInitializers(Ctor, cast<CXXConstructorDecl>(PatternDecl),
5329 TemplateArgs);
5330
5331 // If this is an MS ABI dllexport default constructor, instantiate any
5332 // default arguments.
5334 Ctor->isDefaultConstructor()) {
5336 }
5337 }
5338
5339 // Instantiate the function body.
5340 Body = SubstStmt(Pattern, TemplateArgs);
5341
5342 if (Body.isInvalid())
5343 Function->setInvalidDecl();
5344 }
5345 // FIXME: finishing the function body while in an expression evaluation
5346 // context seems wrong. Investigate more.
5347 ActOnFinishFunctionBody(Function, Body.get(), /*IsInstantiation=*/true);
5348
5349 PerformDependentDiagnostics(PatternDecl, TemplateArgs);
5350
5351 if (auto *Listener = getASTMutationListener())
5352 Listener->FunctionDefinitionInstantiated(Function);
5353
5354 savedContext.pop();
5355 }
5356
5359
5360 // This class may have local implicit instantiations that need to be
5361 // instantiation within this scope.
5362 LocalInstantiations.perform();
5363 Scope.Exit();
5364 GlobalInstantiations.perform();
5365}
5366
5368 VarTemplateDecl *VarTemplate, VarDecl *FromVar,
5369 const TemplateArgumentList *PartialSpecArgs,
5370 const TemplateArgumentListInfo &TemplateArgsInfo,
5372 SourceLocation PointOfInstantiation, LateInstantiatedAttrVec *LateAttrs,
5373 LocalInstantiationScope *StartingScope) {
5374 if (FromVar->isInvalidDecl())
5375 return nullptr;
5376
5377 InstantiatingTemplate Inst(*this, PointOfInstantiation, FromVar);
5378 if (Inst.isInvalid())
5379 return nullptr;
5380
5381 // Instantiate the first declaration of the variable template: for a partial
5382 // specialization of a static data member template, the first declaration may
5383 // or may not be the declaration in the class; if it's in the class, we want
5384 // to instantiate a member in the class (a declaration), and if it's outside,
5385 // we want to instantiate a definition.
5386 //
5387 // If we're instantiating an explicitly-specialized member template or member
5388 // partial specialization, don't do this. The member specialization completely
5389 // replaces the original declaration in this case.
5390 bool IsMemberSpec = false;
5391 MultiLevelTemplateArgumentList MultiLevelList;
5392 if (auto *PartialSpec =
5393 dyn_cast<VarTemplatePartialSpecializationDecl>(FromVar)) {
5394 assert(PartialSpecArgs);
5395 IsMemberSpec = PartialSpec->isMemberSpecialization();
5396 MultiLevelList.addOuterTemplateArguments(
5397 PartialSpec, PartialSpecArgs->asArray(), /*Final=*/false);
5398 } else {
5399 assert(VarTemplate == FromVar->getDescribedVarTemplate());
5400 IsMemberSpec = VarTemplate->isMemberSpecialization();
5401 MultiLevelList.addOuterTemplateArguments(VarTemplate, Converted,
5402 /*Final=*/false);
5403 }
5404 if (!IsMemberSpec)
5405 FromVar = FromVar->getFirstDecl();
5406
5407 TemplateDeclInstantiator Instantiator(*this, FromVar->getDeclContext(),
5408 MultiLevelList);
5409
5410 // TODO: Set LateAttrs and StartingScope ...
5411
5412 return cast_or_null<VarTemplateSpecializationDecl>(
5414 VarTemplate, FromVar, TemplateArgsInfo, Converted));
5415}
5416
5418 VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl,
5419 const MultiLevelTemplateArgumentList &TemplateArgs) {
5420 assert(PatternDecl->isThisDeclarationADefinition() &&
5421 "don't have a definition to instantiate from");
5422
5423 // Do substitution on the type of the declaration
5424 TypeSourceInfo *DI =
5425 SubstType(PatternDecl->getTypeSourceInfo(), TemplateArgs,
5426 PatternDecl->getTypeSpecStartLoc(), PatternDecl->getDeclName());
5427 if (!DI)
5428 return nullptr;
5429
5430 // Update the type of this variable template specialization.
5431 VarSpec->setType(DI->getType());
5432
5433 // Convert the declaration into a definition now.
5434 VarSpec->setCompleteDefinition();
5435
5436 // Instantiate the initializer.
5437 InstantiateVariableInitializer(VarSpec, PatternDecl, TemplateArgs);
5438
5439 if (getLangOpts().OpenCL)
5440 deduceOpenCLAddressSpace(VarSpec);
5441
5442 return VarSpec;
5443}
5444
5446 VarDecl *NewVar, VarDecl *OldVar,
5447 const MultiLevelTemplateArgumentList &TemplateArgs,
5448 LateInstantiatedAttrVec *LateAttrs, DeclContext *Owner,
5449 LocalInstantiationScope *StartingScope,
5450 bool InstantiatingVarTemplate,
5451 VarTemplateSpecializationDecl *PrevDeclForVarTemplateSpecialization) {
5452 // Instantiating a partial specialization to produce a partial
5453 // specialization.
5454 bool InstantiatingVarTemplatePartialSpec =
5455 isa<VarTemplatePartialSpecializationDecl>(OldVar) &&
5456 isa<VarTemplatePartialSpecializationDecl>(NewVar);
5457 // Instantiating from a variable template (or partial specialization) to
5458 // produce a variable template specialization.
5459 bool InstantiatingSpecFromTemplate =
5460 isa<VarTemplateSpecializationDecl>(NewVar) &&
5461 (OldVar->getDescribedVarTemplate() ||
5462 isa<VarTemplatePartialSpecializationDecl>(OldVar));
5463
5464 // If we are instantiating a local extern declaration, the
5465 // instantiation belongs lexically to the containing function.
5466 // If we are instantiating a static data member defined
5467 // out-of-line, the instantiation will have the same lexical
5468 // context (which will be a namespace scope) as the template.
5469 if (OldVar->isLocalExternDecl()) {
5470 NewVar->setLocalExternDecl();
5471 NewVar->setLexicalDeclContext(Owner);
5472 } else if (OldVar->isOutOfLine())
5474 NewVar->setTSCSpec(OldVar->getTSCSpec());
5475 NewVar->setInitStyle(OldVar->getInitStyle());
5476 NewVar->setCXXForRangeDecl(OldVar->isCXXForRangeDecl());
5477 NewVar->setObjCForDecl(OldVar->isObjCForDecl());
5478 NewVar->setConstexpr(OldVar->isConstexpr());
5479 NewVar->setInitCapture(OldVar->isInitCapture());
5482 NewVar->setAccess(OldVar->getAccess());
5483
5484 if (!OldVar->isStaticDataMember()) {
5485 if (OldVar->isUsed(false))
5486 NewVar->setIsUsed();
5487 NewVar->setReferenced(OldVar->isReferenced());
5488 }
5489
5490 InstantiateAttrs(TemplateArgs, OldVar, NewVar, LateAttrs, StartingScope);
5491
5493 *this, NewVar->getDeclName(), NewVar->getLocation(),
5496 NewVar->isLocalExternDecl() ? RedeclarationKind::ForExternalRedeclaration
5498
5499 if (NewVar->isLocalExternDecl() && OldVar->getPreviousDecl() &&
5501 OldVar->getPreviousDecl()->getDeclContext()==OldVar->getDeclContext())) {
5502 // We have a previous declaration. Use that one, so we merge with the
5503 // right type.
5504 if (NamedDecl *NewPrev = FindInstantiatedDecl(
5505 NewVar->getLocation(), OldVar->getPreviousDecl(), TemplateArgs))
5506 Previous.addDecl(NewPrev);
5507 } else if (!isa<VarTemplateSpecializationDecl>(NewVar) &&
5508 OldVar->hasLinkage()) {
5509 LookupQualifiedName(Previous, NewVar->getDeclContext(), false);
5510 } else if (PrevDeclForVarTemplateSpecialization) {
5511 Previous.addDecl(PrevDeclForVarTemplateSpecialization);
5512 }
5514
5515 if (!InstantiatingVarTemplate) {
5516 NewVar->getLexicalDeclContext()->addHiddenDecl(NewVar);
5517 if (!NewVar->isLocalExternDecl() || !NewVar->getPreviousDecl())
5518 NewVar->getDeclContext()->makeDeclVisibleInContext(NewVar);
5519 }
5520
5521 if (!OldVar->isOutOfLine()) {
5522 if (NewVar->getDeclContext()->isFunctionOrMethod())
5524 }
5525
5526 // Link instantiations of static data members back to the template from
5527 // which they were instantiated.
5528 //
5529 // Don't do this when instantiating a template (we link the template itself
5530 // back in that case) nor when instantiating a static data member template
5531 // (that's not a member specialization).
5532 if (NewVar->isStaticDataMember() && !InstantiatingVarTemplate &&
5533 !InstantiatingSpecFromTemplate)
5536
5537 // If the pattern is an (in-class) explicit specialization, then the result
5538 // is also an explicit specialization.
5539 if (VarTemplateSpecializationDecl *OldVTSD =
5540 dyn_cast<VarTemplateSpecializationDecl>(OldVar)) {
5541 if (OldVTSD->getSpecializationKind() == TSK_ExplicitSpecialization &&
5542 !isa<VarTemplatePartialSpecializationDecl>(OldVTSD))
5543 cast<VarTemplateSpecializationDecl>(NewVar)->setSpecializationKind(
5545 }
5546
5547 // Forward the mangling number from the template to the instantiated decl.
5550
5551 // Figure out whether to eagerly instantiate the initializer.
5552 if (InstantiatingVarTemplate || InstantiatingVarTemplatePartialSpec) {
5553 // We're producing a template. Don't instantiate the initializer yet.
5554 } else if (NewVar->getType()->isUndeducedType()) {
5555 // We need the type to complete the declaration of the variable.
5556 InstantiateVariableInitializer(NewVar, OldVar, TemplateArgs);
5557 } else if (InstantiatingSpecFromTemplate ||
5558 (OldVar->isInline() && OldVar->isThisDeclarationADefinition() &&
5559 !NewVar->isThisDeclarationADefinition())) {
5560 // Delay instantiation of the initializer for variable template
5561 // specializations or inline static data members until a definition of the
5562 // variable is needed.
5563 } else {
5564 InstantiateVariableInitializer(NewVar, OldVar, TemplateArgs);
5565 }
5566
5567 // Diagnose unused local variables with dependent types, where the diagnostic
5568 // will have been deferred.
5569 if (!NewVar->isInvalidDecl() &&
5570 NewVar->getDeclContext()->isFunctionOrMethod() &&
5571 OldVar->getType()->isDependentType())
5572 DiagnoseUnusedDecl(NewVar);
5573}
5574
5576 VarDecl *Var, VarDecl *OldVar,
5577 const MultiLevelTemplateArgumentList &TemplateArgs) {
5579 L->VariableDefinitionInstantiated(Var);
5580
5581 // We propagate the 'inline' flag with the initializer, because it
5582 // would otherwise imply that the variable is a definition for a
5583 // non-static data member.
5584 if (OldVar->isInlineSpecified())
5585 Var->setInlineSpecified();
5586 else if (OldVar->isInline())
5587 Var->setImplicitlyInline();
5588
5589 if (OldVar->getInit()) {
5592
5597 // Instantiate the initializer.
5599
5600 {
5601 ContextRAII SwitchContext(*this, Var->getDeclContext());
5602 Init = SubstInitializer(OldVar->getInit(), TemplateArgs,
5603 OldVar->getInitStyle() == VarDecl::CallInit);
5604 }
5605
5606 if (!Init.isInvalid()) {
5607 Expr *InitExpr = Init.get();
5608
5609 if (Var->hasAttr<DLLImportAttr>() &&
5610 (!InitExpr ||
5611 !InitExpr->isConstantInitializer(getASTContext(), false))) {
5612 // Do not dynamically initialize dllimport variables.
5613 } else if (InitExpr) {
5614 bool DirectInit = OldVar->isDirectInit();
5615 AddInitializerToDecl(Var, InitExpr, DirectInit);
5616 } else
5618 } else {
5619 // FIXME: Not too happy about invalidating the declaration
5620 // because of a bogus initializer.
5621 Var->setInvalidDecl();
5622 }
5623 } else {
5624 // `inline` variables are a definition and declaration all in one; we won't
5625 // pick up an initializer from anywhere else.
5626 if (Var->isStaticDataMember() && !Var->isInline()) {
5627 if (!Var->isOutOfLine())
5628 return;
5629
5630 // If the declaration inside the class had an initializer, don't add
5631 // another one to the out-of-line definition.
5632 if (OldVar->getFirstDecl()->hasInit())
5633 return;
5634 }
5635
5636 // We'll add an initializer to a for-range declaration later.
5637 if (Var->isCXXForRangeDecl() || Var->isObjCForDecl())
5638 return;
5639
5641 }
5642
5643 if (getLangOpts().CUDA)
5645}
5646
5648 VarDecl *Var, bool Recursive,
5649 bool DefinitionRequired, bool AtEndOfTU) {
5650 if (Var->isInvalidDecl())
5651 return;
5652
5653 // Never instantiate an explicitly-specialized entity.
5656 if (TSK == TSK_ExplicitSpecialization)
5657 return;
5658
5659 // Find the pattern and the arguments to substitute into it.
5660 VarDecl *PatternDecl = Var->getTemplateInstantiationPattern();
5661 assert(PatternDecl && "no pattern for templated variable");
5662 MultiLevelTemplateArgumentList TemplateArgs =
5664
5666 dyn_cast<VarTemplateSpecializationDecl>(Var);
5667 if (VarSpec) {
5668 // If this is a static data member template, there might be an
5669 // uninstantiated initializer on the declaration. If so, instantiate
5670 // it now.
5671 //
5672 // FIXME: This largely duplicates what we would do below. The difference
5673 // is that along this path we may instantiate an initializer from an
5674 // in-class declaration of the template and instantiate the definition
5675 // from a separate out-of-class definition.
5676 if (PatternDecl->isStaticDataMember() &&
5677 (PatternDecl = PatternDecl->getFirstDecl())->hasInit() &&
5678 !Var->hasInit()) {
5679 // FIXME: Factor out the duplicated instantiation context setup/tear down
5680 // code here.
5681 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
5682 if (Inst.isInvalid() || Inst.isAlreadyInstantiating())
5683 return;
5685 "instantiating variable initializer");
5686
5687 // The instantiation is visible here, even if it was first declared in an
5688 // unimported module.
5690
5691 // If we're performing recursive template instantiation, create our own
5692 // queue of pending implicit instantiations that we will instantiate
5693 // later, while we're still within our own instantiation context.
5694 GlobalEagerInstantiationScope GlobalInstantiations(*this,
5695 /*Enabled=*/Recursive);
5696 LocalInstantiationScope Local(*this);
5697 LocalEagerInstantiationScope LocalInstantiations(*this);
5698
5699 // Enter the scope of this instantiation. We don't use
5700 // PushDeclContext because we don't have a scope.
5701 ContextRAII PreviousContext(*this, Var->getDeclContext());
5702 InstantiateVariableInitializer(Var, PatternDecl, TemplateArgs);
5703 PreviousContext.pop();
5704
5705 // This variable may have local implicit instantiations that need to be
5706 // instantiated within this scope.
5707 LocalInstantiations.perform();
5708 Local.Exit();
5709 GlobalInstantiations.perform();
5710 }
5711 } else {
5712 assert(Var->isStaticDataMember() && PatternDecl->isStaticDataMember() &&
5713 "not a static data member?");
5714 }
5715
5716 VarDecl *Def = PatternDecl->getDefinition(getASTContext());
5717
5718 // If we don't have a definition of the variable template, we won't perform
5719 // any instantiation. Rather, we rely on the user to instantiate this
5720 // definition (or provide a specialization for it) in another translation
5721 // unit.
5722 if (!Def && !DefinitionRequired) {
5724 PendingInstantiations.push_back(
5725 std::make_pair(Var, PointOfInstantiation));
5726 } else if (TSK == TSK_ImplicitInstantiation) {
5727 // Warn about missing definition at the end of translation unit.
5728 if (AtEndOfTU && !getDiagnostics().hasErrorOccurred() &&
5729 !getSourceManager().isInSystemHeader(PatternDecl->getBeginLoc())) {
5730 Diag(PointOfInstantiation, diag::warn_var_template_missing)
5731 << Var;
5732 Diag(PatternDecl->getLocation(), diag::note_forward_template_decl);
5734 Diag(PointOfInstantiation, diag::note_inst_declaration_hint) << Var;
5735 }
5736 return;
5737 }
5738 }
5739
5740 // FIXME: We need to track the instantiation stack in order to know which
5741 // definitions should be visible within this instantiation.
5742 // FIXME: Produce diagnostics when Var->getInstantiatedFromStaticDataMember().
5743 if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Var,
5744 /*InstantiatedFromMember*/false,
5745 PatternDecl, Def, TSK,
5746 /*Complain*/DefinitionRequired))
5747 return;
5748
5749 // C++11 [temp.explicit]p10:
5750 // Except for inline functions, const variables of literal types, variables
5751 // of reference types, [...] explicit instantiation declarations
5752 // have the effect of suppressing the implicit instantiation of the entity
5753 // to which they refer.
5754 //
5755 // FIXME: That's not exactly the same as "might be usable in constant
5756 // expressions", which only allows constexpr variables and const integral
5757 // types, not arbitrary const literal types.
5760 return;
5761
5762 // Make sure to pass the instantiated variable to the consumer at the end.
5763 struct PassToConsumerRAII {
5764 ASTConsumer &Consumer;
5765 VarDecl *Var;
5766
5767 PassToConsumerRAII(ASTConsumer &Consumer, VarDecl *Var)
5768 : Consumer(Consumer), Var(Var) { }
5769
5770 ~PassToConsumerRAII() {
5772 }
5773 } PassToConsumerRAII(Consumer, Var);
5774
5775 // If we already have a definition, we're done.
5776 if (VarDecl *Def = Var->getDefinition()) {
5777 // We may be explicitly instantiating something we've already implicitly
5778 // instantiated.
5780 PointOfInstantiation);
5781 return;
5782 }
5783
5784 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
5785 if (Inst.isInvalid() || Inst.isAlreadyInstantiating())
5786 return;
5788 "instantiating variable definition");
5789
5790 // If we're performing recursive template instantiation, create our own
5791 // queue of pending implicit instantiations that we will instantiate later,
5792 // while we're still within our own instantiation context.
5793 GlobalEagerInstantiationScope GlobalInstantiations(*this,
5794 /*Enabled=*/Recursive);
5795
5796 // Enter the scope of this instantiation. We don't use
5797 // PushDeclContext because we don't have a scope.
5798 ContextRAII PreviousContext(*this, Var->getDeclContext());
5799 LocalInstantiationScope Local(*this);
5800
5801 LocalEagerInstantiationScope LocalInstantiations(*this);
5802
5803 VarDecl *OldVar = Var;
5804 if (Def->isStaticDataMember() && !Def->isOutOfLine()) {
5805 // We're instantiating an inline static data member whose definition was
5806 // provided inside the class.
5807 InstantiateVariableInitializer(Var, Def, TemplateArgs);
5808 } else if (!VarSpec) {
5809 Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(),
5810 TemplateArgs));
5811 } else if (Var->isStaticDataMember() &&
5812 Var->getLexicalDeclContext()->isRecord()) {
5813 // We need to instantiate the definition of a static data member template,
5814 // and all we have is the in-class declaration of it. Instantiate a separate
5815 // declaration of the definition.
5816 TemplateDeclInstantiator Instantiator(*this, Var->getDeclContext(),
5817 TemplateArgs);
5818
5819 TemplateArgumentListInfo TemplateArgInfo;
5820 if (const ASTTemplateArgumentListInfo *ArgInfo =
5821 VarSpec->getTemplateArgsAsWritten()) {
5822 TemplateArgInfo.setLAngleLoc(ArgInfo->getLAngleLoc());
5823 TemplateArgInfo.setRAngleLoc(ArgInfo->getRAngleLoc());
5824 for (const TemplateArgumentLoc &Arg : ArgInfo->arguments())
5825 TemplateArgInfo.addArgument(Arg);
5826 }
5827
5828 Var = cast_or_null<VarDecl>(Instantiator.VisitVarTemplateSpecializationDecl(
5829 VarSpec->getSpecializedTemplate(), Def, TemplateArgInfo,
5830 VarSpec->getTemplateArgs().asArray(), VarSpec));
5831 if (Var) {
5832 llvm::PointerUnion<VarTemplateDecl *,
5836 PatternPtr.dyn_cast<VarTemplatePartialSpecializationDecl *>())
5837 cast<VarTemplateSpecializationDecl>(Var)->setInstantiationOf(
5838 Partial, &VarSpec->getTemplateInstantiationArgs());
5839
5840 // Attach the initializer.
5841 InstantiateVariableInitializer(Var, Def, TemplateArgs);
5842 }
5843 } else
5844 // Complete the existing variable's definition with an appropriately
5845 // substituted type and initializer.
5846 Var = CompleteVarTemplateSpecializationDecl(VarSpec, Def, TemplateArgs);
5847
5848 PreviousContext.pop();
5849
5850 if (Var) {
5851 PassToConsumerRAII.Var = Var;
5853 OldVar->getPointOfInstantiation());
5854 }
5855
5856 // This variable may have local implicit instantiations that need to be
5857 // instantiated within this scope.
5858 LocalInstantiations.perform();
5859 Local.Exit();
5860 GlobalInstantiations.perform();
5861}
5862
5863void
5865 const CXXConstructorDecl *Tmpl,
5866 const MultiLevelTemplateArgumentList &TemplateArgs) {
5867
5869 bool AnyErrors = Tmpl->isInvalidDecl();
5870
5871 // Instantiate all the initializers.
5872 for (const auto *Init : Tmpl->inits()) {
5873 // Only instantiate written initializers, let Sema re-construct implicit
5874 // ones.
5875 if (!Init->isWritten())
5876 continue;
5877
5878 SourceLocation EllipsisLoc;
5879
5880 if (Init->isPackExpansion()) {
5881 // This is a pack expansion. We should expand it now.
5882 TypeLoc BaseTL = Init->getTypeSourceInfo()->getTypeLoc();
5884 collectUnexpandedParameterPacks(BaseTL, Unexpanded);
5885 collectUnexpandedParameterPacks(Init->getInit(), Unexpanded);
5886 bool ShouldExpand = false;
5887 bool RetainExpansion = false;
5888 std::optional<unsigned> NumExpansions;
5889 if (CheckParameterPacksForExpansion(Init->getEllipsisLoc(),
5890 BaseTL.getSourceRange(),
5891 Unexpanded,
5892 TemplateArgs, ShouldExpand,
5893 RetainExpansion,
5894 NumExpansions)) {
5895 AnyErrors = true;
5896 New->setInvalidDecl();
5897 continue;
5898 }
5899 assert(ShouldExpand && "Partial instantiation of base initializer?");
5900
5901 // Loop over all of the arguments in the argument pack(s),
5902 for (unsigned I = 0; I != *NumExpansions; ++I) {
5903 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
5904
5905 // Instantiate the initializer.
5906 ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs,
5907 /*CXXDirectInit=*/true);
5908 if (TempInit.isInvalid()) {
5909 AnyErrors = true;
5910 break;
5911 }
5912
5913 // Instantiate the base type.
5914 TypeSourceInfo *BaseTInfo = SubstType(Init->getTypeSourceInfo(),
5915 TemplateArgs,
5916 Init->getSourceLocation(),
5917 New->getDeclName());
5918 if (!BaseTInfo) {
5919 AnyErrors = true;
5920 break;
5921 }
5922
5923 // Build the initializer.
5924 MemInitResult NewInit = BuildBaseInitializer(BaseTInfo->getType(),
5925 BaseTInfo, TempInit.get(),
5926 New->getParent(),
5927 SourceLocation());
5928 if (NewInit.isInvalid()) {
5929 AnyErrors = true;
5930 break;
5931 }
5932
5933 NewInits.push_back(NewInit.get());
5934 }
5935
5936 continue;
5937 }
5938
5939 // Instantiate the initializer.
5940 ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs,
5941 /*CXXDirectInit=*/true);
5942 if (TempInit.isInvalid()) {
5943 AnyErrors = true;
5944 continue;
5945 }
5946
5947 MemInitResult NewInit;
5948 if (Init->isDelegatingInitializer() || Init->isBaseInitializer()) {
5949 TypeSourceInfo *TInfo = SubstType(Init->getTypeSourceInfo(),
5950 TemplateArgs,
5951 Init->getSourceLocation(),
5952 New->getDeclName());
5953 if (!TInfo) {
5954 AnyErrors = true;
5955 New->setInvalidDecl();
5956 continue;
5957 }
5958
5959 if (Init->isBaseInitializer())
5960 NewInit = BuildBaseInitializer(TInfo->getType(), TInfo, TempInit.get(),
5961 New->getParent(), EllipsisLoc);
5962 else
5963 NewInit = BuildDelegatingInitializer(TInfo, TempInit.get(),
5964 cast<CXXRecordDecl>(CurContext->getParent()));
5965 } else if (Init->isMemberInitializer()) {
5966 FieldDecl *Member = cast_or_null<FieldDecl>(FindInstantiatedDecl(
5967 Init->getMemberLocation(),
5968 Init->getMember(),
5969 TemplateArgs));
5970 if (!Member) {
5971 AnyErrors = true;
5972 New->setInvalidDecl();
5973 continue;
5974 }
5975
5976 NewInit = BuildMemberInitializer(Member, TempInit.get(),
5977 Init->getSourceLocation());
5978 } else if (Init->isIndirectMemberInitializer()) {
5979 IndirectFieldDecl *IndirectMember =
5980 cast_or_null<IndirectFieldDecl>(FindInstantiatedDecl(
5981 Init->getMemberLocation(),
5982 Init->getIndirectMember(), TemplateArgs));
5983
5984 if (!IndirectMember) {
5985 AnyErrors = true;
5986 New->setInvalidDecl();
5987 continue;
5988 }
5989
5990 NewInit = BuildMemberInitializer(IndirectMember, TempInit.get(),
5991 Init->getSourceLocation());
5992 }
5993
5994 if (NewInit.isInvalid()) {
5995 AnyErrors = true;
5996 New->setInvalidDecl();
5997 } else {
5998 NewInits.push_back(NewInit.get());
5999 }
6000 }
6001
6002 // Assign all the initializers to the new constructor.
6004 /*FIXME: ColonLoc */
6006 NewInits,
6007 AnyErrors);
6008}
6009
6010// TODO: this could be templated if the various decl types used the
6011// same method name.
6013 ClassTemplateDecl *Instance) {
6014 Pattern = Pattern->getCanonicalDecl();
6015
6016 do {
6017 Instance = Instance->getCanonicalDecl();
6018 if (Pattern == Instance) return true;
6019 Instance = Instance->getInstantiatedFromMemberTemplate();
6020 } while (Instance);
6021
6022 return false;
6023}
6024
6026 FunctionTemplateDecl *Instance) {
6027 Pattern = Pattern->getCanonicalDecl();
6028
6029 do {
6030 Instance = Instance->getCanonicalDecl();
6031 if (Pattern == Instance) return true;
6032 Instance = Instance->getInstantiatedFromMemberTemplate();
6033 } while (Instance);
6034
6035 return false;
6036}
6037
6038static bool
6041 Pattern
6042 = cast<ClassTemplatePartialSpecializationDecl>(Pattern->getCanonicalDecl());
6043 do {
6044 Instance = cast<ClassTemplatePartialSpecializationDecl>(
6045 Instance->getCanonicalDecl());
6046 if (Pattern == Instance)
6047 return true;
6048 Instance = Instance->getInstantiatedFromMember();
6049 } while (Instance);
6050
6051 return false;
6052}
6053
6055 CXXRecordDecl *Instance) {
6056 Pattern = Pattern->getCanonicalDecl();
6057
6058 do {
6059 Instance = Instance->getCanonicalDecl();
6060 if (Pattern == Instance) return true;
6061 Instance = Instance->getInstantiatedFromMemberClass();
6062 } while (Instance);
6063
6064 return false;
6065}
6066
6067static bool isInstantiationOf(FunctionDecl *Pattern,
6068 FunctionDecl *Instance) {
6069 Pattern = Pattern->getCanonicalDecl();
6070
6071 do {
6072 Instance = Instance->getCanonicalDecl();
6073 if (Pattern == Instance) return true;
6074 Instance = Instance->getInstantiatedFromMemberFunction();
6075 } while (Instance);
6076
6077 return false;
6078}
6079
6080static bool isInstantiationOf(EnumDecl *Pattern,
6081 EnumDecl *Instance) {
6082 Pattern = Pattern->getCanonicalDecl();
6083
6084 do {
6085 Instance = Instance->getCanonicalDecl();
6086 if (Pattern == Instance) return true;
6087 Instance = Instance->getInstantiatedFromMemberEnum();
6088 } while (Instance);
6089
6090 return false;
6091}
6092
6094 UsingShadowDecl *Instance,
6095 ASTContext &C) {
6096 return declaresSameEntity(C.getInstantiatedFromUsingShadowDecl(Instance),
6097 Pattern);
6098}
6099
6100static bool isInstantiationOf(UsingDecl *Pattern, UsingDecl *Instance,
6101 ASTContext &C) {
6102 return declaresSameEntity(C.getInstantiatedFromUsingDecl(Instance), Pattern);
6103}
6104
6105template<typename T>
6107 ASTContext &Ctx) {
6108 // An unresolved using declaration can instantiate to an unresolved using
6109 // declaration, or to a using declaration or a using declaration pack.
6110 //
6111 // Multiple declarations can claim to be instantiated from an unresolved
6112 // using declaration if it's a pack expansion. We want the UsingPackDecl
6113 // in that case, not the individual UsingDecls within the pack.
6114 bool OtherIsPackExpansion;
6115 NamedDecl *OtherFrom;
6116 if (auto *OtherUUD = dyn_cast<T>(Other)) {
6117 OtherIsPackExpansion = OtherUUD->isPackExpansion();
6118 OtherFrom = Ctx.getInstantiatedFromUsingDecl(OtherUUD);
6119 } else if (auto *OtherUPD = dyn_cast<UsingPackDecl>(Other)) {
6120 OtherIsPackExpansion = true;
6121 OtherFrom = OtherUPD->getInstantiatedFromUsingDecl();
6122 } else if (auto *OtherUD = dyn_cast<UsingDecl>(Other)) {
6123 OtherIsPackExpansion = false;
6124 OtherFrom = Ctx.getInstantiatedFromUsingDecl(OtherUD);
6125 } else {
6126 return false;
6127 }
6128 return Pattern->isPackExpansion() == OtherIsPackExpansion &&
6129 declaresSameEntity(OtherFrom, Pattern);
6130}
6131
6133 VarDecl *Instance) {
6134 assert(Instance->isStaticDataMember());
6135
6136 Pattern = Pattern->getCanonicalDecl();
6137
6138 do {
6139 Instance = Instance->getCanonicalDecl();
6140 if (Pattern == Instance) return true;
6141 Instance = Instance->getInstantiatedFromStaticDataMember();
6142 } while (Instance);
6143
6144 return false;
6145}
6146
6147// Other is the prospective instantiation
6148// D is the prospective pattern
6150 if (auto *UUD = dyn_cast<UnresolvedUsingTypenameDecl>(D))
6152
6153 if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(D))
6155
6156 if (D->getKind() != Other->getKind())
6157 return false;
6158
6159 if (auto *Record = dyn_cast<CXXRecordDecl>(Other))
6160 return isInstantiationOf(cast<CXXRecordDecl>(D), Record);
6161
6162 if (auto *Function = dyn_cast<FunctionDecl>(Other))
6163 return isInstantiationOf(cast<FunctionDecl>(D), Function);
6164
6165 if (auto *Enum = dyn_cast<EnumDecl>(Other))
6166 return isInstantiationOf(cast<EnumDecl>(D), Enum);
6167
6168 if (auto *Var = dyn_cast<VarDecl>(Other))
6169 if (Var->isStaticDataMember())
6170 return isInstantiationOfStaticDataMember(cast<VarDecl>(D), Var);
6171
6172 if (auto *Temp = dyn_cast<ClassTemplateDecl>(Other))
6173 return isInstantiationOf(cast<ClassTemplateDecl>(D), Temp);
6174
6175 if (auto *Temp = dyn_cast<FunctionTemplateDecl>(Other))
6176 return isInstantiationOf(cast<FunctionTemplateDecl>(D), Temp);
6177
6178 if (auto *PartialSpec =
6179 dyn_cast<ClassTemplatePartialSpecializationDecl>(Other))
6180 return isInstantiationOf(cast<ClassTemplatePartialSpecializationDecl>(D),
6181 PartialSpec);
6182
6183 if (auto *Field = dyn_cast<FieldDecl>(Other)) {
6184 if (!Field->getDeclName()) {
6185 // This is an unnamed field.
6187 cast<FieldDecl>(D));
6188 }
6189 }
6190
6191 if (auto *Using = dyn_cast<UsingDecl>(Other))
6192 return isInstantiationOf(cast<UsingDecl>(D), Using, Ctx);
6193
6194 if (auto *Shadow = dyn_cast<UsingShadowDecl>(Other))
6195 return isInstantiationOf(cast<UsingShadowDecl>(D), Shadow, Ctx);
6196
6197 return D->getDeclName() &&
6198 D->getDeclName() == cast<NamedDecl>(Other)->getDeclName();
6199}
6200
6201template<typename ForwardIterator>
6203 NamedDecl *D,
6204 ForwardIterator first,
6205 ForwardIterator last) {
6206 for (; first != last; ++first)
6207 if (isInstantiationOf(Ctx, D, *first))
6208 return cast<NamedDecl>(*first);
6209
6210 return nullptr;
6211}
6212
6214 const MultiLevelTemplateArgumentList &TemplateArgs) {
6215 if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) {
6216 Decl* ID = FindInstantiatedDecl(Loc, D, TemplateArgs, true);
6217 return cast_or_null<DeclContext>(ID);
6218 } else return DC;
6219}
6220
6221/// Determine whether the given context is dependent on template parameters at
6222/// level \p Level or below.
6223///
6224/// Sometimes we only substitute an inner set of template arguments and leave
6225/// the outer templates alone. In such cases, contexts dependent only on the
6226/// outer levels are not effectively dependent.
6227static bool isDependentContextAtLevel(DeclContext *DC, unsigned Level) {
6228 if (!DC->isDependentContext())
6229 return false;
6230 if (!Level)
6231 return true;
6232 return cast<Decl>(DC)->getTemplateDepth() > Level;
6233}
6234
6236 const MultiLevelTemplateArgumentList &TemplateArgs,
6237 bool FindingInstantiatedContext) {
6238 DeclContext *ParentDC = D->getDeclContext();
6239 // Determine whether our parent context depends on any of the template
6240 // arguments we're currently substituting.
6241 bool ParentDependsOnArgs = isDependentContextAtLevel(
6242 ParentDC, TemplateArgs.getNumRetainedOuterLevels());
6243 // FIXME: Parameters of pointer to functions (y below) that are themselves
6244 // parameters (p below) can have their ParentDC set to the translation-unit
6245 // - thus we can not consistently check if the ParentDC of such a parameter
6246 // is Dependent or/and a FunctionOrMethod.
6247 // For e.g. this code, during Template argument deduction tries to
6248 // find an instantiated decl for (T y) when the ParentDC for y is
6249 // the translation unit.
6250 // e.g. template <class T> void Foo(auto (*p)(T y) -> decltype(y())) {}
6251 // float baz(float(*)()) { return 0.0; }
6252 // Foo(baz);
6253 // The better fix here is perhaps to ensure that a ParmVarDecl, by the time
6254 // it gets here, always has a FunctionOrMethod as its ParentDC??
6255 // For now:
6256 // - as long as we have a ParmVarDecl whose parent is non-dependent and
6257 // whose type is not instantiation dependent, do nothing to the decl
6258 // - otherwise find its instantiated decl.
6259 if (isa<ParmVarDecl>(D) && !ParentDependsOnArgs &&
6260 !cast<ParmVarDecl>(D)->getType()->isInstantiationDependentType())
6261 return D;
6262 if (isa<ParmVarDecl>(D) || isa<NonTypeTemplateParmDecl>(D) ||
6263 isa<TemplateTypeParmDecl>(D) || isa<TemplateTemplateParmDecl>(D) ||
6264 (ParentDependsOnArgs && (ParentDC->isFunctionOrMethod() ||
6265 isa<OMPDeclareReductionDecl>(ParentDC) ||
6266 isa<OMPDeclareMapperDecl>(ParentDC))) ||
6267 (isa<CXXRecordDecl>(D) && cast<CXXRecordDecl>(D)->isLambda() &&
6268 cast<CXXRecordDecl>(D)->getTemplateDepth() >
6269 TemplateArgs.getNumRetainedOuterLevels())) {
6270 // D is a local of some kind. Look into the map of local
6271 // declarations to their instantiations.
6274 if (Decl *FD = Found->dyn_cast<Decl *>()) {
6275 if (auto *BD = dyn_cast<BindingDecl>(FD);
6276 BD && BD->isParameterPack() &&
6278 auto *DRE = cast<DeclRefExpr>(
6279 BD->getBindingPackExprs()[ArgumentPackSubstitutionIndex]);
6280 return cast<NamedDecl>(DRE->getDecl());
6281 }
6282 return cast<NamedDecl>(FD);
6283 }
6284
6285 int PackIdx = ArgumentPackSubstitutionIndex;
6286 assert(PackIdx != -1 &&
6287 "found declaration pack but not pack expanding");
6288 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
6289 return cast<NamedDecl>((*cast<DeclArgumentPack *>(*Found))[PackIdx]);
6290 }
6291 }
6292
6293 // If we're performing a partial substitution during template argument
6294 // deduction, we may not have values for template parameters yet. They
6295 // just map to themselves.
6296 if (isa<NonTypeTemplateParmDecl>(D) || isa<TemplateTypeParmDecl>(D) ||
6297 isa<TemplateTemplateParmDecl>(D))
6298 return D;
6299
6300 if (D->isInvalidDecl())
6301 return nullptr;
6302
6303 // Normally this function only searches for already instantiated declaration
6304 // however we have to make an exclusion for local types used before
6305 // definition as in the code:
6306 //
6307 // template<typename T> void f1() {
6308 // void g1(struct x1);
6309 // struct x1 {};
6310 // }
6311 //
6312 // In this case instantiation of the type of 'g1' requires definition of
6313 // 'x1', which is defined later. Error recovery may produce an enum used
6314 // before definition. In these cases we need to instantiate relevant
6315 // declarations here.
6316 bool NeedInstantiate = false;
6317 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
6318 NeedInstantiate = RD->isLocalClass();
6319 else if (isa<TypedefNameDecl>(D) &&
6320 isa<CXXDeductionGuideDecl>(D->getDeclContext()))
6321 NeedInstantiate = true;
6322 else
6323 NeedInstantiate = isa<EnumDecl>(D);
6324 if (NeedInstantiate) {
6325 Decl *Inst = SubstDecl(D, CurContext, TemplateArgs);
6327 return cast<TypeDecl>(Inst);
6328 }
6329
6330 // If we didn't find the decl, then we must have a label decl that hasn't
6331 // been found yet. Lazily instantiate it and return it now.
6332 assert(isa<LabelDecl>(D));
6333
6334 Decl *Inst = SubstDecl(D, CurContext, TemplateArgs);
6335 assert(Inst && "Failed to instantiate label??");
6336
6338 return cast<LabelDecl>(Inst);
6339 }
6340
6341 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
6342 if (!Record->isDependentContext())
6343 return D;
6344
6345 // Determine whether this record is the "templated" declaration describing
6346 // a class template or class template specialization.
6347 ClassTemplateDecl *ClassTemplate = Record->getDescribedClassTemplate();
6348 if (ClassTemplate)
6349 ClassTemplate = ClassTemplate->getCanonicalDecl();
6350 else if (ClassTemplateSpecializationDecl *Spec =
6351 dyn_cast<ClassTemplateSpecializationDecl>(Record))
6352 ClassTemplate = Spec->getSpecializedTemplate()->getCanonicalDecl();
6353
6354 // Walk the current context to find either the record or an instantiation of
6355 // it.
6356 DeclContext *DC = CurContext;
6357 while (!DC->isFileContext()) {
6358 // If we're performing substitution while we're inside the template
6359 // definition, we'll find our own context. We're done.
6360 if (DC->Equals(Record))
6361 return Record;
6362
6363 if (CXXRecordDecl *InstRecord = dyn_cast<CXXRecordDecl>(DC)) {
6364 // Check whether we're in the process of instantiating a class template
6365 // specialization of the template we're mapping.
6367 = dyn_cast<ClassTemplateSpecializationDecl>(InstRecord)){
6368 ClassTemplateDecl *SpecTemplate = InstSpec->getSpecializedTemplate();
6369 if (ClassTemplate && isInstantiationOf(ClassTemplate, SpecTemplate))
6370 return InstRecord;
6371 }
6372
6373 // Check whether we're in the process of instantiating a member class.
6374 if (isInstantiationOf(Record, InstRecord))
6375 return InstRecord;
6376 }
6377
6378 // Move to the outer template scope.
6379 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC)) {
6380 if (FD->getFriendObjectKind() &&
6382 DC = FD->getLexicalDeclContext();
6383 continue;
6384 }
6385 // An implicit deduction guide acts as if it's within the class template
6386 // specialization described by its name and first N template params.
6387 auto *Guide = dyn_cast<CXXDeductionGuideDecl>(FD);
6388 if (Guide && Guide->isImplicit()) {
6389 TemplateDecl *TD = Guide->getDeducedTemplate();
6390 // Convert the arguments to an "as-written" list.
6392 for (TemplateArgument Arg : TemplateArgs.getInnermost().take_front(
6393 TD->getTemplateParameters()->size())) {
6394 ArrayRef<TemplateArgument> Unpacked(Arg);
6395 if (Arg.getKind() == TemplateArgument::Pack)
6396 Unpacked = Arg.pack_elements();
6397 for (TemplateArgument UnpackedArg : Unpacked)
6398 Args.addArgument(
6399 getTrivialTemplateArgumentLoc(UnpackedArg, QualType(), Loc));
6400 }
6402 // We may get a non-null type with errors, in which case
6403 // `getAsCXXRecordDecl` will return `nullptr`. For instance, this
6404 // happens when one of the template arguments is an invalid
6405 // expression. We return early to avoid triggering the assertion
6406 // about the `CodeSynthesisContext`.
6407 if (T.isNull() || T->containsErrors())
6408 return nullptr;
6409 CXXRecordDecl *SubstRecord = T->getAsCXXRecordDecl();
6410
6411 if (!SubstRecord) {
6412 // T can be a dependent TemplateSpecializationType when performing a
6413 // substitution for building a deduction guide or for template
6414 // argument deduction in the process of rebuilding immediate
6415 // expressions. (Because the default argument that involves a lambda
6416 // is untransformed and thus could be dependent at this point.)
6418 CodeSynthesisContexts.back().Kind ==
6420 // Return a nullptr as a sentinel value, we handle it properly in
6421 // the TemplateInstantiator::TransformInjectedClassNameType
6422 // override, which we transform it to a TemplateSpecializationType.
6423 return nullptr;
6424 }
6425 // Check that this template-id names the primary template and not a
6426 // partial or explicit specialization. (In the latter cases, it's
6427 // meaningless to attempt to find an instantiation of D within the
6428 // specialization.)
6429 // FIXME: The standard doesn't say what should happen here.
6430 if (FindingInstantiatedContext &&
6432 Loc, cast<ClassTemplateSpecializationDecl>(SubstRecord))) {
6433 Diag(Loc, diag::err_specialization_not_primary_template)
6434 << T << (SubstRecord->getTemplateSpecializationKind() ==
6436 return nullptr;
6437 }
6438 DC = SubstRecord;
6439 continue;
6440 }
6441 }
6442
6443 DC = DC->getParent();
6444 }
6445
6446 // Fall through to deal with other dependent record types (e.g.,
6447 // anonymous unions in class templates).
6448 }
6449
6450 if (!ParentDependsOnArgs)
6451 return D;
6452
6453 ParentDC = FindInstantiatedContext(Loc, ParentDC, TemplateArgs);
6454 if (!ParentDC)
6455 return nullptr;
6456
6457 if (ParentDC != D->getDeclContext()) {
6458 // We performed some kind of instantiation in the parent context,
6459 // so now we need to look into the instantiated parent context to
6460 // find the instantiation of the declaration D.
6461
6462 // If our context used to be dependent, we may need to instantiate
6463 // it before performing lookup into that context.
6464 bool IsBeingInstantiated = false;
6465 if (CXXRecordDecl *Spec = dyn_cast<CXXRecordDecl>(ParentDC)) {
6466 if (!Spec->isDependentContext()) {
6468 const RecordType *Tag = T->getAs<RecordType>();
6469 assert(Tag && "type of non-dependent record is not a RecordType");
6470 if (Tag->isBeingDefined())
6471 IsBeingInstantiated = true;
6472 if (!Tag->isBeingDefined() &&
6473 RequireCompleteType(Loc, T, diag::err_incomplete_type))
6474 return nullptr;
6475
6476 ParentDC = Tag->getDecl();
6477 }
6478 }
6479
6480 NamedDecl *Result = nullptr;
6481 // FIXME: If the name is a dependent name, this lookup won't necessarily
6482 // find it. Does that ever matter?
6483 if (auto Name = D->getDeclName()) {
6484 DeclarationNameInfo NameInfo(Name, D->getLocation());
6485 DeclarationNameInfo NewNameInfo =
6486 SubstDeclarationNameInfo(NameInfo, TemplateArgs);
6487 Name = NewNameInfo.getName();
6488 if (!Name)
6489 return nullptr;
6490 DeclContext::lookup_result Found = ParentDC->lookup(Name);
6491
6492 Result = findInstantiationOf(Context, D, Found.begin(), Found.end());
6493 } else {
6494 // Since we don't have a name for the entity we're looking for,
6495 // our only option is to walk through all of the declarations to
6496 // find that name. This will occur in a few cases:
6497 //
6498 // - anonymous struct/union within a template
6499 // - unnamed class/struct/union/enum within a template
6500 //
6501 // FIXME: Find a better way to find these instantiations!
6503 ParentDC->decls_begin(),
6504 ParentDC->decls_end());
6505 }
6506
6507 if (!Result) {
6508 if (isa<UsingShadowDecl>(D)) {
6509 // UsingShadowDecls can instantiate to nothing because of using hiding.
6510 } else if (hasUncompilableErrorOccurred()) {
6511 // We've already complained about some ill-formed code, so most likely
6512 // this declaration failed to instantiate. There's no point in
6513 // complaining further, since this is normal in invalid code.
6514 // FIXME: Use more fine-grained 'invalid' tracking for this.
6515 } else if (IsBeingInstantiated) {
6516 // The class in which this member exists is currently being
6517 // instantiated, and we haven't gotten around to instantiating this
6518 // member yet. This can happen when the code uses forward declarations
6519 // of member classes, and introduces ordering dependencies via
6520 // template instantiation.
6521 Diag(Loc, diag::err_member_not_yet_instantiated)
6522 << D->getDeclName()
6523 << Context.getTypeDeclType(cast<CXXRecordDecl>(ParentDC));
6524 Diag(D->getLocation(), diag::note_non_instantiated_member_here);
6525 } else if (EnumConstantDecl *ED = dyn_cast<EnumConstantDecl>(D)) {
6526 // This enumeration constant was found when the template was defined,
6527 // but can't be found in the instantiation. This can happen if an
6528 // unscoped enumeration member is explicitly specialized.
6529 EnumDecl *Enum = cast<EnumDecl>(ED->getLexicalDeclContext());
6530 EnumDecl *Spec = cast<EnumDecl>(FindInstantiatedDecl(Loc, Enum,
6531 TemplateArgs));
6532 assert(Spec->getTemplateSpecializationKind() ==
6534 Diag(Loc, diag::err_enumerator_does_not_exist)
6535 << D->getDeclName()
6536 << Context.getTypeDeclType(cast<TypeDecl>(Spec->getDeclContext()));
6537 Diag(Spec->getLocation(), diag::note_enum_specialized_here)
6538 << Context.getTypeDeclType(Spec);
6539 } else {
6540 // We should have found something, but didn't.
6541 llvm_unreachable("Unable to find instantiation of declaration!");
6542 }
6543 }
6544
6545 D = Result;
6546 }
6547
6548 return D;
6549}
6550
6552 std::deque<PendingImplicitInstantiation> delayedPCHInstantiations;
6553 while (!PendingLocalImplicitInstantiations.empty() ||
6554 (!LocalOnly && !PendingInstantiations.empty())) {
6556
6558 Inst = PendingInstantiations.front();
6559 PendingInstantiations.pop_front();
6560 } else {
6563 }
6564
6565 // Instantiate function definitions
6566 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) {
6567 bool DefinitionRequired = Function->getTemplateSpecializationKind() ==
6569 if (Function->isMultiVersion()) {
6571 Function, [this, Inst, DefinitionRequired](FunctionDecl *CurFD) {
6572 InstantiateFunctionDefinition(/*FIXME:*/ Inst.second, CurFD, true,
6573 DefinitionRequired, true);
6574 if (CurFD->isDefined())
6575 CurFD->setInstantiationIsPending(false);
6576 });
6577 } else {
6578 InstantiateFunctionDefinition(/*FIXME:*/ Inst.second, Function, true,
6579 DefinitionRequired, true);
6580 if (Function->isDefined())
6581 Function->setInstantiationIsPending(false);
6582 }
6583 // Definition of a PCH-ed template declaration may be available only in the TU.
6584 if (!LocalOnly && LangOpts.PCHInstantiateTemplates &&
6585 TUKind == TU_Prefix && Function->instantiationIsPending())
6586 delayedPCHInstantiations.push_back(Inst);
6587 continue;
6588 }
6589
6590 // Instantiate variable definitions
6591 VarDecl *Var = cast<VarDecl>(Inst.first);
6592
6593 assert((Var->isStaticDataMember() ||
6594 isa<VarTemplateSpecializationDecl>(Var)) &&
6595 "Not a static data member, nor a variable template"
6596 " specialization?");
6597
6598 // Don't try to instantiate declarations if the most recent redeclaration
6599 // is invalid.
6600 if (Var->getMostRecentDecl()->isInvalidDecl())
6601 continue;
6602
6603 // Check if the most recent declaration has changed the specialization kind
6604 // and removed the need for implicit instantiation.
6605 switch (Var->getMostRecentDecl()
6607 case TSK_Undeclared:
6608 llvm_unreachable("Cannot instantitiate an undeclared specialization.");
6611 continue; // No longer need to instantiate this type.
6613 // We only need an instantiation if the pending instantiation *is* the
6614 // explicit instantiation.
6615 if (Var != Var->getMostRecentDecl())
6616 continue;
6617 break;
6619 break;
6620 }
6621
6623 "instantiating variable definition");
6624 bool DefinitionRequired = Var->getTemplateSpecializationKind() ==
6626
6627 // Instantiate static data member definitions or variable template
6628 // specializations.
6629 InstantiateVariableDefinition(/*FIXME:*/ Inst.second, Var, true,
6630 DefinitionRequired, true);
6631 }
6632
6633 if (!LocalOnly && LangOpts.PCHInstantiateTemplates)
6634 PendingInstantiations.swap(delayedPCHInstantiations);
6635}
6636
6638 const MultiLevelTemplateArgumentList &TemplateArgs) {
6639 for (auto *DD : Pattern->ddiags()) {
6640 switch (DD->getKind()) {
6642 HandleDependentAccessCheck(*DD, TemplateArgs);
6643 break;
6644 }
6645 }
6646}
Defines the clang::ASTContext interface.
NodeId Parent
Definition: ASTDiff.cpp:191
This file provides some common utility functions for processing Lambda related AST Constructs.
StringRef P
const Decl * D
Expr * E
Defines the C++ template declaration subclasses.
Defines the clang::Expr interface and subclasses for C++ expressions.
llvm::MachO::Record Record
Definition: MachO.h:31
This file declares semantic analysis functions specific to AMDGPU.
This file declares semantic analysis for CUDA constructs.
This file declares semantic analysis for HLSL constructs.
SourceLocation Loc
Definition: SemaObjC.cpp:759
This file declares semantic analysis for Objective-C.
This file declares semantic analysis for OpenMP constructs and clauses.
This file declares semantic analysis functions specific to Swift.
static void instantiateDependentAMDGPUWavesPerEUAttr(Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, const AMDGPUWavesPerEUAttr &Attr, Decl *New)
static NamedDecl * findInstantiationOf(ASTContext &Ctx, NamedDecl *D, ForwardIterator first, ForwardIterator last)
static void instantiateDependentAMDGPUMaxNumWorkGroupsAttr(Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, const AMDGPUMaxNumWorkGroupsAttr &Attr, Decl *New)
static void instantiateDependentAMDGPUFlatWorkGroupSizeAttr(Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, const AMDGPUFlatWorkGroupSizeAttr &Attr, Decl *New)
static void instantiateDependentDiagnoseIfAttr(Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, const DiagnoseIfAttr *DIA, const Decl *Tmpl, FunctionDecl *New)
static QualType adjustFunctionTypeForInstantiation(ASTContext &Context, FunctionDecl *D, TypeSourceInfo *TInfo)
Adjust the given function type for an instantiation of the given declaration, to cope with modificati...
static bool isRelevantAttr(Sema &S, const Decl *D, const Attr *A)
Determine whether the attribute A might be relevant to the declaration D.
static bool isDependentContextAtLevel(DeclContext *DC, unsigned Level)
Determine whether the given context is dependent on template parameters at level Level or below.
static void instantiateDependentModeAttr(Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, const ModeAttr &Attr, Decl *New)
static void instantiateDependentCUDALaunchBoundsAttr(Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, const CUDALaunchBoundsAttr &Attr, Decl *New)
static bool isDeclWithinFunction(const Decl *D)
static void instantiateDependentAssumeAlignedAttr(Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, const AssumeAlignedAttr *Aligned, Decl *New)
static bool SubstQualifier(Sema &SemaRef, const DeclT *OldDecl, DeclT *NewDecl, const MultiLevelTemplateArgumentList &TemplateArgs)
static void collectUnexpandedParameterPacks(Sema &S, TemplateParameterList *Params, SmallVectorImpl< UnexpandedParameterPack > &Unexpanded)
static DeclT * getPreviousDeclForInstantiation(DeclT *D)
Get the previous declaration of a declaration for the purposes of template instantiation.
static Expr * instantiateDependentFunctionAttrCondition(Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, const Attr *A, Expr *OldCond, const Decl *Tmpl, FunctionDecl *New)
static bool isInstantiationOf(ClassTemplateDecl *Pattern, ClassTemplateDecl *Instance)
static void instantiateDependentHLSLParamModifierAttr(Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, const HLSLParamModifierAttr *Attr, Decl *New)
static void instantiateDependentAllocAlignAttr(Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, const AllocAlignAttr *Align, Decl *New)
static bool isInstantiationOfStaticDataMember(VarDecl *Pattern, VarDecl *Instance)
static void instantiateOMPDeclareSimdDeclAttr(Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, const OMPDeclareSimdDeclAttr &Attr, Decl *New)
Instantiation of 'declare simd' attribute and its arguments.
static void instantiateDependentSYCLKernelAttr(Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, const SYCLKernelAttr &Attr, Decl *New)
static void instantiateDependentAlignValueAttr(Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, const AlignValueAttr *Aligned, Decl *New)
static void instantiateDependentAlignedAttr(Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, const AlignedAttr *Aligned, Decl *New, bool IsPackExpansion)
static void instantiateOMPDeclareVariantAttr(Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, const OMPDeclareVariantAttr &Attr, Decl *New)
Instantiation of 'declare variant' attribute and its arguments.
static void instantiateDependentEnableIfAttr(Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, const EnableIfAttr *EIA, const Decl *Tmpl, FunctionDecl *New)
static void instantiateDependentAnnotationAttr(Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, const AnnotateAttr *Attr, Decl *New)
static Sema::RetainOwnershipKind attrToRetainOwnershipKind(const Attr *A)
static bool isInstantiationOfUnresolvedUsingDecl(T *Pattern, Decl *Other, ASTContext &Ctx)
static bool isInvalid(LocType Loc, bool *Invalid)
Defines the SourceManager interface.
Defines the clang::TypeLoc interface and its subclasses.
StateNode * Previous
#define bool
Definition: amdgpuintrin.h:20
ASTConsumer - This is an abstract interface that should be implemented by clients that read ASTs.
Definition: ASTConsumer.h:34
virtual bool HandleTopLevelDecl(DeclGroupRef D)
HandleTopLevelDecl - Handle the specified top-level declaration.
Definition: ASTConsumer.cpp:18
virtual void HandleCXXStaticMemberVarInstantiation(VarDecl *D)
HandleCXXStaticMemberVarInstantiation - Tell the consumer that this.
Definition: ASTConsumer.h:117
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:188
unsigned getManglingNumber(const NamedDecl *ND, bool ForAuxTarget=false) const
TypedefNameDecl * getTypedefNameForUnnamedTagDecl(const TagDecl *TD)
void setInstantiatedFromUsingDecl(NamedDecl *Inst, NamedDecl *Pattern)
Remember that the using decl Inst is an instantiation of the using decl Pattern of a class template.
QualType mergeFunctionTypes(QualType, QualType, bool OfBlockPointer=false, bool Unqualified=false, bool AllowCXX=false, bool IsConditionalOperator=false)
NamedDecl * getInstantiatedFromUsingDecl(NamedDecl *Inst)
If the given using decl Inst is an instantiation of another (possibly unresolved) using decl,...
DeclarationNameTable DeclarationNames
Definition: ASTContext.h:684
QualType getTemplateSpecializationType(TemplateName T, ArrayRef< TemplateArgument > Args, QualType Canon=QualType()) const
QualType getRecordType(const RecordDecl *Decl) const
QualType getInjectedClassNameType(CXXRecordDecl *Decl, QualType TST) const
getInjectedClassNameType - Return the unique reference to the injected class name type for the specif...
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
Definition: ASTContext.h:2723
bool hasSameType(QualType T1, QualType T2) const
Determine whether the given types T1 and T2 are equivalent.
Definition: ASTContext.h:2739
void setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst, UsingShadowDecl *Pattern)
unsigned getStaticLocalNumber(const VarDecl *VD) const
QualType getTypeDeclType(const TypeDecl *Decl, const TypeDecl *PrevDecl=nullptr) const
Return the unique reference to the type for the specified type declaration.
Definition: ASTContext.h:1703
void forEachMultiversionedFunctionVersion(const FunctionDecl *FD, llvm::function_ref< void(FunctionDecl *)> Pred) const
Visits all versions of a multiversioned function with the passed predicate.
void setInstantiatedFromUsingEnumDecl(UsingEnumDecl *Inst, UsingEnumDecl *Pattern)
Remember that the using enum decl Inst is an instantiation of the using enum decl Pattern of a class ...
CanQualType BoolTy
Definition: ASTContext.h:1161
void setStaticLocalNumber(const VarDecl *VD, unsigned Number)
OMPTraitInfo & getNewOMPTraitInfo()
Return a new OMPTraitInfo object owned by this context.
TypeSourceInfo * getTrivialTypeSourceInfo(QualType T, SourceLocation Loc=SourceLocation()) const
Allocate a TypeSourceInfo where all locations have been initialized to a given location,...
CanQualType IntTy
Definition: ASTContext.h:1169
void setManglingNumber(const NamedDecl *ND, unsigned Number)
void addDeclaratorForUnnamedTagDecl(TagDecl *TD, DeclaratorDecl *DD)
FieldDecl * getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) const
DeclaratorDecl * getDeclaratorForUnnamedTagDecl(const TagDecl *TD)
CanQualType UnsignedLongLongTy
Definition: ASTContext.h:1171
QualType getFunctionType(QualType ResultTy, ArrayRef< QualType > Args, const FunctionProtoType::ExtProtoInfo &EPI) const
Return a normal function type with a typed argument list.
Definition: ASTContext.h:1681
QualType getPromotedIntegerType(QualType PromotableType) const
Return the type that PromotableType will promote to: C99 6.3.1.1p2, assuming that PromotableType is a...
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:799
void setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst, FieldDecl *Tmpl)
bool isPromotableIntegerType(QualType T) const
More type predicates useful for type checking/promotion.
void addTypedefNameForUnnamedTagDecl(TagDecl *TD, TypedefNameDecl *TND)
An abstract interface that should be implemented by listeners that want to be notified when an AST en...
Represents an access specifier followed by colon ':'.
Definition: DeclCXX.h:86
static AccessSpecDecl * Create(ASTContext &C, AccessSpecifier AS, DeclContext *DC, SourceLocation ASLoc, SourceLocation ColonLoc)
Definition: DeclCXX.h:117
PtrTy get() const
Definition: Ownership.h:170
bool isInvalid() const
Definition: Ownership.h:166
bool isUsable() const
Definition: Ownership.h:168
Attr - This represents one attribute.
Definition: Attr.h:43
attr::Kind getKind() const
Definition: Attr.h:89
Attr * clone(ASTContext &C) const
SourceLocation getLocation() const
Definition: Attr.h:96
SourceLocation getLoc() const
Represents a C++ declaration that introduces decls from somewhere else.
Definition: DeclCXX.h:3479
A binding in a decomposition declaration.
Definition: DeclCXX.h:4169
static BindingDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation IdLoc, IdentifierInfo *Id, QualType T)
Definition: DeclCXX.cpp:3471
Represents the builtin template declaration which is used to implement __make_integer_seq and other b...
Represents a C++ constructor within a class.
Definition: DeclCXX.h:2592
bool isDefaultConstructor() const
Whether this constructor is a default constructor (C++ [class.ctor]p5), which can be used to default-...
Definition: DeclCXX.cpp:2890
static CXXConstructorDecl * Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc, const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, ExplicitSpecifier ES, bool UsesFPIntrin, bool isInline, bool isImplicitlyDeclared, ConstexprSpecKind ConstexprKind, InheritedConstructor Inherited=InheritedConstructor(), Expr *TrailingRequiresClause=nullptr)
Definition: DeclCXX.cpp:2860
Represents a C++ conversion function within a class.
Definition: DeclCXX.h:2924
static CXXConversionDecl * Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc, const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, bool UsesFPIntrin, bool isInline, ExplicitSpecifier ES, ConstexprSpecKind ConstexprKind, SourceLocation EndLocation, Expr *TrailingRequiresClause=nullptr)
Definition: DeclCXX.cpp:3049
Represents a C++ deduction guide declaration.
Definition: DeclCXX.h:1967
static CXXDeductionGuideDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, ExplicitSpecifier ES, const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, SourceLocation EndLocation, CXXConstructorDecl *Ctor=nullptr, DeductionCandidate Kind=DeductionCandidate::Normal, Expr *TrailingRequiresClause=nullptr, const CXXDeductionGuideDecl *SourceDG=nullptr, SourceDeductionGuideKind SK=SourceDeductionGuideKind::None)
Definition: DeclCXX.cpp:2291
Represents a C++ destructor within a class.
Definition: DeclCXX.h:2856
static CXXDestructorDecl * Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc, const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, bool UsesFPIntrin, bool isInline, bool isImplicitlyDeclared, ConstexprSpecKind ConstexprKind, Expr *TrailingRequiresClause=nullptr)
Definition: DeclCXX.cpp:2994
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:2117
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition: DeclCXX.h:2243
bool isMoveAssignmentOperator() const
Determine whether this is a move assignment operator.
Definition: DeclCXX.cpp:2627
static CXXMethodDecl * Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc, const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, StorageClass SC, bool UsesFPIntrin, bool isInline, ConstexprSpecKind ConstexprKind, SourceLocation EndLocation, Expr *TrailingRequiresClause=nullptr)
Definition: DeclCXX.cpp:2413
bool isCopyAssignmentOperator() const
Determine whether this is a copy-assignment operator, regardless of whether it was declared implicitl...
Definition: DeclCXX.cpp:2605
Represents a C++ struct/union/class.
Definition: DeclCXX.h:258
CXXRecordDecl * getDefinition() const
Definition: DeclCXX.h:565
static CXXRecordDecl * CreateLambda(const ASTContext &C, DeclContext *DC, TypeSourceInfo *Info, SourceLocation Loc, unsigned DependencyKind, bool IsGeneric, LambdaCaptureDefault CaptureDefault)
Definition: DeclCXX.cpp:148
static CXXRecordDecl * Create(const ASTContext &C, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, CXXRecordDecl *PrevDecl=nullptr, bool DelayTypeCreation=false)
Definition: DeclCXX.cpp:132
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine whether this particular class is a specialization or instantiation of a class template or m...
Definition: DeclCXX.cpp:2012
void setInstantiationOfMemberClass(CXXRecordDecl *RD, TemplateSpecializationKind TSK)
Specify that this record is an instantiation of the member class RD.
Definition: DeclCXX.cpp:1995
void setDescribedClassTemplate(ClassTemplateDecl *Template)
Definition: DeclCXX.cpp:2008
CXXRecordDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclCXX.h:524
Represents a C++ nested-name-specifier or a global scope specifier.
Definition: DeclSpec.h:74
void Adopt(NestedNameSpecifierLoc Other)
Adopt an existing nested-name-specifier (with source-range information).
Definition: DeclSpec.cpp:129
Declaration of a class template.
void AddPartialSpecialization(ClassTemplatePartialSpecializationDecl *D, void *InsertPos)
Insert the specified partial specialization knowing that it is not already in.
ClassTemplateDecl * getMostRecentDecl()
CXXRecordDecl * getTemplatedDecl() const
Get the underlying class declarations of the template.
ClassTemplatePartialSpecializationDecl * findPartialSpecialization(ArrayRef< TemplateArgument > Args, TemplateParameterList *TPL, void *&InsertPos)
Return the partial specialization with the provided arguments if it exists, otherwise return the inse...
static ClassTemplateDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, DeclarationName Name, TemplateParameterList *Params, NamedDecl *Decl)
Create a class template node.
ClassTemplateDecl * getCanonicalDecl() override
Retrieves the canonical declaration of this template.
ClassTemplatePartialSpecializationDecl * findPartialSpecInstantiatedFromMember(ClassTemplatePartialSpecializationDecl *D)
Find a class template partial specialization which was instantiated from the given member partial spe...
void AddSpecialization(ClassTemplateSpecializationDecl *D, void *InsertPos)
Insert the specified specialization knowing that it is not already in.
void setCommonPtr(Common *C)
QualType getInjectedClassNameSpecialization()
Retrieve the template specialization type of the injected-class-name for this class template.
Common * getCommonPtr() const
ClassTemplateSpecializationDecl * findSpecialization(ArrayRef< TemplateArgument > Args, void *&InsertPos)
Return the specialization with the provided arguments if it exists, otherwise return the insertion po...
void setInstantiatedFromMember(ClassTemplatePartialSpecializationDecl *PartialSpec)
static ClassTemplatePartialSpecializationDecl * Create(ASTContext &Context, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, TemplateParameterList *Params, ClassTemplateDecl *SpecializedTemplate, ArrayRef< TemplateArgument > Args, QualType CanonInjectedType, ClassTemplatePartialSpecializationDecl *PrevDecl)
TemplateParameterList * getTemplateParameters() const
Get the list of template parameters.
Represents a class template specialization, which refers to a class template with a given set of temp...
TemplateSpecializationKind getSpecializationKind() const
Determine the kind of specialization that this declaration represents.
const ASTTemplateArgumentListInfo * getTemplateArgsAsWritten() const
Retrieve the template argument list as written in the sources, if any.
SourceLocation getPointOfInstantiation() const
Get the point of instantiation (if any), or null if none.
void setExternKeywordLoc(SourceLocation Loc)
Sets the location of the extern keyword.
void setSpecializationKind(TemplateSpecializationKind TSK)
void setTemplateKeywordLoc(SourceLocation Loc)
Sets the location of the template keyword.
static ClassTemplateSpecializationDecl * Create(ASTContext &Context, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, ClassTemplateDecl *SpecializedTemplate, ArrayRef< TemplateArgument > Args, ClassTemplateSpecializationDecl *PrevDecl)
void setTemplateArgsAsWritten(const ASTTemplateArgumentListInfo *ArgsWritten)
Set the template argument list as written in the sources.
Declaration of a C++20 concept.
const TypeClass * getTypePtr() const
Definition: TypeLoc.h:422
Represents a shadow constructor declaration introduced into a class by a C++11 using-declaration that...
Definition: DeclCXX.h:3660
A POD class for pairing a NamedDecl* with an access specifier.
static DeclAccessPair make(NamedDecl *D, AccessSpecifier AS)
The results of name lookup within a DeclContext.
Definition: DeclBase.h:1372
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1439
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:2106
bool Equals(const DeclContext *DC) const
Determine whether this declaration context is equivalent to the declaration context DC.
Definition: DeclBase.h:2235
bool isFileContext() const
Definition: DeclBase.h:2177
void makeDeclVisibleInContext(NamedDecl *D)
Makes a declaration visible within this context.
Definition: DeclBase.cpp:2065
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
Definition: DeclBase.cpp:1345
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
Definition: DeclBase.cpp:1866
bool isRecord() const
Definition: DeclBase.h:2186
DeclContext * getRedeclContext()
getRedeclContext - Retrieve the context in which an entity conflicts with other entities of the same ...
Definition: DeclBase.cpp:2010
void addDecl(Decl *D)
Add the declaration D into this context.
Definition: DeclBase.cpp:1780
decl_iterator decls_end() const
Definition: DeclBase.h:2368
ddiag_range ddiags() const
decl_range decls() const
decls_begin/decls_end - Iterate over the declarations stored in this context.
Definition: DeclBase.h:2366
bool isFunctionOrMethod() const
Definition: DeclBase.h:2158
void addHiddenDecl(Decl *D)
Add the declaration D to this context without modifying any lookup tables.
Definition: DeclBase.cpp:1754
decl_iterator decls_begin() const
Definition: DeclBase.cpp:1636
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:1265
static DeclRefExpr * Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, ValueDecl *D, bool RefersToEnclosingVariableOrCapture, SourceLocation NameLoc, QualType T, ExprValueKind VK, NamedDecl *FoundD=nullptr, const TemplateArgumentListInfo *TemplateArgs=nullptr, NonOdrUseReason NOUR=NOUR_None)
Definition: Expr.cpp:487
ValueDecl * getDecl()
Definition: Expr.h:1333
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:86
Decl * getPreviousDecl()
Retrieve the previous declaration that declares the same entity as this declaration,...
Definition: DeclBase.h:1054
SourceLocation getEndLoc() const LLVM_READONLY
Definition: DeclBase.h:438
FriendObjectKind getFriendObjectKind() const
Determines whether this declaration is the object of a friend declaration and, if so,...
Definition: DeclBase.h:1219
T * getAttr() const
Definition: DeclBase.h:576
void addAttr(Attr *A)
Definition: DeclBase.cpp:1019
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition: DeclBase.h:596
void setLocalExternDecl()
Changes the namespace of this declaration to reflect that it's a function-local extern declaration.
Definition: DeclBase.h:1144
virtual bool isOutOfLine() const
Determine whether this declaration is declared out of line (outside its semantic context).
Definition: Decl.cpp:99
bool isParameterPack() const
Whether this declaration is a parameter pack.
Definition: DeclBase.cpp:247
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
Definition: DeclBase.cpp:159
bool isInIdentifierNamespace(unsigned NS) const
Definition: DeclBase.h:886
@ FOK_None
Not a friend object.
Definition: DeclBase.h:1210
bool isReferenced() const
Whether any declaration of this entity was referenced.
Definition: DeclBase.cpp:582
unsigned getTemplateDepth() const
Determine the number of levels of template parameter surrounding this declaration.
Definition: DeclBase.cpp:301
void setObjectOfFriendDecl(bool PerformFriendInjection=false)
Changes the namespace of this declaration to reflect that it's the object of a friend declaration.
Definition: DeclBase.h:1173
bool isFromASTFile() const
Determine whether this declaration came from an AST file (such as a precompiled header or module) rat...
Definition: DeclBase.h:786
bool isInLocalScopeForInstantiation() const
Determine whether a substitution into this declaration would occur as part of a substitution into a d...
Definition: DeclBase.cpp:403
DeclContext * getNonTransparentDeclContext()
Return the non transparent context.
Definition: DeclBase.cpp:1226
virtual bool hasBody() const
Returns true if this Decl represents a declaration for a body of code, such as a function or method d...
Definition: DeclBase.h:1086
bool isInvalidDecl() const
Definition: DeclBase.h:591
bool isLocalExternDecl() const
Determine whether this is a block-scope declaration with linkage.
Definition: DeclBase.h:1162
llvm::iterator_range< specific_attr_iterator< T > > specific_attrs() const
Definition: DeclBase.h:562
void setAccess(AccessSpecifier AS)
Definition: DeclBase.h:505
SourceLocation getLocation() const
Definition: DeclBase.h:442
const char * getDeclKindName() const
Definition: DeclBase.cpp:150
@ IDNS_Ordinary
Ordinary names.
Definition: DeclBase.h:144
void setImplicit(bool I=true)
Definition: DeclBase.h:597
void setReferenced(bool R=true)
Definition: DeclBase.h:626
void setIsUsed()
Set whether the declaration is used, in the sense of odr-use.
Definition: DeclBase.h:611
bool isUsed(bool CheckUsedAttr=true) const
Whether any (re-)declaration of the entity was used, meaning that a definition is required.
Definition: DeclBase.cpp:557
DeclContext * getDeclContext()
Definition: DeclBase.h:451
attr_range attrs() const
Definition: DeclBase.h:538
AccessSpecifier getAccess() const
Definition: DeclBase.h:510
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: DeclBase.h:434
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition: DeclBase.h:911
bool hasAttr() const
Definition: DeclBase.h:580
void setNonMemberOperator()
Specifies that this declaration is a C++ overloaded non-member.
Definition: DeclBase.h:1228
void setLexicalDeclContext(DeclContext *DC)
Definition: DeclBase.cpp:367
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclBase.h:971
Kind getKind() const
Definition: DeclBase.h:445
virtual SourceRange getSourceRange() const LLVM_READONLY
Source range that this declaration covers.
Definition: DeclBase.h:430
void setVisibleDespiteOwningModule()
Set that this declaration is globally visible, even if it came from a module that is not visible.
Definition: DeclBase.h:863
DeclarationName getCXXDestructorName(CanQualType Ty)
Returns the name of a C++ destructor for the given Type.
DeclarationName getCXXOperatorName(OverloadedOperatorKind Op)
Get the name of the overloadable C++ operator corresponding to Op.
DeclarationName getCXXConstructorName(CanQualType Ty)
Returns the name of a C++ constructor for the given Type.
The name of a declaration.
NameKind getNameKind() const
Determine what kind of name this is.
Represents a ValueDecl that came out of a declarator.
Definition: Decl.h:739
SourceLocation getInnerLocStart() const
Return start of source range ignoring outer template declarations.
Definition: Decl.h:781
SourceLocation getTypeSpecStartLoc() const
Definition: Decl.cpp:1977
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Decl.h:790
void setTypeSourceInfo(TypeSourceInfo *TI)
Definition: Decl.h:773
void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc)
Definition: Decl.cpp:1989
TypeSourceInfo * getTypeSourceInfo() const
Definition: Decl.h:768
void setTemplateParameterListsInfo(ASTContext &Context, ArrayRef< TemplateParameterList * > TPLists)
Definition: Decl.cpp:2023
Represents the type decltype(expr) (C++11).
Definition: Type.h:5880
Expr * getUnderlyingExpr() const
Definition: Type.h:5890
A decomposition declaration.
Definition: DeclCXX.h:4233
static DecompositionDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation LSquareLoc, QualType T, TypeSourceInfo *TInfo, StorageClass S, ArrayRef< BindingDecl * > Bindings)
Definition: DeclCXX.cpp:3503
Provides information about a dependent function-template specialization declaration.
Definition: DeclTemplate.h:693
Represents a qualified type name for which the type name is dependent.
Definition: Type.h:7030
unsigned getCustomDiagID(Level L, const char(&FormatString)[N])
Return an ID for a diagnostic with the specified format string and level.
Definition: Diagnostic.h:900
bool hasErrorOccurred() const
Definition: Diagnostic.h:868
RAII object that enters a new expression evaluation context.
An instance of this object exists for each enum constant that is defined.
Definition: Decl.h:3298
Represents an enum.
Definition: Decl.h:3868
enumerator_range enumerators() const
Definition: Decl.h:4001
bool isScoped() const
Returns true if this is a C++11 scoped enumeration.
Definition: Decl.h:4073
static EnumDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, EnumDecl *PrevDecl, bool IsScoped, bool IsScopedUsingClassTag, bool IsFixed)
Definition: Decl.cpp:4893
TypeSourceInfo * getIntegerTypeSourceInfo() const
Return the type source info for the underlying integer type, if no type source info exists,...
Definition: Decl.h:4044
EnumDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: Decl.h:3949
TemplateSpecializationKind getTemplateSpecializationKind() const
If this enumeration is a member of a specialization of a templated class, determine what kind of temp...
Definition: Decl.cpp:4946
Store information needed for an explicit specifier.
Definition: DeclCXX.h:1912
ExplicitSpecKind getKind() const
Definition: DeclCXX.h:1920
bool isInvalid() const
Determine if the explicit specifier is invalid.
Definition: DeclCXX.h:1941
static ExplicitSpecifier Invalid()
Definition: DeclCXX.h:1952
const Expr * getExpr() const
Definition: DeclCXX.h:1921
void setKind(ExplicitSpecKind Kind)
Definition: DeclCXX.h:1945
static ExplicitSpecifier getFromDecl(FunctionDecl *Function)
Definition: DeclCXX.cpp:2278
This represents one expression.
Definition: Expr.h:110
static bool isPotentialConstantExprUnevaluated(Expr *E, const FunctionDecl *FD, SmallVectorImpl< PartialDiagnosticAt > &Diags)
isPotentialConstantExprUnevaluated - Return true if this expression might be usable in a constant exp...
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition: Expr.h:175
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition: Expr.h:192
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Definition: Expr.cpp:3096
bool isConstantInitializer(ASTContext &Ctx, bool ForRef, const Expr **Culprit=nullptr) const
isConstantInitializer - Returns true if this expression can be emitted to IR as a constant,...
Definition: Expr.cpp:3324
QualType getType() const
Definition: Expr.h:142
Declaration context for names declared as extern "C" in C++.
Definition: Decl.h:226
Represents difference between two FPOptions values.
Definition: LangOptions.h:979
Represents a member of a struct/union/class.
Definition: Decl.h:3040
FriendDecl - Represents the declaration of a friend entity, which can be a function,...
Definition: DeclFriend.h:54
static FriendDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, FriendUnion Friend_, SourceLocation FriendL, SourceLocation EllipsisLoc={}, ArrayRef< TemplateParameterList * > FriendTypeTPLists={})
Definition: DeclFriend.cpp:34
void setUnsupportedFriend(bool Unsupported)
Definition: DeclFriend.h:189
Declaration of a friend template.
static DefaultedOrDeletedFunctionInfo * Create(ASTContext &Context, ArrayRef< DeclAccessPair > Lookups, StringLiteral *DeletedMessage=nullptr)
Definition: Decl.cpp:3100
Represents a function declaration or definition.
Definition: Decl.h:1935
void setInstantiationIsPending(bool IC)
State that the instantiation of this function is pending.
Definition: Decl.h:2448
const ParmVarDecl * getParamDecl(unsigned i) const
Definition: Decl.h:2679
Stmt * getBody(const FunctionDecl *&Definition) const
Retrieve the body (definition) of the function.
Definition: Decl.cpp:3240
void setDescribedFunctionTemplate(FunctionTemplateDecl *Template)
Definition: Decl.cpp:4069
FunctionTemplateDecl * getDescribedFunctionTemplate() const
Retrieves the function template that is described by this function declaration.
Definition: Decl.cpp:4064
bool isThisDeclarationADefinition() const
Returns whether this specific declaration of the function is also a definition that does not contain ...
Definition: Decl.h:2249
void setDefaultedOrDeletedInfo(DefaultedOrDeletedFunctionInfo *Info)
Definition: Decl.cpp:3121
bool isInlined() const
Determine whether this function should be inlined, because it is either marked "inline" or "constexpr...
Definition: Decl.h:2803
void setInstantiationOfMemberFunction(FunctionDecl *FD, TemplateSpecializationKind TSK)
Specify that this record is an instantiation of the member function FD.
Definition: Decl.h:2856
QualType getReturnType() const
Definition: Decl.h:2727
FunctionDecl * getTemplateInstantiationPattern(bool ForDefinition=true) const
Retrieve the function declaration from which this function could be instantiated, if it is an instant...
Definition: Decl.cpp:4135
FunctionDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: Decl.cpp:3635
bool isLateTemplateParsed() const
Whether this templated function will be late parsed.
Definition: Decl.h:2292
void setVirtualAsWritten(bool V)
State that this function is marked as virtual explicitly.
Definition: Decl.h:2284
bool hasSkippedBody() const
True if the function was a definition but its body was skipped.
Definition: Decl.h:2562
FunctionDecl * getDefinition()
Get the definition for this declaration.
Definition: Decl.h:2217
void setImplicitlyInline(bool I=true)
Flag that this function is implicitly inline.
Definition: Decl.h:2798
static FunctionDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation NLoc, DeclarationName N, QualType T, TypeSourceInfo *TInfo, StorageClass SC, bool UsesFPIntrin=false, bool isInlineSpecified=false, bool hasWrittenPrototype=true, ConstexprSpecKind ConstexprKind=ConstexprSpecKind::Unspecified, Expr *TrailingRequiresClause=nullptr)
Definition: Decl.h:2124
bool isThisDeclarationInstantiatedFromAFriendDefinition() const
Determine whether this specific declaration of the function is a friend declaration that was instanti...
Definition: Decl.cpp:3184
void setRangeEnd(SourceLocation E)
Definition: Decl.h:2153
bool isDefaulted() const
Whether this function is defaulted.
Definition: Decl.h:2320
void setIneligibleOrNotSelected(bool II)
Definition: Decl.h:2356
bool isVirtualAsWritten() const
Whether this function is marked as virtual explicitly.
Definition: Decl.h:2279
void setFunctionTemplateSpecialization(FunctionTemplateDecl *Template, TemplateArgumentList *TemplateArgs, void *InsertPos, TemplateSpecializationKind TSK=TSK_ImplicitInstantiation, TemplateArgumentListInfo *TemplateArgsAsWritten=nullptr, SourceLocation PointOfInstantiation=SourceLocation())
Specify that this function declaration is actually a function template specialization.
Definition: Decl.h:2956
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition: Decl.cpp:3714
DeclarationNameInfo getNameInfo() const
Definition: Decl.h:2146
bool isDefined(const FunctionDecl *&Definition, bool CheckForPendingFriendDefinition=false) const
Returns true if the function has a definition that does not need to be instantiated.
Definition: Decl.cpp:3207
DefaultedOrDeletedFunctionInfo * getDefalutedOrDeletedInfo() const
Definition: Decl.cpp:3155
void setParams(ArrayRef< ParmVarDecl * > NewParamInfo)
Definition: Decl.h:2687
bool willHaveBody() const
True if this function will eventually have a body, once it's fully parsed.
Definition: Decl.h:2568
Represents a prototype with parameter type info, e.g.
Definition: Type.h:5108
ExceptionSpecificationType getExceptionSpecType() const
Get the kind of exception specification on this function.
Definition: Type.h:5388
QualType getParamType(unsigned i) const
Definition: Type.h:5363
bool hasExceptionSpec() const
Return whether this function has any kind of exception spec.
Definition: Type.h:5394
ExtProtoInfo getExtProtoInfo() const
Definition: Type.h:5372
FunctionDecl * getExceptionSpecTemplate() const
If this function type has an uninstantiated exception specification, this is the function whose excep...
Definition: Type.h:5467
ArrayRef< QualType > getParamTypes() const
Definition: Type.h:5368
Declaration of a template function.
Definition: DeclTemplate.h:958
FunctionTemplateDecl * getCanonicalDecl() override
Retrieves the canonical declaration of this template.
FunctionDecl * findSpecialization(ArrayRef< TemplateArgument > Args, void *&InsertPos)
Return the specialization with the provided arguments if it exists, otherwise return the insertion po...
FunctionDecl * getTemplatedDecl() const
Get the underlying function declaration of the template.
FunctionTemplateDecl * getInstantiatedFromMemberTemplate() const
void setInstantiatedFromMemberTemplate(FunctionTemplateDecl *D)
FunctionTemplateDecl * getPreviousDecl()
Retrieve the previous declaration of this function template, or nullptr if no such declaration exists...
static FunctionTemplateDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, DeclarationName Name, TemplateParameterList *Params, NamedDecl *Decl)
Create a function template node.
ParmVarDecl * getParam(unsigned i) const
Definition: TypeLoc.h:1538
void setParam(unsigned i, ParmVarDecl *VD)
Definition: TypeLoc.h:1539
ExtInfo getExtInfo() const
Definition: Type.h:4661
bool getNoReturnAttr() const
Determine whether this function type includes the GNU noreturn attribute.
Definition: Type.h:4657
QualType getReturnType() const
Definition: Type.h:4649
HLSLBufferDecl - Represent a cbuffer or tbuffer declaration.
Definition: Decl.h:5033
One of these records is kept for each identifier that is lexed.
bool isStr(const char(&Str)[StrLen]) const
Return true if this is the identifier for the specified string.
Represents a field injected from an anonymous union/struct into the parent scope.
Definition: Decl.h:3342
static IndirectFieldDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, const IdentifierInfo *Id, QualType T, llvm::MutableArrayRef< NamedDecl * > CH)
Definition: Decl.cpp:5560
Description of a constructor that was inherited from a base class.
Definition: DeclCXX.h:2563
const TypeClass * getTypePtr() const
Definition: TypeLoc.h:515
static IntegerLiteral * Create(const ASTContext &C, const llvm::APInt &V, QualType type, SourceLocation l)
Returns a new integer literal with value 'V' and type 'type'.
Definition: Expr.cpp:979
Represents the declaration of a label.
Definition: Decl.h:503
static LabelDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation IdentL, IdentifierInfo *II)
Definition: Decl.cpp:5382
A stack-allocated class that identifies which local variable declaration instantiations are present i...
Definition: Template.h:365
void InstantiatedLocal(const Decl *D, Decl *Inst)
LocalInstantiationScope * cloneScopes(LocalInstantiationScope *Outermost)
Clone this scope, and all outer scopes, down to the given outermost scope.
Definition: Template.h:465
llvm::PointerUnion< Decl *, DeclArgumentPack * > * findInstantiationOf(const Decl *D)
Find the instantiation of the declaration D within the current instantiation scope.
Represents the results of name lookup.
Definition: Lookup.h:46
A global _GUID constant.
Definition: DeclCXX.h:4389
An instance of this class represents the declaration of a property member.
Definition: DeclCXX.h:4335
static MSPropertyDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, DeclarationName N, QualType T, TypeSourceInfo *TInfo, SourceLocation StartL, IdentifierInfo *Getter, IdentifierInfo *Setter)
Definition: DeclCXX.cpp:3544
Provides information a specialization of a member of a class template, which may be a member function...
Definition: DeclTemplate.h:619
Data structure that captures multiple levels of template argument lists for use in template instantia...
Definition: Template.h:76
const ArgList & getInnermost() const
Retrieve the innermost template argument list.
Definition: Template.h:265
void addOuterTemplateArguments(Decl *AssociatedDecl, ArgList Args, bool Final)
Add a new outmost level to the multi-level template argument list.
Definition: Template.h:210
unsigned getNumLevels() const
Determine the number of levels in this template argument list.
Definition: Template.h:123
void setKind(TemplateSubstitutionKind K)
Definition: Template.h:109
unsigned getNumSubstitutedLevels() const
Determine the number of substituted levels in this template argument list.
Definition: Template.h:129
void addOuterRetainedLevels(unsigned Num)
Definition: Template.h:260
unsigned getNumRetainedOuterLevels() const
Definition: Template.h:139
This represents a decl that may have a name.
Definition: Decl.h:253
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition: Decl.h:274
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition: Decl.h:319
bool hasLinkage() const
Determine whether this declaration has linkage.
Definition: Decl.cpp:1919
void setDeclName(DeclarationName N)
Set the name of this declaration.
Definition: Decl.h:322
Represents a C++ namespace alias.
Definition: DeclCXX.h:3182
static NamespaceAliasDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation NamespaceLoc, SourceLocation AliasLoc, IdentifierInfo *Alias, NestedNameSpecifierLoc QualifierLoc, SourceLocation IdentLoc, NamedDecl *Namespace)
Definition: DeclCXX.cpp:3174
Represent a C++ namespace.
Definition: Decl.h:551
A C++ nested-name-specifier augmented with source location information.
bool hasQualifier() const
Evaluates true when this nested-name-specifier location is non-empty.
SourceRange getSourceRange() const LLVM_READONLY
Retrieve the source range covering the entirety of this nested-name-specifier.
NonTypeTemplateParmDecl - Declares a non-type template parameter, e.g., "Size" in.
static NonTypeTemplateParmDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, unsigned D, unsigned P, const IdentifierInfo *Id, QualType T, bool ParameterPack, TypeSourceInfo *TInfo)
void setDefaultArgument(const ASTContext &C, const TemplateArgumentLoc &DefArg)
Set the default argument for this template parameter, and whether that default argument was inherited...
This represents '#pragma omp allocate ...' directive.
Definition: DeclOpenMP.h:474
Pseudo declaration for capturing expressions.
Definition: DeclOpenMP.h:383
This is a basic class for representing single OpenMP clause.
Definition: OpenMPClause.h:55
This represents '#pragma omp declare mapper ...' directive.
Definition: DeclOpenMP.h:287
This represents '#pragma omp declare reduction ...' directive.
Definition: DeclOpenMP.h:177
This represents '#pragma omp requires...' directive.
Definition: DeclOpenMP.h:417
This represents '#pragma omp threadprivate ...' directive.
Definition: DeclOpenMP.h:110
Helper data structure representing the traits in a match clause of an declare variant or metadirectiv...
bool anyScoreOrCondition(llvm::function_ref< bool(Expr *&, bool)> Cond)
Represents a field declaration created by an @defs(...).
Definition: DeclObjC.h:2029
Wrapper for void* pointer.
Definition: Ownership.h:50
PtrTy get() const
Definition: Ownership.h:80
static OpaquePtr make(QualType P)
Definition: Ownership.h:60
SourceLocation getEllipsisLoc() const
Definition: TypeLoc.h:2610
TypeLoc getPatternLoc() const
Definition: TypeLoc.h:2626
Represents a pack expansion of types.
Definition: Type.h:7147
std::optional< unsigned > getNumExpansions() const
Retrieve the number of expansions that this pack expansion will generate, if known.
Definition: Type.h:7172
Represents a parameter to a function.
Definition: Decl.h:1725
bool hasUninstantiatedDefaultArg() const
Definition: Decl.h:1858
Represents a #pragma comment line.
Definition: Decl.h:146
Represents a #pragma detect_mismatch line.
Definition: Decl.h:180
PrettyDeclStackTraceEntry - If a crash occurs in the parser while parsing something related to a decl...
A (possibly-)qualified type.
Definition: Type.h:929
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition: Type.h:996
QualType getNonReferenceType() const
If Type is a reference type (e.g., const int&), returns the type that the reference refers to ("const...
Definition: Type.h:8140
The collection of all-type qualifiers we support.
Definition: Type.h:324
Represents a struct/union/class.
Definition: Decl.h:4169
Wrapper for source info for record types.
Definition: TypeLoc.h:742
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:6078
Declaration of a redeclarable template.
Definition: DeclTemplate.h:720
void setInstantiatedFromMemberTemplate(RedeclarableTemplateDecl *TD)
Definition: DeclTemplate.h:909
decl_type * getFirstDecl()
Return the first declaration of this declaration or itself if this is the only declaration.
Definition: Redeclarable.h:215
decl_type * getPreviousDecl()
Return the previous declaration of this declaration or NULL if this is the first declaration.
Definition: Redeclarable.h:203
decl_type * getMostRecentDecl()
Returns the most recent (re)declaration of this declaration.
Definition: Redeclarable.h:225
void setPreviousDecl(decl_type *PrevDecl)
Set the previous declaration.
Definition: Decl.h:5087
Represents the body of a requires-expression.
Definition: DeclCXX.h:2086
static RequiresExprBodyDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc)
Definition: DeclCXX.cpp:2313
llvm::MutableArrayRef< Expr * > getExprs()
Definition: ExprCXX.h:5347
unsigned getNumExprs() const
Definition: ExprCXX.h:5345
Scope - A scope is a transient data structure that is used while parsing the program.
Definition: Scope.h:41
void addAMDGPUFlatWorkGroupSizeAttr(Decl *D, const AttributeCommonInfo &CI, Expr *Min, Expr *Max)
addAMDGPUFlatWorkGroupSizeAttr - Adds an amdgpu_flat_work_group_size attribute to a particular declar...
Definition: SemaAMDGPU.cpp:212
void addAMDGPUWavesPerEUAttr(Decl *D, const AttributeCommonInfo &CI, Expr *Min, Expr *Max)
addAMDGPUWavePersEUAttr - Adds an amdgpu_waves_per_eu attribute to a particular declaration.
Definition: SemaAMDGPU.cpp:273
void addAMDGPUMaxNumWorkGroupsAttr(Decl *D, const AttributeCommonInfo &CI, Expr *XExpr, Expr *YExpr, Expr *ZExpr)
addAMDGPUMaxNumWorkGroupsAttr - Adds an amdgpu_max_num_work_groups attribute to a particular declarat...
Definition: SemaAMDGPU.cpp:355
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID, bool DeferHint=false)
Emit a diagnostic.
Definition: SemaBase.cpp:60
Sema & SemaRef
Definition: SemaBase.h:40
void checkAllowedInitializer(VarDecl *VD)
Definition: SemaCUDA.cpp:656
QualType getInoutParameterType(QualType Ty)
Definition: SemaHLSL.cpp:2767
bool inferObjCARCLifetime(ValueDecl *decl)
void AddXConsumedAttr(Decl *D, const AttributeCommonInfo &CI, Sema::RetainOwnershipKind K, bool IsTemplateInstantiation)
Definition: SemaObjC.cpp:1740
DeclGroupPtrTy ActOnOpenMPDeclareReductionDirectiveEnd(Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid)
Called at the end of '#pragma omp declare reduction'.
void ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner)
Finish current declare reduction construct initializer.
ExprResult ActOnOpenMPDeclareMapperDirectiveVarDecl(Scope *S, QualType MapperType, SourceLocation StartLoc, DeclarationName VN)
Build the mapper variable of '#pragma omp declare mapper'.
VarDecl * ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D)
Initialize declare reduction construct initializer.
QualType ActOnOpenMPDeclareReductionType(SourceLocation TyLoc, TypeResult ParsedType)
Check if the specified type is allowed to be used in 'omp declare reduction' construct.
DeclGroupPtrTy ActOnOpenMPAllocateDirective(SourceLocation Loc, ArrayRef< Expr * > VarList, ArrayRef< OMPClause * > Clauses, DeclContext *Owner=nullptr)
Called on well-formed '#pragma omp allocate'.
DeclGroupPtrTy ActOnOpenMPDeclareReductionDirectiveStart(Scope *S, DeclContext *DC, DeclarationName Name, ArrayRef< std::pair< QualType, SourceLocation > > ReductionTypes, AccessSpecifier AS, Decl *PrevDeclInScope=nullptr)
Called on start of '#pragma omp declare reduction'.
OMPClause * ActOnOpenMPAllocatorClause(Expr *Allocator, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc)
Called on well-formed 'allocator' clause.
void EndOpenMPDSABlock(Stmt *CurDirective)
Called on end of data sharing attribute block.
QualType ActOnOpenMPDeclareMapperType(SourceLocation TyLoc, TypeResult ParsedType)
Check if the specified type is allowed to be used in 'omp declare mapper' construct.
std::optional< std::pair< FunctionDecl *, Expr * > > checkOpenMPDeclareVariantFunction(DeclGroupPtrTy DG, Expr *VariantRef, OMPTraitInfo &TI, unsigned NumAppendArgs, SourceRange SR)
Checks '#pragma omp declare variant' variant function and original functions after parsing of the ass...
void ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D)
Initialize declare reduction construct initializer.
OMPClause * ActOnOpenMPMapClause(Expr *IteratorModifier, ArrayRef< OpenMPMapModifierKind > MapTypeModifiers, ArrayRef< SourceLocation > MapTypeModifiersLoc, CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo &MapperId, OpenMPMapClauseKind MapType, bool IsMapTypeImplicit, SourceLocation MapLoc, SourceLocation ColonLoc, ArrayRef< Expr * > VarList, const OMPVarListLocTy &Locs, bool NoDiagnose=false, ArrayRef< Expr * > UnresolvedMappers={})
Called on well-formed 'map' clause.
void StartOpenMPDSABlock(OpenMPDirectiveKind K, const DeclarationNameInfo &DirName, Scope *CurScope, SourceLocation Loc)
Called on start of new data sharing attribute block.
OMPThreadPrivateDecl * CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef< Expr * > VarList)
Builds a new OpenMPThreadPrivateDecl and checks its correctness.
void ActOnOpenMPDeclareVariantDirective(FunctionDecl *FD, Expr *VariantRef, OMPTraitInfo &TI, ArrayRef< Expr * > AdjustArgsNothing, ArrayRef< Expr * > AdjustArgsNeedDevicePtr, ArrayRef< OMPInteropInfo > AppendArgs, SourceLocation AdjustArgsLoc, SourceLocation AppendArgsLoc, SourceRange SR)
Called on well-formed '#pragma omp declare variant' after parsing of the associated method/function.
void ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer, VarDecl *OmpPrivParm)
Finish current declare reduction construct initializer.
DeclGroupPtrTy ActOnOpenMPDeclareSimdDirective(DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen, ArrayRef< Expr * > Uniforms, ArrayRef< Expr * > Aligneds, ArrayRef< Expr * > Alignments, ArrayRef< Expr * > Linears, ArrayRef< unsigned > LinModifiers, ArrayRef< Expr * > Steps, SourceRange SR)
Called on well-formed '#pragma omp declare simd' after parsing of the associated method/function.
OMPClause * ActOnOpenMPAlignClause(Expr *Alignment, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc)
Called on well-formed 'align' clause.
DeclGroupPtrTy ActOnOpenMPDeclareMapperDirective(Scope *S, DeclContext *DC, DeclarationName Name, QualType MapperType, SourceLocation StartLoc, DeclarationName VN, AccessSpecifier AS, Expr *MapperVarRef, ArrayRef< OMPClause * > Clauses, Decl *PrevDeclInScope=nullptr)
Called on start of '#pragma omp declare mapper'.
void AddParameterABIAttr(Decl *D, const AttributeCommonInfo &CI, ParameterABI abi)
Definition: SemaSwift.cpp:715
RAII object used to change the argument pack substitution index within a Sema object.
Definition: Sema.h:13243
RAII object used to temporarily allow the C++ 'this' expression to be used, with the given qualifiers...
Definition: Sema.h:8062
A RAII object to temporarily push a declaration context.
Definition: Sema.h:3013
CXXSpecialMemberKind asSpecialMember() const
Definition: Sema.h:5923
A helper class for building up ExtParameterInfos.
Definition: Sema.h:12646
Records and restores the CurFPFeatures state on entry/exit of compound statements.
Definition: Sema.h:13613
RAII class used to indicate that we are performing provisional semantic analysis to determine the val...
Definition: Sema.h:12155
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:466
SemaAMDGPU & AMDGPU()
Definition: Sema.h:1048
MemInitResult BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init, CXXRecordDecl *ClassDecl)
VarTemplateSpecializationDecl * BuildVarTemplateInstantiation(VarTemplateDecl *VarTemplate, VarDecl *FromVar, const TemplateArgumentList *PartialSpecArgs, const TemplateArgumentListInfo &TemplateArgsInfo, SmallVectorImpl< TemplateArgument > &Converted, SourceLocation PointOfInstantiation, LateInstantiatedAttrVec *LateAttrs=nullptr, LocalInstantiationScope *StartingScope=nullptr)
bool SubstTypeConstraint(TemplateTypeParmDecl *Inst, const TypeConstraint *TC, const MultiLevelTemplateArgumentList &TemplateArgs, bool EvaluateConstraint)
SmallVector< CodeSynthesisContext, 16 > CodeSynthesisContexts
List of active code synthesis contexts.
Definition: Sema.h:13177
LocalInstantiationScope * CurrentInstantiationScope
The current instantiation scope used to store local variables.
Definition: Sema.h:12675
TemplateArgumentLoc getTrivialTemplateArgumentLoc(const TemplateArgument &Arg, QualType NTTPType, SourceLocation Loc, NamedDecl *TemplateParam=nullptr)
Allocate a TemplateArgumentLoc where all locations have been initialized to the given location.
bool CheckUsingDeclQualifier(SourceLocation UsingLoc, bool HasTypename, const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, SourceLocation NameLoc, const LookupResult *R=nullptr, const UsingDecl *UD=nullptr)
Checks that the given nested-name qualifier used in a using decl in the current context is appropriat...
DefaultedFunctionKind getDefaultedFunctionKind(const FunctionDecl *FD)
Determine the kind of defaulting that would be done for a given function.
bool CheckParameterPacksForExpansion(SourceLocation EllipsisLoc, SourceRange PatternRange, ArrayRef< UnexpandedParameterPack > Unexpanded, const MultiLevelTemplateArgumentList &TemplateArgs, bool &ShouldExpand, bool &RetainExpansion, std::optional< unsigned > &NumExpansions)
Determine whether we could expand a pack expansion with the given set of parameter packs into separat...
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition: Sema.h:9004
@ LookupUsingDeclName
Look up all declarations in a scope with the given name, including resolved using declarations.
Definition: Sema.h:9031
@ LookupRedeclarationWithLinkage
Look up an ordinary name that is going to be redeclared as a name with linkage.
Definition: Sema.h:9036
Decl * ActOnSkippedFunctionBody(Decl *Decl)
Definition: SemaDecl.cpp:15870
Decl * BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc, Expr *AssertExpr, Expr *AssertMessageExpr, SourceLocation RParenLoc, bool Failed)
TemplateName SubstTemplateName(NestedNameSpecifierLoc QualifierLoc, TemplateName Name, SourceLocation Loc, const MultiLevelTemplateArgumentList &TemplateArgs)
ParmVarDecl * SubstParmVarDecl(ParmVarDecl *D, const MultiLevelTemplateArgumentList &TemplateArgs, int indexAdjustment, std::optional< unsigned > NumExpansions, bool ExpectParameterPack, bool EvaluateConstraints=true)
NamedDecl * FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D, const MultiLevelTemplateArgumentList &TemplateArgs, bool FindingInstantiatedContext=false)
Find the instantiation of the given declaration within the current instantiation.
MemInitResult BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo, Expr *Init, CXXRecordDecl *ClassDecl, SourceLocation EllipsisLoc)
RetainOwnershipKind
Definition: Sema.h:4614
bool InstantiateDefaultArgument(SourceLocation CallLoc, FunctionDecl *FD, ParmVarDecl *Param)
SemaOpenMP & OpenMP()
Definition: Sema.h:1128
void AddAlignedAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E, bool IsPackExpansion)
AddAlignedAttr - Adds an aligned attribute to a particular declaration.
AccessResult CheckFriendAccess(NamedDecl *D)
Checks access to the target of a friend declaration.
const TranslationUnitKind TUKind
The kind of translation unit we are processing.
Definition: Sema.h:869
bool DiagnoseUninstantiableTemplate(SourceLocation PointOfInstantiation, NamedDecl *Instantiation, bool InstantiatedFromMember, const NamedDecl *Pattern, const NamedDecl *PatternDef, TemplateSpecializationKind TSK, bool Complain=true)
Determine whether we would be unable to instantiate this template (because it either has no definitio...
void InstantiateExceptionSpec(SourceLocation PointOfInstantiation, FunctionDecl *Function)
void AddAssumeAlignedAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E, Expr *OE)
AddAssumeAlignedAttr - Adds an assume_aligned attribute to a particular declaration.
SemaCUDA & CUDA()
Definition: Sema.h:1073
bool RequireCompleteDeclContext(CXXScopeSpec &SS, DeclContext *DC)
Require that the context specified by SS be complete.
bool TemplateParameterListsAreEqual(const TemplateCompareNewDeclInfo &NewInstFrom, TemplateParameterList *New, const NamedDecl *OldInstFrom, TemplateParameterList *Old, bool Complain, TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc=SourceLocation())
Determine whether the given template parameter lists are equivalent.
void CheckOverrideControl(NamedDecl *D)
CheckOverrideControl - Check C++11 override control semantics.
const ExpressionEvaluationContextRecord & currentEvaluationContext() const
Definition: Sema.h:6451
llvm::DenseSet< std::pair< Decl *, unsigned > > InstantiatingSpecializations
Specializations whose definitions are currently being instantiated.
Definition: Sema.h:13180
void deduceOpenCLAddressSpace(ValueDecl *decl)
Definition: SemaDecl.cpp:6867
PragmaStack< FPOptionsOverride > FpPragmaStack
Definition: Sema.h:1666
FunctionDecl * InstantiateFunctionDeclaration(FunctionTemplateDecl *FTD, const TemplateArgumentList *Args, SourceLocation Loc, CodeSynthesisContext::SynthesisKind CSC=CodeSynthesisContext::ExplicitTemplateArgumentSubstitution)
Instantiate (or find existing instantiation of) a function template with a given set of template argu...
bool tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec)
tryResolveExplicitSpecifier - Attempt to resolve the explict specifier.
ExprResult SubstInitializer(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs, bool CXXDirectInit)
MemInitResult BuildMemberInitializer(ValueDecl *Member, Expr *Init, SourceLocation IdLoc)
UsingShadowDecl * BuildUsingShadowDecl(Scope *S, BaseUsingDecl *BUD, NamedDecl *Target, UsingShadowDecl *PrevDecl)
Builds a shadow declaration corresponding to a 'using' declaration.
void CheckThreadLocalForLargeAlignment(VarDecl *VD)
Definition: SemaDecl.cpp:14651
void SubstExceptionSpec(FunctionDecl *New, const FunctionProtoType *Proto, const MultiLevelTemplateArgumentList &Args)
ExpressionEvaluationContextRecord & parentEvaluationContext()
Definition: Sema.h:6463
LateParsedTemplateMapT LateParsedTemplateMap
Definition: Sema.h:11079
bool SubstExprs(ArrayRef< Expr * > Exprs, bool IsCall, const MultiLevelTemplateArgumentList &TemplateArgs, SmallVectorImpl< Expr * > &Outputs)
Substitute the given template arguments into a list of expressions, expanding pack expansions if requ...
void CheckTemplatePartialSpecialization(ClassTemplatePartialSpecializationDecl *Partial)
StmtResult SubstStmt(Stmt *S, const MultiLevelTemplateArgumentList &TemplateArgs)
ParmVarDecl * BuildParmVarDeclForTypedef(DeclContext *DC, SourceLocation Loc, QualType T)
Synthesizes a variable for a parameter arising from a typedef.
Definition: SemaDecl.cpp:15158
ASTContext & Context
Definition: Sema.h:911
bool CheckTemplatePartialSpecializationArgs(SourceLocation Loc, TemplateDecl *PrimaryTemplate, unsigned NumExplicitArgs, ArrayRef< TemplateArgument > Args)
Check the non-type template arguments of a class template partial specialization according to C++ [te...
ExprResult SubstExpr(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs)
DiagnosticsEngine & getDiagnostics() const
Definition: Sema.h:531
TypeSourceInfo * CheckPackExpansion(TypeSourceInfo *Pattern, SourceLocation EllipsisLoc, std::optional< unsigned > NumExpansions)
Construct a pack expansion type from the pattern of the pack expansion.
SemaObjC & ObjC()
Definition: Sema.h:1113
DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType=nullptr)
Definition: SemaDecl.cpp:72
void InstantiateMemInitializers(CXXConstructorDecl *New, const CXXConstructorDecl *Tmpl, const MultiLevelTemplateArgumentList &TemplateArgs)
void CleanupVarDeclMarking()
Definition: SemaExpr.cpp:19691
ASTContext & getASTContext() const
Definition: Sema.h:534
TypeSourceInfo * SubstType(TypeSourceInfo *T, const MultiLevelTemplateArgumentList &TemplateArgs, SourceLocation Loc, DeclarationName Entity, bool AllowDeducedTST=false)
Perform substitution on the type T with a given set of template arguments.
void InstantiateVariableDefinition(SourceLocation PointOfInstantiation, VarDecl *Var, bool Recursive=false, bool DefinitionRequired=false, bool AtEndOfTU=false)
Instantiate the definition of the given variable from its template.
void inferGslPointerAttribute(NamedDecl *ND, CXXRecordDecl *UnderlyingRecord)
Add gsl::Pointer attribute to std::container::iterator.
Definition: SemaAttr.cpp:111
NamedDecl * BuildUsingDeclaration(Scope *S, AccessSpecifier AS, SourceLocation UsingLoc, bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS, DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc, const ParsedAttributesView &AttrList, bool IsInstantiation, bool IsUsingIfExists)
Builds a using declaration.
PrintingPolicy getPrintingPolicy() const
Retrieve a suitable printing policy for diagnostics.
Definition: Sema.h:819
bool SubstTemplateArguments(ArrayRef< TemplateArgumentLoc > Args, const MultiLevelTemplateArgumentList &TemplateArgs, TemplateArgumentListInfo &Outputs)
void HandleDependentAccessCheck(const DependentDiagnostic &DD, const MultiLevelTemplateArgumentList &TemplateArgs)
@ TPL_TemplateMatch
We are matching the template parameter lists of two templates that might be redeclarations.
Definition: Sema.h:11830
bool CheckFunctionTemplateSpecialization(FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs, LookupResult &Previous, bool QualifiedFriend=false)
Perform semantic analysis for the given function template specialization.
void SetDeclDefaulted(Decl *dcl, SourceLocation DefaultLoc)
NamedReturnInfo getNamedReturnInfo(Expr *&E, SimplerImplicitMoveMode Mode=SimplerImplicitMoveMode::Normal)
Determine whether the given expression might be move-eligible or copy-elidable in either a (co_)retur...
Definition: SemaStmt.cpp:3331
bool CheckEnumUnderlyingType(TypeSourceInfo *TI)
Check that this is a valid underlying type for an enum declaration.
Definition: SemaDecl.cpp:16878
void InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs, const Decl *Pattern, Decl *Inst, LateInstantiatedAttrVec *LateAttrs=nullptr, LocalInstantiationScope *OuterMostScope=nullptr)
const LangOptions & getLangOpts() const
Definition: Sema.h:527
bool AttachTypeConstraint(NestedNameSpecifierLoc NS, DeclarationNameInfo NameInfo, ConceptDecl *NamedConcept, NamedDecl *FoundDecl, const TemplateArgumentListInfo *TemplateArgs, TemplateTypeParmDecl *ConstrainedParameter, QualType ConstrainedType, SourceLocation EllipsisLoc)
Attach a type-constraint to a template parameter.
void AddModeAttr(Decl *D, const AttributeCommonInfo &CI, IdentifierInfo *Name, bool InInstantiation=false)
AddModeAttr - Adds a mode attribute to a particular declaration.
void * OpaqueParser
Definition: Sema.h:955
void collectUnexpandedParameterPacks(TemplateArgument Arg, SmallVectorImpl< UnexpandedParameterPack > &Unexpanded)
Collect the set of unexpanded parameter packs within the given template argument.
const LangOptions & LangOpts
Definition: Sema.h:909
void InstantiateClassMembers(SourceLocation PointOfInstantiation, CXXRecordDecl *Instantiation, const MultiLevelTemplateArgumentList &TemplateArgs, TemplateSpecializationKind TSK)
Instantiates the definitions of all of the member of the given class, which is an instantiation of a ...
void PerformPendingInstantiations(bool LocalOnly=false)
Performs template instantiation for all implicit template instantiations we have seen until this poin...
Decl * ActOnStartOfFunctionDef(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParamLists, SkipBodyInfo *SkipBody=nullptr, FnBodyKind BodyKind=FnBodyKind::Other)
Definition: SemaDecl.cpp:15346
SemaHLSL & HLSL()
Definition: Sema.h:1078
VarTemplateSpecializationDecl * CompleteVarTemplateSpecializationDecl(VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl, const MultiLevelTemplateArgumentList &TemplateArgs)
Instantiates a variable template specialization by completing it with appropriate type information an...
bool CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, LookupResult &Previous, bool IsMemberSpecialization, bool DeclIsDefn)
Perform semantic checking of a new function declaration.
Definition: SemaDecl.cpp:11956
FieldDecl * CheckFieldDecl(DeclarationName Name, QualType T, TypeSourceInfo *TInfo, RecordDecl *Record, SourceLocation Loc, bool Mutable, Expr *BitfieldWidth, InClassInitStyle InitStyle, SourceLocation TSSL, AccessSpecifier AS, NamedDecl *PrevDecl, Declarator *D=nullptr)
Build a new FieldDecl and check its well-formedness.
Definition: SemaDecl.cpp:18517
void updateAttrsForLateParsedTemplate(const Decl *Pattern, Decl *Inst)
Update instantiation attributes after template was late parsed.
bool CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange)
Mark the given method pure.
void InstantiateVariableInitializer(VarDecl *Var, VarDecl *OldVar, const MultiLevelTemplateArgumentList &TemplateArgs)
Instantiate the initializer of a variable.
SmallVector< PendingImplicitInstantiation, 1 > LateParsedInstantiations
Queue of implicit template instantiations that cannot be performed eagerly.
Definition: Sema.h:13574
DeclarationNameInfo SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo, const MultiLevelTemplateArgumentList &TemplateArgs)
Do template substitution on declaration name info.
SemaSwift & Swift()
Definition: Sema.h:1158
std::vector< std::unique_ptr< TemplateInstantiationCallback > > TemplateInstCallbacks
The template instantiation callbacks to trace or track instantiations (objects can be chained).
Definition: Sema.h:13229
const VarDecl * getCopyElisionCandidate(NamedReturnInfo &Info, QualType ReturnType)
Updates given NamedReturnInfo's move-eligible and copy-elidable statuses, considering the function re...
Definition: SemaStmt.cpp:3409
bool RequireCompleteEnumDecl(EnumDecl *D, SourceLocation L, CXXScopeSpec *SS=nullptr)
Require that the EnumDecl is completed with its enumerators defined or instantiated.
void AddAllocAlignAttr(Decl *D, const AttributeCommonInfo &CI, Expr *ParamExpr)
AddAllocAlignAttr - Adds an alloc_align attribute to a particular declaration.
bool usesPartialOrExplicitSpecialization(SourceLocation Loc, ClassTemplateSpecializationDecl *ClassTemplateSpec)
std::optional< unsigned > getNumArgumentsInExpansion(QualType T, const MultiLevelTemplateArgumentList &TemplateArgs)
Determine the number of arguments in the given pack expansion type.
ExplicitSpecifier instantiateExplicitSpecifier(const MultiLevelTemplateArgumentList &TemplateArgs, ExplicitSpecifier ES)
bool SubstParmTypes(SourceLocation Loc, ArrayRef< ParmVarDecl * > Params, const FunctionProtoType::ExtParameterInfo *ExtParamInfos, const MultiLevelTemplateArgumentList &TemplateArgs, SmallVectorImpl< QualType > &ParamTypes, SmallVectorImpl< ParmVarDecl * > *OutParams, ExtParameterInfoBuilder &ParamInfos)
Substitute the given template arguments into the given set of parameters, producing the set of parame...
bool CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous)
Perform semantic checking on a newly-created variable declaration.
Definition: SemaDecl.cpp:8954
int ArgumentPackSubstitutionIndex
The current index into pack expansion arguments that will be used for substitution of parameter packs...
Definition: Sema.h:13237
bool CheckUsingShadowDecl(BaseUsingDecl *BUD, NamedDecl *Target, const LookupResult &PreviousDecls, UsingShadowDecl *&PrevShadow)
Determines whether to create a using shadow decl for a particular decl, given the set of decls existi...
sema::BlockScopeInfo * getCurBlock()
Retrieve the current block, if any.
Definition: Sema.cpp:2362
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition: Sema.h:1046
MultiLevelTemplateArgumentList getTemplateInstantiationArgs(const NamedDecl *D, const DeclContext *DC=nullptr, bool Final=false, std::optional< ArrayRef< TemplateArgument > > Innermost=std::nullopt, bool RelativeToPrimary=false, const FunctionDecl *Pattern=nullptr, bool ForConstraintInstantiation=false, bool SkipForSpecialization=false, bool ForDefaultArgumentSubstitution=false)
Retrieve the template argument list(s) that should be used to instantiate the definition of the given...
SemaOpenCL & OpenCL()
Definition: Sema.h:1123
std::deque< PendingImplicitInstantiation > PendingLocalImplicitInstantiations
The queue of implicit template instantiations that are required and must be performed within the curr...
Definition: Sema.h:13587
void CompleteMemberSpecialization(NamedDecl *Member, LookupResult &Previous)
ExprResult PerformContextuallyConvertToBool(Expr *From)
PerformContextuallyConvertToBool - Perform a contextual conversion of the expression From to bool (C+...
void MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T)
Mark all of the declarations referenced within a particular AST node as referenced.
Definition: SemaExpr.cpp:20141
bool CheckSpecializationInstantiationRedecl(SourceLocation NewLoc, TemplateSpecializationKind ActOnExplicitInstantiationNewTSK, NamedDecl *PrevDecl, TemplateSpecializationKind PrevTSK, SourceLocation PrevPtOfInstantiation, bool &SuppressNew)
Diagnose cases where we have an explicit template specialization before/after an explicit template in...
SourceManager & getSourceManager() const
Definition: Sema.h:532
FunctionDecl * SubstSpaceshipAsEqualEqual(CXXRecordDecl *RD, FunctionDecl *Spaceship)
Substitute the name and return type of a defaulted 'operator<=>' to form an implicit 'operator=='.
void ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange, Decl *EnumDecl, ArrayRef< Decl * > Elements, Scope *S, const ParsedAttributesView &Attr)
Definition: SemaDecl.cpp:20044
Decl * SubstDecl(Decl *D, DeclContext *Owner, const MultiLevelTemplateArgumentList &TemplateArgs)
DeclContext * computeDeclContext(QualType T)
Compute the DeclContext that is associated with the given type.
QualType CheckNonTypeTemplateParameterType(TypeSourceInfo *&TSI, SourceLocation Loc)
Check that the type of a non-type template parameter is well-formed.
QualType CheckTemplateIdType(TemplateName Template, SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs)
Decl * ActOnFinishFunctionBody(Decl *Decl, Stmt *Body)
Definition: SemaDecl.cpp:15880
void ActOnMemInitializers(Decl *ConstructorDecl, SourceLocation ColonLoc, ArrayRef< CXXCtorInitializer * > MemInits, bool AnyErrors)
ActOnMemInitializers - Handle the member initializers for a constructor.
TemplateParameterList * SubstTemplateParams(TemplateParameterList *Params, DeclContext *Owner, const MultiLevelTemplateArgumentList &TemplateArgs, bool EvaluateConstraints=true)
void AddLaunchBoundsAttr(Decl *D, const AttributeCommonInfo &CI, Expr *MaxThreads, Expr *MinBlocks, Expr *MaxBlocks)
AddLaunchBoundsAttr - Adds a launch_bounds attribute to a particular declaration.
void AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor)
Build an exception spec for destructors that don't have one.
bool InstantiateClass(SourceLocation PointOfInstantiation, CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs, TemplateSpecializationKind TSK, bool Complain=true)
Instantiate the definition of a class from a given pattern.
void InstantiateDefaultCtorDefaultArgs(CXXConstructorDecl *Ctor)
In the MS ABI, we need to instantiate default arguments of dllexported default constructors along wit...
RedeclarationKind forRedeclarationInCurContext() const
bool SubstTemplateArgument(const TemplateArgumentLoc &Input, const MultiLevelTemplateArgumentList &TemplateArgs, TemplateArgumentLoc &Output, SourceLocation Loc={}, const DeclarationName &Entity={})
void InstantiateFunctionDefinition(SourceLocation PointOfInstantiation, FunctionDecl *Function, bool Recursive=false, bool DefinitionRequired=false, bool AtEndOfTU=false)
Instantiate the definition of the given function from its template.
bool CheckUsingDeclRedeclaration(SourceLocation UsingLoc, bool HasTypenameKeyword, const CXXScopeSpec &SS, SourceLocation NameLoc, const LookupResult &Previous)
Checks that the given using declaration is not an invalid redeclaration.
bool SubstDefaultArgument(SourceLocation Loc, ParmVarDecl *Param, const MultiLevelTemplateArgumentList &TemplateArgs, bool ForCallExpr=false)
Substitute the given template arguments into the default argument.
void InstantiateAttrsForDecl(const MultiLevelTemplateArgumentList &TemplateArgs, const Decl *Pattern, Decl *Inst, LateInstantiatedAttrVec *LateAttrs=nullptr, LocalInstantiationScope *OuterMostScope=nullptr)
EnumConstantDecl * CheckEnumConstant(EnumDecl *Enum, EnumConstantDecl *LastEnumConst, SourceLocation IdLoc, IdentifierInfo *Id, Expr *val)
Definition: SemaDecl.cpp:19575
ASTConsumer & Consumer
Definition: Sema.h:912
void DiagnoseUnusedNestedTypedefs(const RecordDecl *D)
Definition: SemaDecl.cpp:2052
bool hasUncompilableErrorOccurred() const
Whether uncompilable error has occurred.
Definition: Sema.cpp:1686
std::deque< PendingImplicitInstantiation > PendingInstantiations
The queue of implicit template instantiations that are required but have not yet been performed.
Definition: Sema.h:13570
bool CheckInheritingConstructorUsingDecl(UsingDecl *UD)
Additional checks for a using declaration referring to a constructor name.
@ ConstantEvaluated
The current context is "potentially evaluated" in C++11 terms, but the expression is evaluated at com...
@ PotentiallyEvaluated
The current expression is potentially evaluated at run time, which means that code may be generated t...
@ Unevaluated
The current expression and its subexpressions occur within an unevaluated operand (C++11 [expr]p7),...
void CheckStaticLocalForDllExport(VarDecl *VD)
Check if VD needs to be dllexport/dllimport due to being in a dllexport/import function.
Definition: SemaDecl.cpp:14614
NestedNameSpecifierLoc SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS, const MultiLevelTemplateArgumentList &TemplateArgs)
bool RequireCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind, TypeDiagnoser &Diagnoser)
Ensure that the type T is a complete type.
Definition: SemaType.cpp:9120
LateTemplateParserCB * LateTemplateParser
Definition: Sema.h:953
bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, bool InUnqualifiedLookup=false)
Perform qualified name lookup into a given context.
bool RebuildingImmediateInvocation
Whether the AST is currently being rebuilt to correct immediate invocations.
Definition: Sema.h:7781
SourceManager & SourceMgr
Definition: Sema.h:914
bool CheckAlignasTypeArgument(StringRef KWName, TypeSourceInfo *TInfo, SourceLocation OpLoc, SourceRange R)
Definition: SemaExpr.cpp:4717
NamedDecl * BuildUsingPackDecl(NamedDecl *InstantiatedFrom, ArrayRef< NamedDecl * > Expansions)
void SetDeclDeleted(Decl *dcl, SourceLocation DelLoc, StringLiteral *Message=nullptr)
FPOptions CurFPFeatures
Definition: Sema.h:907
NamespaceDecl * getStdNamespace() const
static bool adjustContextForLocalExternDecl(DeclContext *&DC)
Adjust the DeclContext for a function or variable that might be a function-local external declaration...
Definition: SemaDecl.cpp:7293
Attr * CreateAnnotationAttr(const AttributeCommonInfo &CI, StringRef Annot, MutableArrayRef< Expr * > Args)
CreateAnnotationAttr - Creates an annotation Annot with Args arguments.
Definition: Sema.cpp:2783
@ TPC_ClassTemplate
Definition: Sema.h:11296
@ TPC_FriendFunctionTemplate
Definition: Sema.h:11301
@ TPC_FriendFunctionTemplateDefinition
Definition: Sema.h:11302
void DiagnoseUnusedDecl(const NamedDecl *ND)
Definition: SemaDecl.cpp:2070
void FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S, bool ConsiderLinkage, bool AllowInlineNamespace)
Filters out lookup results that don't fall within the given scope as determined by isDeclInScope.
Definition: SemaDecl.cpp:1581
void ActOnUninitializedDecl(Decl *dcl)
Definition: SemaDecl.cpp:13939
void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit)
AddInitializerToDecl - Adds the initializer Init to the declaration dcl.
Definition: SemaDecl.cpp:13380
void runWithSufficientStackSpace(SourceLocation Loc, llvm::function_ref< void()> Fn)
Run some code with "sufficient" stack space.
Definition: Sema.cpp:564
void MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, bool MightBeOdrUse=true)
Mark a function referenced, and check whether it is odr-used (C++ [basic.def.odr]p2,...
Definition: SemaExpr.cpp:18109
void BuildVariableInstantiation(VarDecl *NewVar, VarDecl *OldVar, const MultiLevelTemplateArgumentList &TemplateArgs, LateInstantiatedAttrVec *LateAttrs, DeclContext *Owner, LocalInstantiationScope *StartingScope, bool InstantiatingVarTemplate=false, VarTemplateSpecializationDecl *PrevVTSD=nullptr)
BuildVariableInstantiation - Used after a new variable has been created.
bool CheckTemplateParameterList(TemplateParameterList *NewParams, TemplateParameterList *OldParams, TemplateParamListContext TPC, SkipBodyInfo *SkipBody=nullptr)
Checks the validity of a template parameter list, possibly considering the template parameter list fr...
ExprResult CreateRecoveryExpr(SourceLocation Begin, SourceLocation End, ArrayRef< Expr * > SubExprs, QualType T=QualType())
Attempts to produce a RecoveryExpr after some AST node cannot be created.
Definition: SemaExpr.cpp:21192
void UpdateExceptionSpec(FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI)
void CheckAlignasUnderalignment(Decl *D)
bool CheckTemplateArgumentList(TemplateDecl *Template, SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs, const DefaultArguments &DefaultArgs, bool PartialTemplateArgs, CheckTemplateArgumentInfo &CTAI, bool UpdateArgsWithConversions=true, bool *ConstraintsNotSatisfied=nullptr)
Check that the given template arguments can be provided to the given template, converting the argumen...
std::pair< ValueDecl *, SourceLocation > PendingImplicitInstantiation
An entity for which implicit template instantiation is required.
Definition: Sema.h:13566
DeclContext * FindInstantiatedContext(SourceLocation Loc, DeclContext *DC, const MultiLevelTemplateArgumentList &TemplateArgs)
Finds the instantiation of the given declaration context within the current instantiation.
bool isIncompatibleTypedef(const TypeDecl *Old, TypedefNameDecl *New)
Definition: SemaDecl.cpp:2437
void AddAlignValueAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E)
AddAlignValueAttr - Adds an align_value attribute to a particular declaration.
ArrayRef< sema::FunctionScopeInfo * > getFunctionScopes() const
Definition: Sema.h:11071
void PerformDependentDiagnostics(const DeclContext *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs)
bool checkStringLiteralArgumentAttr(const AttributeCommonInfo &CI, const Expr *E, StringRef &Str, SourceLocation *ArgLocation=nullptr)
Check if the argument E is a ASCII string literal.
bool CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped, QualType EnumUnderlyingTy, bool IsFixed, const EnumDecl *Prev)
Check whether this is a valid redeclaration of a previous enumeration.
Definition: SemaDecl.cpp:16895
bool CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, ParmVarDecl *Param, Expr *Init=nullptr, bool SkipImmediateInvocations=true)
Instantiate or parse a C++ default argument expression as necessary.
Definition: SemaExpr.cpp:5346
ASTMutationListener * getASTMutationListener() const
Definition: Sema.cpp:590
ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue)
Definition: Sema.h:8282
TypeSourceInfo * SubstFunctionDeclType(TypeSourceInfo *T, const MultiLevelTemplateArgumentList &TemplateArgs, SourceLocation Loc, DeclarationName Entity, CXXRecordDecl *ThisContext, Qualifiers ThisTypeQuals, bool EvaluateConstraints=true)
A form of SubstType intended specifically for instantiating the type of a FunctionDecl.
Encodes a location in the source.
bool isInSystemHeader(SourceLocation Loc) const
Returns if a SourceLocation is in a system header.
unsigned getExpansionLineNumber(SourceLocation Loc, bool *Invalid=nullptr) const
StringRef getFilename(SourceLocation SpellingLoc) const
Return the filename of the file containing a SourceLocation.
SourceLocation getExpansionLoc(SourceLocation Loc) const
Given a SourceLocation object Loc, return the expansion location referenced by the ID.
A trivial tuple used to represent a source range.
SourceLocation getEnd() const
Represents a C++11 static_assert declaration.
Definition: DeclCXX.h:4120
Stmt - This represents one statement.
Definition: Stmt.h:84
SourceLocation getEndLoc() const LLVM_READONLY
Definition: Stmt.cpp:358
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Stmt.cpp:346
Represents the declaration of a struct/union/class/enum.
Definition: Decl.h:3585
NestedNameSpecifierLoc getQualifierLoc() const
Retrieve the nested-name-specifier (with source-location information) that qualifies the name of this...
Definition: Decl.h:3830
TypedefNameDecl * getTypedefNameForAnonDecl() const
Definition: Decl.h:3813
void setTypedefNameForAnonDecl(TypedefNameDecl *TDD)
Definition: Decl.cpp:4769
void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc)
Definition: Decl.cpp:4824
bool hasNameForLinkage() const
Is this tag type named, either directly or via being defined in a typedef of this type?
Definition: Decl.h:3809
TagKind getTagKind() const
Definition: Decl.h:3780
bool isMicrosoft() const
Is this ABI an MSVC-compatible ABI?
Definition: TargetCXXABI.h:136
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
Definition: TargetInfo.h:1333
A convenient class for passing around template argument information.
Definition: TemplateBase.h:632
void setLAngleLoc(SourceLocation Loc)
Definition: TemplateBase.h:650
void setRAngleLoc(SourceLocation Loc)
Definition: TemplateBase.h:651
void addArgument(const TemplateArgumentLoc &Loc)
Definition: TemplateBase.h:667
A template argument list.
Definition: DeclTemplate.h:250
static TemplateArgumentList * CreateCopy(ASTContext &Context, ArrayRef< TemplateArgument > Args)
Create a new template argument list that copies the given set of template arguments.
ArrayRef< TemplateArgument > asArray() const
Produce this as an array ref.
Definition: DeclTemplate.h:280
Location wrapper for a TemplateArgument.
Definition: TemplateBase.h:524
Represents a template argument.
Definition: TemplateBase.h:61
@ Pack
The template argument is actually a parameter pack.
Definition: TemplateBase.h:107
void setEvaluateConstraints(bool B)
Definition: Template.h:602
Decl * VisitVarDecl(VarDecl *D, bool InstantiatingVarTemplate, ArrayRef< BindingDecl * > *Bindings=nullptr)
bool InitMethodInstantiation(CXXMethodDecl *New, CXXMethodDecl *Tmpl)
Initializes common fields of an instantiated method declaration (New) from the corresponding fields o...
bool InitFunctionInstantiation(FunctionDecl *New, FunctionDecl *Tmpl)
Initializes the common fields of an instantiation function declaration (New) from the corresponding f...
VarTemplatePartialSpecializationDecl * InstantiateVarTemplatePartialSpecialization(VarTemplateDecl *VarTemplate, VarTemplatePartialSpecializationDecl *PartialSpec)
Instantiate the declaration of a variable template partial specialization.
void adjustForRewrite(RewriteKind RK, FunctionDecl *Orig, QualType &T, TypeSourceInfo *&TInfo, DeclarationNameInfo &NameInfo)
TypeSourceInfo * SubstFunctionType(FunctionDecl *D, SmallVectorImpl< ParmVarDecl * > &Params)
Decl * VisitVarTemplateSpecializationDecl(VarTemplateDecl *VarTemplate, VarDecl *FromVar, const TemplateArgumentListInfo &TemplateArgsInfo, ArrayRef< TemplateArgument > Converted, VarTemplateSpecializationDecl *PrevDecl=nullptr)
void InstantiateEnumDefinition(EnumDecl *Enum, EnumDecl *Pattern)
Decl * VisitFunctionDecl(FunctionDecl *D, TemplateParameterList *TemplateParams, RewriteKind RK=RewriteKind::None)
Normal class members are of more specific types and therefore don't make it here.
Decl * VisitCXXMethodDecl(CXXMethodDecl *D, TemplateParameterList *TemplateParams, RewriteKind RK=RewriteKind::None)
Decl * InstantiateTypeAliasTemplateDecl(TypeAliasTemplateDecl *D)
Decl * VisitBaseUsingDecls(BaseUsingDecl *D, BaseUsingDecl *Inst, LookupResult *Lookup)
bool SubstQualifier(const DeclaratorDecl *OldDecl, DeclaratorDecl *NewDecl)
TemplateParameterList * SubstTemplateParams(TemplateParameterList *List)
Instantiates a nested template parameter list in the current instantiation context.
Decl * InstantiateTypedefNameDecl(TypedefNameDecl *D, bool IsTypeAlias)
ClassTemplatePartialSpecializationDecl * InstantiateClassTemplatePartialSpecialization(ClassTemplateDecl *ClassTemplate, ClassTemplatePartialSpecializationDecl *PartialSpec)
Instantiate the declaration of a class template partial specialization.
bool SubstDefaultedFunction(FunctionDecl *New, FunctionDecl *Tmpl)
The base class of all kinds of template declarations (e.g., class, function, etc.).
Definition: DeclTemplate.h:398
TemplateParameterList * getTemplateParameters() const
Get the list of template parameters.
Definition: DeclTemplate.h:417
Represents a C++ template name within the type system.
Definition: TemplateName.h:220
bool isNull() const
Determine whether this template name is NULL.
A template parameter object.
Stores a list of template parameters for a TemplateDecl and its derived classes.
Definition: DeclTemplate.h:73
SourceRange getSourceRange() const LLVM_READONLY
Definition: DeclTemplate.h:209
static TemplateParameterList * Create(const ASTContext &C, SourceLocation TemplateLoc, SourceLocation LAngleLoc, ArrayRef< NamedDecl * > Params, SourceLocation RAngleLoc, Expr *RequiresClause)
Expr * getRequiresClause()
The constraint-expression of the associated requires-clause.
Definition: DeclTemplate.h:183
SourceLocation getRAngleLoc() const
Definition: DeclTemplate.h:207
SourceLocation getLAngleLoc() const
Definition: DeclTemplate.h:206
ArrayRef< NamedDecl * > asArray()
Definition: DeclTemplate.h:142
SourceLocation getTemplateLoc() const
Definition: DeclTemplate.h:205
TemplateTemplateParmDecl - Declares a template template parameter, e.g., "T" in.
void setDefaultArgument(const ASTContext &C, const TemplateArgumentLoc &DefArg)
Set the default argument for this template parameter, and whether that default argument was inherited...
static TemplateTemplateParmDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation L, unsigned D, unsigned P, bool ParameterPack, IdentifierInfo *Id, bool Typename, TemplateParameterList *Params)
Declaration of a template type parameter.
static TemplateTypeParmDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation KeyLoc, SourceLocation NameLoc, unsigned D, unsigned P, IdentifierInfo *Id, bool Typename, bool ParameterPack, bool HasTypeConstraint=false, std::optional< unsigned > NumExpanded=std::nullopt)
void setDefaultArgument(const ASTContext &C, const TemplateArgumentLoc &DefArg)
Set the default argument for this template parameter.
The top declaration context.
Definition: Decl.h:84
A semantic tree transformation that allows one to transform one abstract syntax tree into another.
Represents the declaration of a typedef-name via a C++11 alias-declaration.
Definition: Decl.h:3556
static TypeAliasDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, TypeSourceInfo *TInfo)
Definition: Decl.cpp:5632
void setDescribedAliasTemplate(TypeAliasTemplateDecl *TAT)
Definition: Decl.h:3575
Declaration of an alias template.
static TypeAliasTemplateDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, DeclarationName Name, TemplateParameterList *Params, NamedDecl *Decl)
Create a function template node.
Models the abbreviated syntax to constrain a template type parameter: template <convertible_to<string...
Definition: ASTConcept.h:227
void setTypeForDecl(const Type *TD)
Definition: Decl.h:3417
const Type * getTypeForDecl() const
Definition: Decl.h:3416
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Decl.h:3419
TyLocType push(QualType T)
Pushes space for a new TypeLoc of the given type.
Base wrapper for a particular "section" of type source info.
Definition: TypeLoc.h:59
T getAs() const
Convert to the specified TypeLoc type, returning a null TypeLoc if this TypeLoc is not of the desired...
Definition: TypeLoc.h:89
TypeLoc IgnoreParens() const
Definition: TypeLoc.h:1257
T castAs() const
Convert to the specified TypeLoc type, asserting that this TypeLoc is of the desired type.
Definition: TypeLoc.h:78
SourceRange getSourceRange() const LLVM_READONLY
Get the full source range.
Definition: TypeLoc.h:153
AutoTypeLoc getContainedAutoTypeLoc() const
Get the typeloc of an AutoType whose type will be deduced for a variable with an initializer of this ...
Definition: TypeLoc.cpp:749
T getAsAdjusted() const
Convert to the specified TypeLoc type, returning a null TypeLoc if this TypeLoc is not of the desired...
Definition: TypeLoc.h:2716
A container of type source information.
Definition: Type.h:7908
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
Definition: TypeLoc.h:256
QualType getType() const
Return the type wrapped by this type source info.
Definition: Type.h:7919
SourceLocation getNameLoc() const
Definition: TypeLoc.h:536
void setNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:540
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.cpp:1916
bool isRValueReferenceType() const
Definition: Type.h:8218
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:8810
bool isReferenceType() const
Definition: Type.h:8210
AutoType * getContainedAutoType() const
Get the AutoType whose type will be deduced for a variable with an initializer of this type.
Definition: Type.h:2812
bool isInstantiationDependentType() const
Determine whether this type is an instantiation-dependent type, meaning that the type involves a temp...
Definition: Type.h:2715
bool isLValueReferenceType() const
Definition: Type.h:8214
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: Type.h:2707
bool containsErrors() const
Whether this type is an error type.
Definition: Type.h:2701
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition: Type.h:2725
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition: Type.h:8654
bool isFunctionType() const
Definition: Type.h:8188
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:8741
Represents the declaration of a typedef-name via the 'typedef' type specifier.
Definition: Decl.h:3535
static TypedefDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, TypeSourceInfo *TInfo)
Definition: Decl.cpp:5581
Base class for declarations which introduce a typedef-name.
Definition: Decl.h:3434
An artificial decl, representing a global anonymous constant value which is uniquified by value withi...
Definition: DeclCXX.h:4446
This node is generated when a using-declaration that was annotated with attribute((using_if_exists)) ...
Definition: DeclCXX.h:4102
static UnresolvedUsingIfExistsDecl * Create(ASTContext &Ctx, DeclContext *DC, SourceLocation Loc, DeclarationName Name)
Definition: DeclCXX.cpp:3423
Represents a dependent using declaration which was marked with typename.
Definition: DeclCXX.h:4021
SourceLocation getTypenameLoc() const
Returns the source location of the 'typename' keyword.
Definition: DeclCXX.h:4051
Represents a dependent using declaration which was not marked with typename.
Definition: DeclCXX.h:3924
Represents a C++ using-declaration.
Definition: DeclCXX.h:3574
static UsingDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation UsingL, NestedNameSpecifierLoc QualifierLoc, const DeclarationNameInfo &NameInfo, bool HasTypenameKeyword)
Definition: DeclCXX.cpp:3309
Represents C++ using-directive.
Definition: DeclCXX.h:3077
static UsingDirectiveDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation UsingLoc, SourceLocation NamespaceLoc, NestedNameSpecifierLoc QualifierLoc, SourceLocation IdentLoc, NamedDecl *Nominated, DeclContext *CommonAncestor)
Definition: DeclCXX.cpp:3096
Represents a C++ using-enum-declaration.
Definition: DeclCXX.h:3775
static UsingEnumDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation UsingL, SourceLocation EnumL, SourceLocation NameL, TypeSourceInfo *EnumType)
Definition: DeclCXX.cpp:3330
Represents a pack of using declarations that a single using-declarator pack-expanded into.
Definition: DeclCXX.h:3856
Represents a shadow declaration implicitly introduced into a scope by a (resolved) using-declaration ...
Definition: DeclCXX.h:3382
void setType(QualType newType)
Definition: Decl.h:683
QualType getType() const
Definition: Decl.h:682
bool isParameterPack() const
Determine whether this value is actually a function parameter pack, init-capture pack,...
Definition: Decl.cpp:5420
Represents a variable declaration or definition.
Definition: Decl.h:886
VarTemplateDecl * getDescribedVarTemplate() const
Retrieves the variable template that is described by this variable declaration.
Definition: Decl.cpp:2782
void setObjCForDecl(bool FRD)
Definition: Decl.h:1484
static VarDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, StorageClass S)
Definition: Decl.cpp:2140
void setCXXForRangeDecl(bool FRD)
Definition: Decl.h:1473
bool isConstexpr() const
Whether this variable is (C++11) constexpr.
Definition: Decl.h:1517
void setInstantiationOfStaticDataMember(VarDecl *VD, TemplateSpecializationKind TSK)
Specify that this variable is an instantiation of the static data member VD.
Definition: Decl.cpp:2907
TLSKind getTLSKind() const
Definition: Decl.cpp:2157
bool hasInit() const
Definition: Decl.cpp:2387
void setInitStyle(InitializationStyle Style)
Definition: Decl.h:1400
InitializationStyle getInitStyle() const
The style of initialization for this declaration.
Definition: Decl.h:1414
void setInitCapture(bool IC)
Definition: Decl.h:1529
DefinitionKind isThisDeclarationADefinition(ASTContext &) const
Check whether this declaration is a definition.
Definition: Decl.cpp:2249
bool isOutOfLine() const override
Determine whether this is or was instantiated from an out-of-line definition of a static data member.
Definition: Decl.cpp:2433
VarDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: Decl.cpp:2246
bool isInitCapture() const
Whether this variable is the implicit variable for a lambda init-capture.
Definition: Decl.h:1526
@ CallInit
Call-style initialization (C++98)
Definition: Decl.h:894
bool isObjCForDecl() const
Determine whether this variable is a for-loop declaration for a for-in statement in Objective-C.
Definition: Decl.h:1480
void setPreviousDeclInSameBlockScope(bool Same)
Definition: Decl.h:1541
bool isInlineSpecified() const
Definition: Decl.h:1502
bool isStaticDataMember() const
Determines whether this is a static data member.
Definition: Decl.h:1238
VarDecl * getTemplateInstantiationPattern() const
Retrieve the variable declaration from which this variable could be instantiated, if it is an instant...
Definition: Decl.cpp:2686
bool isCXXForRangeDecl() const
Determine whether this variable is the for-range-declaration in a C++0x for-range statement.
Definition: Decl.h:1470
VarDecl * getDefinition(ASTContext &)
Get the real (not just tentative) definition for this declaration.
Definition: Decl.cpp:2355
bool mightBeUsableInConstantExpressions(const ASTContext &C) const
Determine whether this variable's value might be usable in a constant expression, according to the re...
Definition: Decl.cpp:2458
void setInlineSpecified()
Definition: Decl.h:1506
bool isStaticLocal() const
Returns true if a variable with function scope is a static local variable.
Definition: Decl.h:1163
void setTemplateSpecializationKind(TemplateSpecializationKind TSK, SourceLocation PointOfInstantiation=SourceLocation())
For a static data member that was instantiated from a static data member of a class template,...
Definition: Decl.cpp:2879
void setTSCSpec(ThreadStorageClassSpecifier TSC)
Definition: Decl.h:1128
void setNRVOVariable(bool NRVO)
Definition: Decl.h:1463
bool isInline() const
Whether this variable is (C++1z) inline.
Definition: Decl.h:1499
ThreadStorageClassSpecifier getTSCSpec() const
Definition: Decl.h:1132
const Expr * getInit() const
Definition: Decl.h:1323
void setConstexpr(bool IC)
Definition: Decl.h:1520
void setDescribedVarTemplate(VarTemplateDecl *Template)
Definition: Decl.cpp:2787
bool isDirectInit() const
Whether the initializer is a direct-initializer (list or call).
Definition: Decl.h:1419
StorageClass getStorageClass() const
Returns the storage class as written in the source.
Definition: Decl.h:1123
void setImplicitlyInline()
Definition: Decl.h:1511
bool isPreviousDeclInSameBlockScope() const
Whether this local extern variable declaration's previous declaration was declared in the same block ...
Definition: Decl.h:1536
SourceLocation getPointOfInstantiation() const
If this variable is an instantiation of a variable template or a static data member of a class templa...
Definition: Decl.cpp:2772
TemplateSpecializationKind getTemplateSpecializationKindForInstantiation() const
Get the template specialization kind of this variable for the purposes of template instantiation.
Definition: Decl.cpp:2762
TemplateSpecializationKind getTemplateSpecializationKind() const
If this variable is an instantiation of a variable template or a static data member of a class templa...
Definition: Decl.cpp:2751
Declaration of a variable template.
void AddPartialSpecialization(VarTemplatePartialSpecializationDecl *D, void *InsertPos)
Insert the specified partial specialization knowing that it is not already in.
VarTemplatePartialSpecializationDecl * findPartialSpecialization(ArrayRef< TemplateArgument > Args, TemplateParameterList *TPL, void *&InsertPos)
Return the partial specialization with the provided arguments if it exists, otherwise return the inse...
void AddSpecialization(VarTemplateSpecializationDecl *D, void *InsertPos)
Insert the specified specialization knowing that it is not already in.
static VarTemplateDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, DeclarationName Name, TemplateParameterList *Params, VarDecl *Decl)
Create a variable template node.
VarTemplateSpecializationDecl * findSpecialization(ArrayRef< TemplateArgument > Args, void *&InsertPos)
Return the specialization with the provided arguments if it exists, otherwise return the insertion po...
VarTemplatePartialSpecializationDecl * findPartialSpecInstantiatedFromMember(VarTemplatePartialSpecializationDecl *D)
Find a variable template partial specialization which was instantiated from the given member partial ...
static VarTemplatePartialSpecializationDecl * Create(ASTContext &Context, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, TemplateParameterList *Params, VarTemplateDecl *SpecializedTemplate, QualType T, TypeSourceInfo *TInfo, StorageClass S, ArrayRef< TemplateArgument > Args)
TemplateParameterList * getTemplateParameters() const
Get the list of template parameters.
void setInstantiatedFromMember(VarTemplatePartialSpecializationDecl *PartialSpec)
Represents a variable template specialization, which refers to a variable template with a given set o...
SourceLocation getPointOfInstantiation() const
Get the point of instantiation (if any), or null if none.
void setTemplateArgsAsWritten(const ASTTemplateArgumentListInfo *ArgsWritten)
Set the template argument list as written in the sources.
const ASTTemplateArgumentListInfo * getTemplateArgsAsWritten() const
Retrieve the template argument list as written in the sources, if any.
const TemplateArgumentList & getTemplateArgs() const
Retrieve the template arguments of the variable template specialization.
const TemplateArgumentList & getTemplateInstantiationArgs() const
Retrieve the set of template arguments that should be used to instantiate the initializer of the vari...
static VarTemplateSpecializationDecl * Create(ASTContext &Context, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, VarTemplateDecl *SpecializedTemplate, QualType T, TypeSourceInfo *TInfo, StorageClass S, ArrayRef< TemplateArgument > Args)
llvm::PointerUnion< VarTemplateDecl *, VarTemplatePartialSpecializationDecl * > getSpecializedTemplateOrPartial() const
Retrieve the variable template or variable template partial specialization which was specialized by t...
TemplateSpecializationKind getSpecializationKind() const
Determine the kind of specialization that this declaration represents.
VarTemplateDecl * getSpecializedTemplate() const
Retrieve the template that this specialization specializes.
RetTy Visit(PTR(Decl) D)
Definition: DeclVisitor.h:37
QualType FunctionType
BlockType - The function type of the block, if one was given.
Definition: ScopeInfo.h:800
void addCapture(ValueDecl *Var, bool isBlock, bool isByref, bool isNested, SourceLocation Loc, SourceLocation EllipsisLoc, QualType CaptureType, bool Invalid)
Definition: ScopeInfo.h:737
Provides information about an attempted template argument deduction, whose success or failure was des...
Defines the clang::TargetInfo interface.
const internal::VariadicAllOfMatcher< Decl > decl
Matches declarations.
bool NE(InterpState &S, CodePtr OpPC)
Definition: Interp.h:1157
Attr * instantiateTemplateAttribute(const Attr *At, ASTContext &C, Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs)
Attr * instantiateTemplateAttributeForDecl(const Attr *At, ASTContext &C, Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs)
The JSON file list parser is used to communicate input to InstallAPI.
void atTemplateEnd(TemplateInstantiationCallbackPtrs &Callbacks, const Sema &TheSema, const Sema::CodeSynthesisContext &Inst)
@ CPlusPlus11
Definition: LangStandard.h:56
void atTemplateBegin(TemplateInstantiationCallbackPtrs &Callbacks, const Sema &TheSema, const Sema::CodeSynthesisContext &Inst)
@ Rewrite
We are substituting template parameters for (typically) other template parameters in order to rewrite...
StorageClass
Storage classes.
Definition: Specifiers.h:248
@ SC_Static
Definition: Specifiers.h:252
@ SC_None
Definition: Specifiers.h:250
ExprResult ExprEmpty()
Definition: Ownership.h:271
bool isGenericLambdaCallOperatorOrStaticInvokerSpecialization(const DeclContext *DC)
Definition: ASTLambda.h:89
@ Property
The type of a property.
@ Result
The result type of a method or function.
@ TU_Prefix
The translation unit is a prefix to a translation unit, and is not complete.
Definition: LangOptions.h:1103
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition: Specifiers.h:135
const FunctionProtoType * T
bool declaresSameEntity(const Decl *D1, const Decl *D2)
Determine whether two declarations declare the same entity.
Definition: DeclBase.h:1278
TemplateSpecializationKind
Describes the kind of template specialization that a particular template specialization declaration r...
Definition: Specifiers.h:188
@ TSK_ExplicitInstantiationDefinition
This template specialization was instantiated from a template due to an explicit instantiation defini...
Definition: Specifiers.h:206
@ TSK_ExplicitInstantiationDeclaration
This template specialization was instantiated from a template due to an explicit instantiation declar...
Definition: Specifiers.h:202
@ TSK_ExplicitSpecialization
This template specialization was declared or defined by an explicit specialization (C++ [temp....
Definition: Specifiers.h:198
@ TSK_ImplicitInstantiation
This template specialization was implicitly instantiated from a template.
Definition: Specifiers.h:194
@ TSK_Undeclared
This template specialization was formed from a template-id but has not yet been declared,...
Definition: Specifiers.h:191
@ Enum
The "enum" keyword introduces the elaborated-type-specifier.
bool isLambdaMethod(const DeclContext *DC)
Definition: ASTLambda.h:39
@ Other
Other implicit parameter.
ExceptionSpecificationType
The various types of exception specifications that exist in C++11.
@ EST_DynamicNone
throw()
@ EST_Uninstantiated
not instantiated yet
@ EST_None
no exception specification
@ EST_BasicNoexcept
noexcept
@ EST_Unevaluated
not evaluated yet, for special member function
@ AS_public
Definition: Specifiers.h:124
@ AS_none
Definition: Specifiers.h:127
Represents an explicit template argument list in C++, e.g., the "<int>" in "sort<int>".
Definition: TemplateBase.h:676
SourceLocation RAngleLoc
The source location of the right angle bracket ('>').
Definition: TemplateBase.h:691
SourceLocation LAngleLoc
The source location of the left angle bracket ('<').
Definition: TemplateBase.h:688
llvm::ArrayRef< TemplateArgumentLoc > arguments() const
Definition: TemplateBase.h:705
DeclarationNameInfo - A collector data type for bundling together a DeclarationName and the correspon...
DeclarationName getName() const
getName - Returns the embedded declaration name.
void setName(DeclarationName N)
setName - Sets the embedded declaration name.
const DeclarationNameLoc & getInfo() const
Holds information about the various types of exception specification.
Definition: Type.h:5165
FunctionDecl * SourceDecl
The function whose exception specification this is, for EST_Unevaluated and EST_Uninstantiated.
Definition: Type.h:5177
FunctionDecl * SourceTemplate
The function template whose exception specification this is instantiated from, for EST_Uninstantiated...
Definition: Type.h:5181
ExceptionSpecificationType Type
The kind of exception specification this is.
Definition: Type.h:5167
Extra information about a function prototype.
Definition: Type.h:5193
ExceptionSpecInfo ExceptionSpec
Definition: Type.h:5200
FunctionType::ExtInfo ExtInfo
Definition: Type.h:5194
This structure contains most locations needed for by an OMPVarListClause.
Definition: OpenMPClause.h:259
SmallVector< TemplateArgument, 4 > CanonicalConverted
Definition: Sema.h:11677
A context in which code is being synthesized (where a source location alone is not sufficient to iden...
Definition: Sema.h:12692
SynthesisKind
The kind of template instantiation we are performing.
Definition: Sema.h:12694
@ BuildingDeductionGuides
We are building deduction guides for a class.
Definition: Sema.h:12799
@ DeducedTemplateArgumentSubstitution
We are substituting template argument determined as part of template argument deduction for either a ...
Definition: Sema.h:12720
bool InLifetimeExtendingContext
Whether we are currently in a context in which all temporaries must be lifetime-extended,...
Definition: Sema.h:6377
bool RebuildDefaultArgOrDefaultInit
Whether we should rebuild CXXDefaultArgExpr and CXXDefaultInitExpr.
Definition: Sema.h:6380
A stack object to be created when performing template instantiation.
Definition: Sema.h:12880
bool isInvalid() const
Determines whether we have exceeded the maximum recursive template instantiations.
Definition: Sema.h:13040
bool isAlreadyInstantiating() const
Determine whether we are already instantiating this specialization in some surrounding active instant...
Definition: Sema.h:13044