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