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