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 } else {
1575 assert(!D->getIntegerType()->isDependentType()
1576 && "Dependent type without type source info");
1577 Enum->setIntegerType(D->getIntegerType());
1578 }
1579 }
1580
1581 SemaRef.InstantiateAttrs(TemplateArgs, D, Enum);
1582
1583 Enum->setInstantiationOfMemberEnum(D, TSK_ImplicitInstantiation);
1584 Enum->setAccess(D->getAccess());
1585 // Forward the mangling number from the template to the instantiated decl.
1587 // See if the old tag was defined along with a declarator.
1588 // If it did, mark the new tag as being associated with that declarator.
1591 // See if the old tag was defined along with a typedef.
1592 // If it did, mark the new tag as being associated with that typedef.
1595 if (SubstQualifier(D, Enum)) return nullptr;
1596 Owner->addDecl(Enum);
1597
1598 EnumDecl *Def = D->getDefinition();
1599 if (Def && Def != D) {
1600 // If this is an out-of-line definition of an enum member template, check
1601 // that the underlying types match in the instantiation of both
1602 // declarations.
1603 if (TypeSourceInfo *TI = Def->getIntegerTypeSourceInfo()) {
1604 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
1605 QualType DefnUnderlying =
1606 SemaRef.SubstType(TI->getType(), TemplateArgs,
1607 UnderlyingLoc, DeclarationName());
1608 SemaRef.CheckEnumRedeclaration(Def->getLocation(), Def->isScoped(),
1609 DefnUnderlying, /*IsFixed=*/true, Enum);
1610 }
1611 }
1612
1613 // C++11 [temp.inst]p1: The implicit instantiation of a class template
1614 // specialization causes the implicit instantiation of the declarations, but
1615 // not the definitions of scoped member enumerations.
1616 //
1617 // DR1484 clarifies that enumeration definitions inside of a template
1618 // declaration aren't considered entities that can be separately instantiated
1619 // from the rest of the entity they are declared inside of.
1620 if (isDeclWithinFunction(D) ? D == Def : Def && !Enum->isScoped()) {
1623 }
1624
1625 return Enum;
1626}
1627
1629 EnumDecl *Enum, EnumDecl *Pattern) {
1630 Enum->startDefinition();
1631
1632 // Update the location to refer to the definition.
1633 Enum->setLocation(Pattern->getLocation());
1634
1635 SmallVector<Decl*, 4> Enumerators;
1636
1637 EnumConstantDecl *LastEnumConst = nullptr;
1638 for (auto *EC : Pattern->enumerators()) {
1639 // The specified value for the enumerator.
1640 ExprResult Value((Expr *)nullptr);
1641 if (Expr *UninstValue = EC->getInitExpr()) {
1642 // The enumerator's value expression is a constant expression.
1645
1646 Value = SemaRef.SubstExpr(UninstValue, TemplateArgs);
1647 }
1648
1649 // Drop the initial value and continue.
1650 bool isInvalid = false;
1651 if (Value.isInvalid()) {
1652 Value = nullptr;
1653 isInvalid = true;
1654 }
1655
1656 EnumConstantDecl *EnumConst
1657 = SemaRef.CheckEnumConstant(Enum, LastEnumConst,
1658 EC->getLocation(), EC->getIdentifier(),
1659 Value.get());
1660
1661 if (isInvalid) {
1662 if (EnumConst)
1663 EnumConst->setInvalidDecl();
1664 Enum->setInvalidDecl();
1665 }
1666
1667 if (EnumConst) {
1668 SemaRef.InstantiateAttrs(TemplateArgs, EC, EnumConst);
1669
1670 EnumConst->setAccess(Enum->getAccess());
1671 Enum->addDecl(EnumConst);
1672 Enumerators.push_back(EnumConst);
1673 LastEnumConst = EnumConst;
1674
1675 if (Pattern->getDeclContext()->isFunctionOrMethod() &&
1676 !Enum->isScoped()) {
1677 // If the enumeration is within a function or method, record the enum
1678 // constant as a local.
1679 SemaRef.CurrentInstantiationScope->InstantiatedLocal(EC, EnumConst);
1680 }
1681 }
1682 }
1683
1684 SemaRef.ActOnEnumBody(Enum->getLocation(), Enum->getBraceRange(), Enum,
1685 Enumerators, nullptr, ParsedAttributesView());
1686}
1687
1688Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) {
1689 llvm_unreachable("EnumConstantDecls can only occur within EnumDecls.");
1690}
1691
1692Decl *
1693TemplateDeclInstantiator::VisitBuiltinTemplateDecl(BuiltinTemplateDecl *D) {
1694 llvm_unreachable("BuiltinTemplateDecls cannot be instantiated.");
1695}
1696
1697Decl *TemplateDeclInstantiator::VisitClassTemplateDecl(ClassTemplateDecl *D) {
1698 bool isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
1699
1700 // Create a local instantiation scope for this class template, which
1701 // will contain the instantiations of the template parameters.
1703 TemplateParameterList *TempParams = D->getTemplateParameters();
1704 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1705 if (!InstParams)
1706 return nullptr;
1707
1708 CXXRecordDecl *Pattern = D->getTemplatedDecl();
1709
1710 // Instantiate the qualifier. We have to do this first in case
1711 // we're a friend declaration, because if we are then we need to put
1712 // the new declaration in the appropriate context.
1713 NestedNameSpecifierLoc QualifierLoc = Pattern->getQualifierLoc();
1714 if (QualifierLoc) {
1715 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
1716 TemplateArgs);
1717 if (!QualifierLoc)
1718 return nullptr;
1719 }
1720
1721 CXXRecordDecl *PrevDecl = nullptr;
1722 ClassTemplateDecl *PrevClassTemplate = nullptr;
1723
1724 if (!isFriend && getPreviousDeclForInstantiation(Pattern)) {
1726 if (!Found.empty()) {
1727 PrevClassTemplate = dyn_cast<ClassTemplateDecl>(Found.front());
1728 if (PrevClassTemplate)
1729 PrevDecl = PrevClassTemplate->getTemplatedDecl();
1730 }
1731 }
1732
1733 // If this isn't a friend, then it's a member template, in which
1734 // case we just want to build the instantiation in the
1735 // specialization. If it is a friend, we want to build it in
1736 // the appropriate context.
1737 DeclContext *DC = Owner;
1738 if (isFriend) {
1739 if (QualifierLoc) {
1740 CXXScopeSpec SS;
1741 SS.Adopt(QualifierLoc);
1742 DC = SemaRef.computeDeclContext(SS);
1743 if (!DC) return nullptr;
1744 } else {
1745 DC = SemaRef.FindInstantiatedContext(Pattern->getLocation(),
1746 Pattern->getDeclContext(),
1747 TemplateArgs);
1748 }
1749
1750 // Look for a previous declaration of the template in the owning
1751 // context.
1752 LookupResult R(SemaRef, Pattern->getDeclName(), Pattern->getLocation(),
1755 SemaRef.LookupQualifiedName(R, DC);
1756
1757 if (R.isSingleResult()) {
1758 PrevClassTemplate = R.getAsSingle<ClassTemplateDecl>();
1759 if (PrevClassTemplate)
1760 PrevDecl = PrevClassTemplate->getTemplatedDecl();
1761 }
1762
1763 if (!PrevClassTemplate && QualifierLoc) {
1764 SemaRef.Diag(Pattern->getLocation(), diag::err_not_tag_in_scope)
1765 << llvm::to_underlying(D->getTemplatedDecl()->getTagKind())
1766 << Pattern->getDeclName() << DC << QualifierLoc.getSourceRange();
1767 return nullptr;
1768 }
1769 }
1770
1772 SemaRef.Context, Pattern->getTagKind(), DC, Pattern->getBeginLoc(),
1773 Pattern->getLocation(), Pattern->getIdentifier(), PrevDecl,
1774 /*DelayTypeCreation=*/true);
1775 if (QualifierLoc)
1776 RecordInst->setQualifierInfo(QualifierLoc);
1777
1778 SemaRef.InstantiateAttrsForDecl(TemplateArgs, Pattern, RecordInst, LateAttrs,
1779 StartingScope);
1780
1781 ClassTemplateDecl *Inst
1783 D->getIdentifier(), InstParams, RecordInst);
1784 RecordInst->setDescribedClassTemplate(Inst);
1785
1786 if (isFriend) {
1787 assert(!Owner->isDependentContext());
1788 Inst->setLexicalDeclContext(Owner);
1789 RecordInst->setLexicalDeclContext(Owner);
1790 Inst->setObjectOfFriendDecl();
1791
1792 if (PrevClassTemplate) {
1793 Inst->setCommonPtr(PrevClassTemplate->getCommonPtr());
1794 RecordInst->setTypeForDecl(
1795 PrevClassTemplate->getTemplatedDecl()->getTypeForDecl());
1796 const ClassTemplateDecl *MostRecentPrevCT =
1797 PrevClassTemplate->getMostRecentDecl();
1798 TemplateParameterList *PrevParams =
1799 MostRecentPrevCT->getTemplateParameters();
1800
1801 // Make sure the parameter lists match.
1802 if (!SemaRef.TemplateParameterListsAreEqual(
1803 RecordInst, InstParams, MostRecentPrevCT->getTemplatedDecl(),
1804 PrevParams, true, Sema::TPL_TemplateMatch))
1805 return nullptr;
1806
1807 // Do some additional validation, then merge default arguments
1808 // from the existing declarations.
1809 if (SemaRef.CheckTemplateParameterList(InstParams, PrevParams,
1811 return nullptr;
1812
1813 Inst->setAccess(PrevClassTemplate->getAccess());
1814 } else {
1815 Inst->setAccess(D->getAccess());
1816 }
1817
1818 Inst->setObjectOfFriendDecl();
1819 // TODO: do we want to track the instantiation progeny of this
1820 // friend target decl?
1821 } else {
1822 Inst->setAccess(D->getAccess());
1823 if (!PrevClassTemplate)
1825 }
1826
1827 Inst->setPreviousDecl(PrevClassTemplate);
1828
1829 // Trigger creation of the type for the instantiation.
1831 RecordInst, Inst->getInjectedClassNameSpecialization());
1832
1833 // Finish handling of friends.
1834 if (isFriend) {
1835 DC->makeDeclVisibleInContext(Inst);
1836 return Inst;
1837 }
1838
1839 if (D->isOutOfLine()) {
1842 }
1843
1844 Owner->addDecl(Inst);
1845
1846 if (!PrevClassTemplate) {
1847 // Queue up any out-of-line partial specializations of this member
1848 // class template; the client will force their instantiation once
1849 // the enclosing class has been instantiated.
1851 D->getPartialSpecializations(PartialSpecs);
1852 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
1853 if (PartialSpecs[I]->getFirstDecl()->isOutOfLine())
1854 OutOfLinePartialSpecs.push_back(std::make_pair(Inst, PartialSpecs[I]));
1855 }
1856
1857 return Inst;
1858}
1859
1860Decl *
1861TemplateDeclInstantiator::VisitClassTemplatePartialSpecializationDecl(
1863 ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
1864
1865 // Lookup the already-instantiated declaration in the instantiation
1866 // of the class template and return that.
1868 = Owner->lookup(ClassTemplate->getDeclName());
1869 if (Found.empty())
1870 return nullptr;
1871
1872 ClassTemplateDecl *InstClassTemplate
1873 = dyn_cast<ClassTemplateDecl>(Found.front());
1874 if (!InstClassTemplate)
1875 return nullptr;
1876
1878 = InstClassTemplate->findPartialSpecInstantiatedFromMember(D))
1879 return Result;
1880
1881 return InstantiateClassTemplatePartialSpecialization(InstClassTemplate, D);
1882}
1883
1884Decl *TemplateDeclInstantiator::VisitVarTemplateDecl(VarTemplateDecl *D) {
1885 assert(D->getTemplatedDecl()->isStaticDataMember() &&
1886 "Only static data member templates are allowed.");
1887
1888 // Create a local instantiation scope for this variable template, which
1889 // will contain the instantiations of the template parameters.
1891 TemplateParameterList *TempParams = D->getTemplateParameters();
1892 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1893 if (!InstParams)
1894 return nullptr;
1895
1896 VarDecl *Pattern = D->getTemplatedDecl();
1897 VarTemplateDecl *PrevVarTemplate = nullptr;
1898
1899 if (getPreviousDeclForInstantiation(Pattern)) {
1901 if (!Found.empty())
1902 PrevVarTemplate = dyn_cast<VarTemplateDecl>(Found.front());
1903 }
1904
1905 VarDecl *VarInst =
1906 cast_or_null<VarDecl>(VisitVarDecl(Pattern,
1907 /*InstantiatingVarTemplate=*/true));
1908 if (!VarInst) return nullptr;
1909
1910 DeclContext *DC = Owner;
1911
1913 SemaRef.Context, DC, D->getLocation(), D->getIdentifier(), InstParams,
1914 VarInst);
1915 VarInst->setDescribedVarTemplate(Inst);
1916 Inst->setPreviousDecl(PrevVarTemplate);
1917
1918 Inst->setAccess(D->getAccess());
1919 if (!PrevVarTemplate)
1921
1922 if (D->isOutOfLine()) {
1925 }
1926
1927 Owner->addDecl(Inst);
1928
1929 if (!PrevVarTemplate) {
1930 // Queue up any out-of-line partial specializations of this member
1931 // variable template; the client will force their instantiation once
1932 // the enclosing class has been instantiated.
1934 D->getPartialSpecializations(PartialSpecs);
1935 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
1936 if (PartialSpecs[I]->getFirstDecl()->isOutOfLine())
1937 OutOfLineVarPartialSpecs.push_back(
1938 std::make_pair(Inst, PartialSpecs[I]));
1939 }
1940
1941 return Inst;
1942}
1943
1944Decl *TemplateDeclInstantiator::VisitVarTemplatePartialSpecializationDecl(
1946 assert(D->isStaticDataMember() &&
1947 "Only static data member templates are allowed.");
1948
1949 VarTemplateDecl *VarTemplate = D->getSpecializedTemplate();
1950
1951 // Lookup the already-instantiated declaration and return that.
1952 DeclContext::lookup_result Found = Owner->lookup(VarTemplate->getDeclName());
1953 assert(!Found.empty() && "Instantiation found nothing?");
1954
1955 VarTemplateDecl *InstVarTemplate = dyn_cast<VarTemplateDecl>(Found.front());
1956 assert(InstVarTemplate && "Instantiation did not find a variable template?");
1957
1959 InstVarTemplate->findPartialSpecInstantiatedFromMember(D))
1960 return Result;
1961
1962 return InstantiateVarTemplatePartialSpecialization(InstVarTemplate, D);
1963}
1964
1965Decl *
1966TemplateDeclInstantiator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
1967 // Create a local instantiation scope for this function template, which
1968 // will contain the instantiations of the template parameters and then get
1969 // merged with the local instantiation scope for the function template
1970 // itself.
1973
1974 TemplateParameterList *TempParams = D->getTemplateParameters();
1975 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1976 if (!InstParams)
1977 return nullptr;
1978
1979 FunctionDecl *Instantiated = nullptr;
1980 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(D->getTemplatedDecl()))
1981 Instantiated = cast_or_null<FunctionDecl>(VisitCXXMethodDecl(DMethod,
1982 InstParams));
1983 else
1984 Instantiated = cast_or_null<FunctionDecl>(VisitFunctionDecl(
1985 D->getTemplatedDecl(),
1986 InstParams));
1987
1988 if (!Instantiated)
1989 return nullptr;
1990
1991 // Link the instantiated function template declaration to the function
1992 // template from which it was instantiated.
1993 FunctionTemplateDecl *InstTemplate
1994 = Instantiated->getDescribedFunctionTemplate();
1995 InstTemplate->setAccess(D->getAccess());
1996 assert(InstTemplate &&
1997 "VisitFunctionDecl/CXXMethodDecl didn't create a template!");
1998
1999 bool isFriend = (InstTemplate->getFriendObjectKind() != Decl::FOK_None);
2000
2001 // Link the instantiation back to the pattern *unless* this is a
2002 // non-definition friend declaration.
2003 if (!InstTemplate->getInstantiatedFromMemberTemplate() &&
2004 !(isFriend && !D->getTemplatedDecl()->isThisDeclarationADefinition()))
2005 InstTemplate->setInstantiatedFromMemberTemplate(D);
2006
2007 // Make declarations visible in the appropriate context.
2008 if (!isFriend) {
2009 Owner->addDecl(InstTemplate);
2010 } else if (InstTemplate->getDeclContext()->isRecord() &&
2012 SemaRef.CheckFriendAccess(InstTemplate);
2013 }
2014
2015 return InstTemplate;
2016}
2017
2018Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) {
2019 CXXRecordDecl *PrevDecl = nullptr;
2020 if (CXXRecordDecl *PatternPrev = getPreviousDeclForInstantiation(D)) {
2021 NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
2022 PatternPrev,
2023 TemplateArgs);
2024 if (!Prev) return nullptr;
2025 PrevDecl = cast<CXXRecordDecl>(Prev);
2026 }
2027
2028 CXXRecordDecl *Record = nullptr;
2029 bool IsInjectedClassName = D->isInjectedClassName();
2030 if (D->isLambda())
2032 SemaRef.Context, Owner, D->getLambdaTypeInfo(), D->getLocation(),
2033 D->getLambdaDependencyKind(), D->isGenericLambda(),
2034 D->getLambdaCaptureDefault());
2035 else
2036 Record = CXXRecordDecl::Create(SemaRef.Context, D->getTagKind(), Owner,
2037 D->getBeginLoc(), D->getLocation(),
2038 D->getIdentifier(), PrevDecl,
2039 /*DelayTypeCreation=*/IsInjectedClassName);
2040 // Link the type of the injected-class-name to that of the outer class.
2041 if (IsInjectedClassName)
2042 (void)SemaRef.Context.getTypeDeclType(Record, cast<CXXRecordDecl>(Owner));
2043
2044 // Substitute the nested name specifier, if any.
2045 if (SubstQualifier(D, Record))
2046 return nullptr;
2047
2048 SemaRef.InstantiateAttrsForDecl(TemplateArgs, D, Record, LateAttrs,
2049 StartingScope);
2050
2051 Record->setImplicit(D->isImplicit());
2052 // FIXME: Check against AS_none is an ugly hack to work around the issue that
2053 // the tag decls introduced by friend class declarations don't have an access
2054 // specifier. Remove once this area of the code gets sorted out.
2055 if (D->getAccess() != AS_none)
2056 Record->setAccess(D->getAccess());
2057 if (!IsInjectedClassName)
2058 Record->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
2059
2060 // If the original function was part of a friend declaration,
2061 // inherit its namespace state.
2062 if (D->getFriendObjectKind())
2063 Record->setObjectOfFriendDecl();
2064
2065 // Make sure that anonymous structs and unions are recorded.
2066 if (D->isAnonymousStructOrUnion())
2067 Record->setAnonymousStructOrUnion(true);
2068
2069 if (D->isLocalClass())
2071
2072 // Forward the mangling number from the template to the instantiated decl.
2074 SemaRef.Context.getManglingNumber(D));
2075
2076 // See if the old tag was defined along with a declarator.
2077 // If it did, mark the new tag as being associated with that declarator.
2080
2081 // See if the old tag was defined along with a typedef.
2082 // If it did, mark the new tag as being associated with that typedef.
2085
2086 Owner->addDecl(Record);
2087
2088 // DR1484 clarifies that the members of a local class are instantiated as part
2089 // of the instantiation of their enclosing entity.
2090 if (D->isCompleteDefinition() && D->isLocalClass()) {
2091 Sema::LocalEagerInstantiationScope LocalInstantiations(SemaRef);
2092
2093 SemaRef.InstantiateClass(D->getLocation(), Record, D, TemplateArgs,
2095 /*Complain=*/true);
2096
2097 // For nested local classes, we will instantiate the members when we
2098 // reach the end of the outermost (non-nested) local class.
2099 if (!D->isCXXClassMember())
2100 SemaRef.InstantiateClassMembers(D->getLocation(), Record, TemplateArgs,
2102
2103 // This class may have local implicit instantiations that need to be
2104 // performed within this scope.
2105 LocalInstantiations.perform();
2106 }
2107
2109
2110 if (IsInjectedClassName)
2111 assert(Record->isInjectedClassName() && "Broken injected-class-name");
2112
2113 return Record;
2114}
2115
2116/// Adjust the given function type for an instantiation of the
2117/// given declaration, to cope with modifications to the function's type that
2118/// aren't reflected in the type-source information.
2119///
2120/// \param D The declaration we're instantiating.
2121/// \param TInfo The already-instantiated type.
2123 FunctionDecl *D,
2124 TypeSourceInfo *TInfo) {
2125 const FunctionProtoType *OrigFunc
2126 = D->getType()->castAs<FunctionProtoType>();
2127 const FunctionProtoType *NewFunc
2128 = TInfo->getType()->castAs<FunctionProtoType>();
2129 if (OrigFunc->getExtInfo() == NewFunc->getExtInfo())
2130 return TInfo->getType();
2131
2132 FunctionProtoType::ExtProtoInfo NewEPI = NewFunc->getExtProtoInfo();
2133 NewEPI.ExtInfo = OrigFunc->getExtInfo();
2134 return Context.getFunctionType(NewFunc->getReturnType(),
2135 NewFunc->getParamTypes(), NewEPI);
2136}
2137
2138/// Normal class members are of more specific types and therefore
2139/// don't make it here. This function serves three purposes:
2140/// 1) instantiating function templates
2141/// 2) substituting friend and local function declarations
2142/// 3) substituting deduction guide declarations for nested class templates
2144 FunctionDecl *D, TemplateParameterList *TemplateParams,
2145 RewriteKind FunctionRewriteKind) {
2146 // Check whether there is already a function template specialization for
2147 // this declaration.
2148 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
2149 bool isFriend;
2150 if (FunctionTemplate)
2151 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
2152 else
2153 isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
2154
2155 // Friend function defined withing class template may stop being function
2156 // definition during AST merges from different modules, in this case decl
2157 // with function body should be used for instantiation.
2158 if (isFriend) {
2159 const FunctionDecl *Defn = nullptr;
2160 if (D->hasBody(Defn)) {
2161 D = const_cast<FunctionDecl *>(Defn);
2162 FunctionTemplate = Defn->getDescribedFunctionTemplate();
2163 }
2164 }
2165
2166 if (FunctionTemplate && !TemplateParams) {
2167 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
2168
2169 void *InsertPos = nullptr;
2170 FunctionDecl *SpecFunc
2171 = FunctionTemplate->findSpecialization(Innermost, InsertPos);
2172
2173 // If we already have a function template specialization, return it.
2174 if (SpecFunc)
2175 return SpecFunc;
2176 }
2177
2178 bool MergeWithParentScope = (TemplateParams != nullptr) ||
2179 Owner->isFunctionOrMethod() ||
2180 !(isa<Decl>(Owner) &&
2181 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
2182 LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
2183
2184 ExplicitSpecifier InstantiatedExplicitSpecifier;
2185 if (auto *DGuide = dyn_cast<CXXDeductionGuideDecl>(D)) {
2186 InstantiatedExplicitSpecifier = SemaRef.instantiateExplicitSpecifier(
2187 TemplateArgs, DGuide->getExplicitSpecifier());
2188 if (InstantiatedExplicitSpecifier.isInvalid())
2189 return nullptr;
2190 }
2191
2193 TypeSourceInfo *TInfo = SubstFunctionType(D, Params);
2194 if (!TInfo)
2195 return nullptr;
2197
2198 if (TemplateParams && TemplateParams->size()) {
2199 auto *LastParam =
2200 dyn_cast<TemplateTypeParmDecl>(TemplateParams->asArray().back());
2201 if (LastParam && LastParam->isImplicit() &&
2202 LastParam->hasTypeConstraint()) {
2203 // In abbreviated templates, the type-constraints of invented template
2204 // type parameters are instantiated with the function type, invalidating
2205 // the TemplateParameterList which relied on the template type parameter
2206 // not having a type constraint. Recreate the TemplateParameterList with
2207 // the updated parameter list.
2208 TemplateParams = TemplateParameterList::Create(
2209 SemaRef.Context, TemplateParams->getTemplateLoc(),
2210 TemplateParams->getLAngleLoc(), TemplateParams->asArray(),
2211 TemplateParams->getRAngleLoc(), TemplateParams->getRequiresClause());
2212 }
2213 }
2214
2215 NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
2216 if (QualifierLoc) {
2217 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
2218 TemplateArgs);
2219 if (!QualifierLoc)
2220 return nullptr;
2221 }
2222
2223 Expr *TrailingRequiresClause = D->getTrailingRequiresClause();
2224
2225 // If we're instantiating a local function declaration, put the result
2226 // in the enclosing namespace; otherwise we need to find the instantiated
2227 // context.
2228 DeclContext *DC;
2229 if (D->isLocalExternDecl()) {
2230 DC = Owner;
2232 } else if (isFriend && QualifierLoc) {
2233 CXXScopeSpec SS;
2234 SS.Adopt(QualifierLoc);
2235 DC = SemaRef.computeDeclContext(SS);
2236 if (!DC) return nullptr;
2237 } else {
2239 TemplateArgs);
2240 }
2241
2242 DeclarationNameInfo NameInfo
2243 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
2244
2245 if (FunctionRewriteKind != RewriteKind::None)
2246 adjustForRewrite(FunctionRewriteKind, D, T, TInfo, NameInfo);
2247
2249 if (auto *DGuide = dyn_cast<CXXDeductionGuideDecl>(D)) {
2251 SemaRef.Context, DC, D->getInnerLocStart(),
2252 InstantiatedExplicitSpecifier, NameInfo, T, TInfo,
2253 D->getSourceRange().getEnd(), DGuide->getCorrespondingConstructor(),
2254 DGuide->getDeductionCandidateKind(), TrailingRequiresClause);
2255 Function->setAccess(D->getAccess());
2256 } else {
2258 SemaRef.Context, DC, D->getInnerLocStart(), NameInfo, T, TInfo,
2259 D->getCanonicalDecl()->getStorageClass(), D->UsesFPIntrin(),
2260 D->isInlineSpecified(), D->hasWrittenPrototype(), D->getConstexprKind(),
2261 TrailingRequiresClause);
2262 Function->setFriendConstraintRefersToEnclosingTemplate(
2263 D->FriendConstraintRefersToEnclosingTemplate());
2264 Function->setRangeEnd(D->getSourceRange().getEnd());
2265 }
2266
2267 if (D->isInlined())
2268 Function->setImplicitlyInline();
2269
2270 if (QualifierLoc)
2271 Function->setQualifierInfo(QualifierLoc);
2272
2273 if (D->isLocalExternDecl())
2274 Function->setLocalExternDecl();
2275
2276 DeclContext *LexicalDC = Owner;
2277 if (!isFriend && D->isOutOfLine() && !D->isLocalExternDecl()) {
2278 assert(D->getDeclContext()->isFileContext());
2279 LexicalDC = D->getDeclContext();
2280 }
2281 else if (D->isLocalExternDecl()) {
2282 LexicalDC = SemaRef.CurContext;
2283 }
2284
2285 Function->setLexicalDeclContext(LexicalDC);
2286
2287 // Attach the parameters
2288 for (unsigned P = 0; P < Params.size(); ++P)
2289 if (Params[P])
2290 Params[P]->setOwningFunction(Function);
2291 Function->setParams(Params);
2292
2293 if (TrailingRequiresClause)
2294 Function->setTrailingRequiresClause(TrailingRequiresClause);
2295
2296 if (TemplateParams) {
2297 // Our resulting instantiation is actually a function template, since we
2298 // are substituting only the outer template parameters. For example, given
2299 //
2300 // template<typename T>
2301 // struct X {
2302 // template<typename U> friend void f(T, U);
2303 // };
2304 //
2305 // X<int> x;
2306 //
2307 // We are instantiating the friend function template "f" within X<int>,
2308 // which means substituting int for T, but leaving "f" as a friend function
2309 // template.
2310 // Build the function template itself.
2311 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, DC,
2312 Function->getLocation(),
2313 Function->getDeclName(),
2314 TemplateParams, Function);
2315 Function->setDescribedFunctionTemplate(FunctionTemplate);
2316
2317 FunctionTemplate->setLexicalDeclContext(LexicalDC);
2318
2319 if (isFriend && D->isThisDeclarationADefinition()) {
2320 FunctionTemplate->setInstantiatedFromMemberTemplate(
2321 D->getDescribedFunctionTemplate());
2322 }
2323 } else if (FunctionTemplate &&
2324 SemaRef.CodeSynthesisContexts.back().Kind !=
2326 // Record this function template specialization.
2327 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
2328 Function->setFunctionTemplateSpecialization(FunctionTemplate,
2330 Innermost),
2331 /*InsertPos=*/nullptr);
2332 } else if (FunctionRewriteKind == RewriteKind::None) {
2333 if (isFriend && D->isThisDeclarationADefinition()) {
2334 // Do not connect the friend to the template unless it's actually a
2335 // definition. We don't want non-template functions to be marked as being
2336 // template instantiations.
2337 Function->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
2338 } else if (!isFriend) {
2339 // If this is not a function template, and this is not a friend (that is,
2340 // this is a locally declared function), save the instantiation
2341 // relationship for the purposes of constraint instantiation.
2342 Function->setInstantiatedFromDecl(D);
2343 }
2344 }
2345
2346 if (isFriend) {
2347 Function->setObjectOfFriendDecl();
2348 if (FunctionTemplateDecl *FT = Function->getDescribedFunctionTemplate())
2349 FT->setObjectOfFriendDecl();
2350 }
2351
2353 Function->setInvalidDecl();
2354
2355 bool IsExplicitSpecialization = false;
2356
2358 SemaRef, Function->getDeclName(), SourceLocation(),
2361 D->isLocalExternDecl() ? RedeclarationKind::ForExternalRedeclaration
2362 : SemaRef.forRedeclarationInCurContext());
2363
2365 D->getDependentSpecializationInfo()) {
2366 assert(isFriend && "dependent specialization info on "
2367 "non-member non-friend function?");
2368
2369 // Instantiate the explicit template arguments.
2370 TemplateArgumentListInfo ExplicitArgs;
2371 if (const auto *ArgsWritten = DFTSI->TemplateArgumentsAsWritten) {
2372 ExplicitArgs.setLAngleLoc(ArgsWritten->getLAngleLoc());
2373 ExplicitArgs.setRAngleLoc(ArgsWritten->getRAngleLoc());
2374 if (SemaRef.SubstTemplateArguments(ArgsWritten->arguments(), TemplateArgs,
2375 ExplicitArgs))
2376 return nullptr;
2377 }
2378
2379 // Map the candidates for the primary template to their instantiations.
2380 for (FunctionTemplateDecl *FTD : DFTSI->getCandidates()) {
2381 if (NamedDecl *ND =
2382 SemaRef.FindInstantiatedDecl(D->getLocation(), FTD, TemplateArgs))
2383 Previous.addDecl(ND);
2384 else
2385 return nullptr;
2386 }
2387
2389 Function,
2390 DFTSI->TemplateArgumentsAsWritten ? &ExplicitArgs : nullptr,
2391 Previous))
2392 Function->setInvalidDecl();
2393
2394 IsExplicitSpecialization = true;
2395 } else if (const ASTTemplateArgumentListInfo *ArgsWritten =
2396 D->getTemplateSpecializationArgsAsWritten()) {
2397 // The name of this function was written as a template-id.
2398 SemaRef.LookupQualifiedName(Previous, DC);
2399
2400 // Instantiate the explicit template arguments.
2401 TemplateArgumentListInfo ExplicitArgs(ArgsWritten->getLAngleLoc(),
2402 ArgsWritten->getRAngleLoc());
2403 if (SemaRef.SubstTemplateArguments(ArgsWritten->arguments(), TemplateArgs,
2404 ExplicitArgs))
2405 return nullptr;
2406
2408 &ExplicitArgs,
2409 Previous))
2410 Function->setInvalidDecl();
2411
2412 IsExplicitSpecialization = true;
2413 } else if (TemplateParams || !FunctionTemplate) {
2414 // Look only into the namespace where the friend would be declared to
2415 // find a previous declaration. This is the innermost enclosing namespace,
2416 // as described in ActOnFriendFunctionDecl.
2418
2419 // In C++, the previous declaration we find might be a tag type
2420 // (class or enum). In this case, the new declaration will hide the
2421 // tag type. Note that this does not apply if we're declaring a
2422 // typedef (C++ [dcl.typedef]p4).
2423 if (Previous.isSingleTagDecl())
2424 Previous.clear();
2425
2426 // Filter out previous declarations that don't match the scope. The only
2427 // effect this has is to remove declarations found in inline namespaces
2428 // for friend declarations with unqualified names.
2429 if (isFriend && !QualifierLoc) {
2430 SemaRef.FilterLookupForScope(Previous, DC, /*Scope=*/ nullptr,
2431 /*ConsiderLinkage=*/ true,
2432 QualifierLoc.hasQualifier());
2433 }
2434 }
2435
2436 // Per [temp.inst], default arguments in function declarations at local scope
2437 // are instantiated along with the enclosing declaration. For example:
2438 //
2439 // template<typename T>
2440 // void ft() {
2441 // void f(int = []{ return T::value; }());
2442 // }
2443 // template void ft<int>(); // error: type 'int' cannot be used prior
2444 // to '::' because it has no members
2445 //
2446 // The error is issued during instantiation of ft<int>() because substitution
2447 // into the default argument fails; the default argument is instantiated even
2448 // though it is never used.
2449 if (Function->isLocalExternDecl()) {
2450 for (ParmVarDecl *PVD : Function->parameters()) {
2451 if (!PVD->hasDefaultArg())
2452 continue;
2453 if (SemaRef.SubstDefaultArgument(D->getInnerLocStart(), PVD, TemplateArgs)) {
2454 // If substitution fails, the default argument is set to a
2455 // RecoveryExpr that wraps the uninstantiated default argument so
2456 // that downstream diagnostics are omitted.
2457 Expr *UninstExpr = PVD->getUninstantiatedDefaultArg();
2458 ExprResult ErrorResult = SemaRef.CreateRecoveryExpr(
2459 UninstExpr->getBeginLoc(), UninstExpr->getEndLoc(),
2460 { UninstExpr }, UninstExpr->getType());
2461 if (ErrorResult.isUsable())
2462 PVD->setDefaultArg(ErrorResult.get());
2463 }
2464 }
2465 }
2466
2467 SemaRef.CheckFunctionDeclaration(/*Scope*/ nullptr, Function, Previous,
2468 IsExplicitSpecialization,
2469 Function->isThisDeclarationADefinition());
2470
2471 // Check the template parameter list against the previous declaration. The
2472 // goal here is to pick up default arguments added since the friend was
2473 // declared; we know the template parameter lists match, since otherwise
2474 // we would not have picked this template as the previous declaration.
2475 if (isFriend && TemplateParams && FunctionTemplate->getPreviousDecl()) {
2477 TemplateParams,
2478 FunctionTemplate->getPreviousDecl()->getTemplateParameters(),
2479 Function->isThisDeclarationADefinition()
2482 }
2483
2484 // If we're introducing a friend definition after the first use, trigger
2485 // instantiation.
2486 // FIXME: If this is a friend function template definition, we should check
2487 // to see if any specializations have been used.
2488 if (isFriend && D->isThisDeclarationADefinition() && Function->isUsed(false)) {
2489 if (MemberSpecializationInfo *MSInfo =
2490 Function->getMemberSpecializationInfo()) {
2491 if (MSInfo->getPointOfInstantiation().isInvalid()) {
2492 SourceLocation Loc = D->getLocation(); // FIXME
2493 MSInfo->setPointOfInstantiation(Loc);
2494 SemaRef.PendingLocalImplicitInstantiations.push_back(
2495 std::make_pair(Function, Loc));
2496 }
2497 }
2498 }
2499
2500 if (D->isExplicitlyDefaulted()) {
2502 return nullptr;
2503 }
2504 if (D->isDeleted())
2505 SemaRef.SetDeclDeleted(Function, D->getLocation(), D->getDeletedMessage());
2506
2507 NamedDecl *PrincipalDecl =
2508 (TemplateParams ? cast<NamedDecl>(FunctionTemplate) : Function);
2509
2510 // If this declaration lives in a different context from its lexical context,
2511 // add it to the corresponding lookup table.
2512 if (isFriend ||
2513 (Function->isLocalExternDecl() && !Function->getPreviousDecl()))
2514 DC->makeDeclVisibleInContext(PrincipalDecl);
2515
2516 if (Function->isOverloadedOperator() && !DC->isRecord() &&
2518 PrincipalDecl->setNonMemberOperator();
2519
2520 return Function;
2521}
2522
2524 CXXMethodDecl *D, TemplateParameterList *TemplateParams,
2525 RewriteKind FunctionRewriteKind) {
2526 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
2527 if (FunctionTemplate && !TemplateParams) {
2528 // We are creating a function template specialization from a function
2529 // template. Check whether there is already a function template
2530 // specialization for this particular set of template arguments.
2531 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
2532
2533 void *InsertPos = nullptr;
2534 FunctionDecl *SpecFunc
2535 = FunctionTemplate->findSpecialization(Innermost, InsertPos);
2536
2537 // If we already have a function template specialization, return it.
2538 if (SpecFunc)
2539 return SpecFunc;
2540 }
2541
2542 bool isFriend;
2543 if (FunctionTemplate)
2544 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
2545 else
2546 isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
2547
2548 bool MergeWithParentScope = (TemplateParams != nullptr) ||
2549 !(isa<Decl>(Owner) &&
2550 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
2551 LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
2552
2554 SemaRef, const_cast<CXXMethodDecl *>(D), TemplateArgs, Scope);
2555
2556 // Instantiate enclosing template arguments for friends.
2558 unsigned NumTempParamLists = 0;
2559 if (isFriend && (NumTempParamLists = D->getNumTemplateParameterLists())) {
2560 TempParamLists.resize(NumTempParamLists);
2561 for (unsigned I = 0; I != NumTempParamLists; ++I) {
2562 TemplateParameterList *TempParams = D->getTemplateParameterList(I);
2563 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
2564 if (!InstParams)
2565 return nullptr;
2566 TempParamLists[I] = InstParams;
2567 }
2568 }
2569
2570 auto InstantiatedExplicitSpecifier = ExplicitSpecifier::getFromDecl(D);
2571 // deduction guides need this
2572 const bool CouldInstantiate =
2573 InstantiatedExplicitSpecifier.getExpr() == nullptr ||
2574 !InstantiatedExplicitSpecifier.getExpr()->isValueDependent();
2575
2576 // Delay the instantiation of the explicit-specifier until after the
2577 // constraints are checked during template argument deduction.
2578 if (CouldInstantiate ||
2579 SemaRef.CodeSynthesisContexts.back().Kind !=
2581 InstantiatedExplicitSpecifier = SemaRef.instantiateExplicitSpecifier(
2582 TemplateArgs, InstantiatedExplicitSpecifier);
2583
2584 if (InstantiatedExplicitSpecifier.isInvalid())
2585 return nullptr;
2586 } else {
2587 InstantiatedExplicitSpecifier.setKind(ExplicitSpecKind::Unresolved);
2588 }
2589
2590 // Implicit destructors/constructors created for local classes in
2591 // DeclareImplicit* (see SemaDeclCXX.cpp) might not have an associated TSI.
2592 // Unfortunately there isn't enough context in those functions to
2593 // conditionally populate the TSI without breaking non-template related use
2594 // cases. Populate TSIs prior to calling SubstFunctionType to make sure we get
2595 // a proper transformation.
2596 if (cast<CXXRecordDecl>(D->getParent())->isLambda() &&
2597 !D->getTypeSourceInfo() &&
2598 isa<CXXConstructorDecl, CXXDestructorDecl>(D)) {
2599 TypeSourceInfo *TSI =
2600 SemaRef.Context.getTrivialTypeSourceInfo(D->getType());
2601 D->setTypeSourceInfo(TSI);
2602 }
2603
2605 TypeSourceInfo *TInfo = SubstFunctionType(D, Params);
2606 if (!TInfo)
2607 return nullptr;
2609
2610 if (TemplateParams && TemplateParams->size()) {
2611 auto *LastParam =
2612 dyn_cast<TemplateTypeParmDecl>(TemplateParams->asArray().back());
2613 if (LastParam && LastParam->isImplicit() &&
2614 LastParam->hasTypeConstraint()) {
2615 // In abbreviated templates, the type-constraints of invented template
2616 // type parameters are instantiated with the function type, invalidating
2617 // the TemplateParameterList which relied on the template type parameter
2618 // not having a type constraint. Recreate the TemplateParameterList with
2619 // the updated parameter list.
2620 TemplateParams = TemplateParameterList::Create(
2621 SemaRef.Context, TemplateParams->getTemplateLoc(),
2622 TemplateParams->getLAngleLoc(), TemplateParams->asArray(),
2623 TemplateParams->getRAngleLoc(), TemplateParams->getRequiresClause());
2624 }
2625 }
2626
2627 NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
2628 if (QualifierLoc) {
2629 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
2630 TemplateArgs);
2631 if (!QualifierLoc)
2632 return nullptr;
2633 }
2634
2635 DeclContext *DC = Owner;
2636 if (isFriend) {
2637 if (QualifierLoc) {
2638 CXXScopeSpec SS;
2639 SS.Adopt(QualifierLoc);
2640 DC = SemaRef.computeDeclContext(SS);
2641
2642 if (DC && SemaRef.RequireCompleteDeclContext(SS, DC))
2643 return nullptr;
2644 } else {
2645 DC = SemaRef.FindInstantiatedContext(D->getLocation(),
2646 D->getDeclContext(),
2647 TemplateArgs);
2648 }
2649 if (!DC) return nullptr;
2650 }
2651
2652 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
2653 Expr *TrailingRequiresClause = D->getTrailingRequiresClause();
2654
2655 DeclarationNameInfo NameInfo
2656 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
2657
2658 if (FunctionRewriteKind != RewriteKind::None)
2659 adjustForRewrite(FunctionRewriteKind, D, T, TInfo, NameInfo);
2660
2661 // Build the instantiated method declaration.
2662 CXXMethodDecl *Method = nullptr;
2663
2664 SourceLocation StartLoc = D->getInnerLocStart();
2665 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
2667 SemaRef.Context, Record, StartLoc, NameInfo, T, TInfo,
2668 InstantiatedExplicitSpecifier, Constructor->UsesFPIntrin(),
2669 Constructor->isInlineSpecified(), false,
2670 Constructor->getConstexprKind(), InheritedConstructor(),
2671 TrailingRequiresClause);
2672 Method->setRangeEnd(Constructor->getEndLoc());
2673 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
2675 SemaRef.Context, Record, StartLoc, NameInfo, T, TInfo,
2676 Destructor->UsesFPIntrin(), Destructor->isInlineSpecified(), false,
2677 Destructor->getConstexprKind(), TrailingRequiresClause);
2678 Method->setIneligibleOrNotSelected(true);
2679 Method->setRangeEnd(Destructor->getEndLoc());
2681 SemaRef.Context.getCanonicalType(
2682 SemaRef.Context.getTypeDeclType(Record))));
2683 } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) {
2685 SemaRef.Context, Record, StartLoc, NameInfo, T, TInfo,
2686 Conversion->UsesFPIntrin(), Conversion->isInlineSpecified(),
2687 InstantiatedExplicitSpecifier, Conversion->getConstexprKind(),
2688 Conversion->getEndLoc(), TrailingRequiresClause);
2689 } else {
2690 StorageClass SC = D->isStatic() ? SC_Static : SC_None;
2691 Method = CXXMethodDecl::Create(
2692 SemaRef.Context, Record, StartLoc, NameInfo, T, TInfo, SC,
2693 D->UsesFPIntrin(), D->isInlineSpecified(), D->getConstexprKind(),
2694 D->getEndLoc(), TrailingRequiresClause);
2695 }
2696
2697 if (D->isInlined())
2698 Method->setImplicitlyInline();
2699
2700 if (QualifierLoc)
2701 Method->setQualifierInfo(QualifierLoc);
2702
2703 if (TemplateParams) {
2704 // Our resulting instantiation is actually a function template, since we
2705 // are substituting only the outer template parameters. For example, given
2706 //
2707 // template<typename T>
2708 // struct X {
2709 // template<typename U> void f(T, U);
2710 // };
2711 //
2712 // X<int> x;
2713 //
2714 // We are instantiating the member template "f" within X<int>, which means
2715 // substituting int for T, but leaving "f" as a member function template.
2716 // Build the function template itself.
2717 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Record,
2718 Method->getLocation(),
2719 Method->getDeclName(),
2720 TemplateParams, Method);
2721 if (isFriend) {
2722 FunctionTemplate->setLexicalDeclContext(Owner);
2723 FunctionTemplate->setObjectOfFriendDecl();
2724 } else if (D->isOutOfLine())
2725 FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
2726 Method->setDescribedFunctionTemplate(FunctionTemplate);
2727 } else if (FunctionTemplate) {
2728 // Record this function template specialization.
2729 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
2730 Method->setFunctionTemplateSpecialization(FunctionTemplate,
2732 Innermost),
2733 /*InsertPos=*/nullptr);
2734 } else if (!isFriend && FunctionRewriteKind == RewriteKind::None) {
2735 // Record that this is an instantiation of a member function.
2737 }
2738
2739 // If we are instantiating a member function defined
2740 // out-of-line, the instantiation will have the same lexical
2741 // context (which will be a namespace scope) as the template.
2742 if (isFriend) {
2743 if (NumTempParamLists)
2745 SemaRef.Context,
2746 llvm::ArrayRef(TempParamLists.data(), NumTempParamLists));
2747
2748 Method->setLexicalDeclContext(Owner);
2749 Method->setObjectOfFriendDecl();
2750 } else if (D->isOutOfLine())
2752
2753 // Attach the parameters
2754 for (unsigned P = 0; P < Params.size(); ++P)
2755 Params[P]->setOwningFunction(Method);
2756 Method->setParams(Params);
2757
2758 if (InitMethodInstantiation(Method, D))
2759 Method->setInvalidDecl();
2760
2762 RedeclarationKind::ForExternalRedeclaration);
2763
2764 bool IsExplicitSpecialization = false;
2765
2766 // If the name of this function was written as a template-id, instantiate
2767 // the explicit template arguments.
2769 D->getDependentSpecializationInfo()) {
2770 // Instantiate the explicit template arguments.
2771 TemplateArgumentListInfo ExplicitArgs;
2772 if (const auto *ArgsWritten = DFTSI->TemplateArgumentsAsWritten) {
2773 ExplicitArgs.setLAngleLoc(ArgsWritten->getLAngleLoc());
2774 ExplicitArgs.setRAngleLoc(ArgsWritten->getRAngleLoc());
2775 if (SemaRef.SubstTemplateArguments(ArgsWritten->arguments(), TemplateArgs,
2776 ExplicitArgs))
2777 return nullptr;
2778 }
2779
2780 // Map the candidates for the primary template to their instantiations.
2781 for (FunctionTemplateDecl *FTD : DFTSI->getCandidates()) {
2782 if (NamedDecl *ND =
2783 SemaRef.FindInstantiatedDecl(D->getLocation(), FTD, TemplateArgs))
2784 Previous.addDecl(ND);
2785 else
2786 return nullptr;
2787 }
2788
2790 Method, DFTSI->TemplateArgumentsAsWritten ? &ExplicitArgs : nullptr,
2791 Previous))
2792 Method->setInvalidDecl();
2793
2794 IsExplicitSpecialization = true;
2795 } else if (const ASTTemplateArgumentListInfo *ArgsWritten =
2796 D->getTemplateSpecializationArgsAsWritten()) {
2797 SemaRef.LookupQualifiedName(Previous, DC);
2798
2799 TemplateArgumentListInfo ExplicitArgs(ArgsWritten->getLAngleLoc(),
2800 ArgsWritten->getRAngleLoc());
2801
2802 if (SemaRef.SubstTemplateArguments(ArgsWritten->arguments(), TemplateArgs,
2803 ExplicitArgs))
2804 return nullptr;
2805
2806 if (SemaRef.CheckFunctionTemplateSpecialization(Method,
2807 &ExplicitArgs,
2808 Previous))
2809 Method->setInvalidDecl();
2810
2811 IsExplicitSpecialization = true;
2812 } else if (!FunctionTemplate || TemplateParams || isFriend) {
2814
2815 // In C++, the previous declaration we find might be a tag type
2816 // (class or enum). In this case, the new declaration will hide the
2817 // tag type. Note that this does not apply if we're declaring a
2818 // typedef (C++ [dcl.typedef]p4).
2819 if (Previous.isSingleTagDecl())
2820 Previous.clear();
2821 }
2822
2823 // Per [temp.inst], default arguments in member functions of local classes
2824 // are instantiated along with the member function declaration. For example:
2825 //
2826 // template<typename T>
2827 // void ft() {
2828 // struct lc {
2829 // int operator()(int p = []{ return T::value; }());
2830 // };
2831 // }
2832 // template void ft<int>(); // error: type 'int' cannot be used prior
2833 // to '::'because it has no members
2834 //
2835 // The error is issued during instantiation of ft<int>()::lc::operator()
2836 // because substitution into the default argument fails; the default argument
2837 // is instantiated even though it is never used.
2839 for (unsigned P = 0; P < Params.size(); ++P) {
2840 if (!Params[P]->hasDefaultArg())
2841 continue;
2842 if (SemaRef.SubstDefaultArgument(StartLoc, Params[P], TemplateArgs)) {
2843 // If substitution fails, the default argument is set to a
2844 // RecoveryExpr that wraps the uninstantiated default argument so
2845 // that downstream diagnostics are omitted.
2846 Expr *UninstExpr = Params[P]->getUninstantiatedDefaultArg();
2847 ExprResult ErrorResult = SemaRef.CreateRecoveryExpr(
2848 UninstExpr->getBeginLoc(), UninstExpr->getEndLoc(),
2849 { UninstExpr }, UninstExpr->getType());
2850 if (ErrorResult.isUsable())
2851 Params[P]->setDefaultArg(ErrorResult.get());
2852 }
2853 }
2854 }
2855
2856 SemaRef.CheckFunctionDeclaration(nullptr, Method, Previous,
2857 IsExplicitSpecialization,
2859
2860 if (D->isPureVirtual())
2861 SemaRef.CheckPureMethod(Method, SourceRange());
2862
2863 // Propagate access. For a non-friend declaration, the access is
2864 // whatever we're propagating from. For a friend, it should be the
2865 // previous declaration we just found.
2866 if (isFriend && Method->getPreviousDecl())
2867 Method->setAccess(Method->getPreviousDecl()->getAccess());
2868 else
2869 Method->setAccess(D->getAccess());
2870 if (FunctionTemplate)
2871 FunctionTemplate->setAccess(Method->getAccess());
2872
2873 SemaRef.CheckOverrideControl(Method);
2874
2875 // If a function is defined as defaulted or deleted, mark it as such now.
2876 if (D->isExplicitlyDefaulted()) {
2877 if (SubstDefaultedFunction(Method, D))
2878 return nullptr;
2879 }
2880 if (D->isDeletedAsWritten())
2881 SemaRef.SetDeclDeleted(Method, Method->getLocation(),
2882 D->getDeletedMessage());
2883
2884 // If this is an explicit specialization, mark the implicitly-instantiated
2885 // template specialization as being an explicit specialization too.
2886 // FIXME: Is this necessary?
2887 if (IsExplicitSpecialization && !isFriend)
2888 SemaRef.CompleteMemberSpecialization(Method, Previous);
2889
2890 // If the method is a special member function, we need to mark it as
2891 // ineligible so that Owner->addDecl() won't mark the class as non trivial.
2892 // At the end of the class instantiation, we calculate eligibility again and
2893 // then we adjust trivility if needed.
2894 // We need this check to happen only after the method parameters are set,
2895 // because being e.g. a copy constructor depends on the instantiated
2896 // arguments.
2897 if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Method)) {
2898 if (Constructor->isDefaultConstructor() ||
2899 Constructor->isCopyOrMoveConstructor())
2900 Method->setIneligibleOrNotSelected(true);
2901 } else if (Method->isCopyAssignmentOperator() ||
2902 Method->isMoveAssignmentOperator()) {
2903 Method->setIneligibleOrNotSelected(true);
2904 }
2905
2906 // If there's a function template, let our caller handle it.
2907 if (FunctionTemplate) {
2908 // do nothing
2909
2910 // Don't hide a (potentially) valid declaration with an invalid one.
2911 } else if (Method->isInvalidDecl() && !Previous.empty()) {
2912 // do nothing
2913
2914 // Otherwise, check access to friends and make them visible.
2915 } else if (isFriend) {
2916 // We only need to re-check access for methods which we didn't
2917 // manage to match during parsing.
2918 if (!D->getPreviousDecl())
2919 SemaRef.CheckFriendAccess(Method);
2920
2921 Record->makeDeclVisibleInContext(Method);
2922
2923 // Otherwise, add the declaration. We don't need to do this for
2924 // class-scope specializations because we'll have matched them with
2925 // the appropriate template.
2926 } else {
2927 Owner->addDecl(Method);
2928 }
2929
2930 // PR17480: Honor the used attribute to instantiate member function
2931 // definitions
2932 if (Method->hasAttr<UsedAttr>()) {
2933 if (const auto *A = dyn_cast<CXXRecordDecl>(Owner)) {
2935 if (const MemberSpecializationInfo *MSInfo =
2936 A->getMemberSpecializationInfo())
2937 Loc = MSInfo->getPointOfInstantiation();
2938 else if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(A))
2939 Loc = Spec->getPointOfInstantiation();
2940 SemaRef.MarkFunctionReferenced(Loc, Method);
2941 }
2942 }
2943
2944 return Method;
2945}
2946
2947Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
2948 return VisitCXXMethodDecl(D);
2949}
2950
2951Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
2952 return VisitCXXMethodDecl(D);
2953}
2954
2955Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
2956 return VisitCXXMethodDecl(D);
2957}
2958
2959Decl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
2960 return SemaRef.SubstParmVarDecl(D, TemplateArgs, /*indexAdjustment*/ 0,
2961 std::nullopt,
2962 /*ExpectParameterPack=*/false);
2963}
2964
2965Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl(
2967 assert(D->getTypeForDecl()->isTemplateTypeParmType());
2968
2969 std::optional<unsigned> NumExpanded;
2970
2971 if (const TypeConstraint *TC = D->getTypeConstraint()) {
2972 if (D->isPackExpansion() && !D->isExpandedParameterPack()) {
2973 assert(TC->getTemplateArgsAsWritten() &&
2974 "type parameter can only be an expansion when explicit arguments "
2975 "are specified");
2976 // The template type parameter pack's type is a pack expansion of types.
2977 // Determine whether we need to expand this parameter pack into separate
2978 // types.
2980 for (auto &ArgLoc : TC->getTemplateArgsAsWritten()->arguments())
2981 SemaRef.collectUnexpandedParameterPacks(ArgLoc, Unexpanded);
2982
2983 // Determine whether the set of unexpanded parameter packs can and should
2984 // be expanded.
2985 bool Expand = true;
2986 bool RetainExpansion = false;
2988 cast<CXXFoldExpr>(TC->getImmediatelyDeclaredConstraint())
2989 ->getEllipsisLoc(),
2990 SourceRange(TC->getConceptNameLoc(),
2991 TC->hasExplicitTemplateArgs() ?
2992 TC->getTemplateArgsAsWritten()->getRAngleLoc() :
2993 TC->getConceptNameInfo().getEndLoc()),
2994 Unexpanded, TemplateArgs, Expand, RetainExpansion, NumExpanded))
2995 return nullptr;
2996 }
2997 }
2998
3000 SemaRef.Context, Owner, D->getBeginLoc(), D->getLocation(),
3001 D->getDepth() - TemplateArgs.getNumSubstitutedLevels(), D->getIndex(),
3002 D->getIdentifier(), D->wasDeclaredWithTypename(), D->isParameterPack(),
3003 D->hasTypeConstraint(), NumExpanded);
3004
3005 Inst->setAccess(AS_public);
3006 Inst->setImplicit(D->isImplicit());
3007 if (auto *TC = D->getTypeConstraint()) {
3008 if (!D->isImplicit()) {
3009 // Invented template parameter type constraints will be instantiated
3010 // with the corresponding auto-typed parameter as it might reference
3011 // other parameters.
3012 if (SemaRef.SubstTypeConstraint(Inst, TC, TemplateArgs,
3013 EvaluateConstraints))
3014 return nullptr;
3015 }
3016 }
3017 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited()) {
3018 TemplateArgumentLoc Output;
3019 if (!SemaRef.SubstTemplateArgument(D->getDefaultArgument(), TemplateArgs,
3020 Output))
3021 Inst->setDefaultArgument(SemaRef.getASTContext(), Output);
3022 }
3023
3024 // Introduce this template parameter's instantiation into the instantiation
3025 // scope.
3027
3028 return Inst;
3029}
3030
3031Decl *TemplateDeclInstantiator::VisitNonTypeTemplateParmDecl(
3033 // Substitute into the type of the non-type template parameter.
3034 TypeLoc TL = D->getTypeSourceInfo()->getTypeLoc();
3035 SmallVector<TypeSourceInfo *, 4> ExpandedParameterPackTypesAsWritten;
3036 SmallVector<QualType, 4> ExpandedParameterPackTypes;
3037 bool IsExpandedParameterPack = false;
3038 TypeSourceInfo *DI;
3039 QualType T;
3040 bool Invalid = false;
3041
3042 if (D->isExpandedParameterPack()) {
3043 // The non-type template parameter pack is an already-expanded pack
3044 // expansion of types. Substitute into each of the expanded types.
3045 ExpandedParameterPackTypes.reserve(D->getNumExpansionTypes());
3046 ExpandedParameterPackTypesAsWritten.reserve(D->getNumExpansionTypes());
3047 for (unsigned I = 0, N = D->getNumExpansionTypes(); I != N; ++I) {
3048 TypeSourceInfo *NewDI =
3049 SemaRef.SubstType(D->getExpansionTypeSourceInfo(I), TemplateArgs,
3050 D->getLocation(), D->getDeclName());
3051 if (!NewDI)
3052 return nullptr;
3053
3054 QualType NewT =
3056 if (NewT.isNull())
3057 return nullptr;
3058
3059 ExpandedParameterPackTypesAsWritten.push_back(NewDI);
3060 ExpandedParameterPackTypes.push_back(NewT);
3061 }
3062
3063 IsExpandedParameterPack = true;
3064 DI = D->getTypeSourceInfo();
3065 T = DI->getType();
3066 } else if (D->isPackExpansion()) {
3067 // The non-type template parameter pack's type is a pack expansion of types.
3068 // Determine whether we need to expand this parameter pack into separate
3069 // types.
3071 TypeLoc Pattern = Expansion.getPatternLoc();
3073 SemaRef.collectUnexpandedParameterPacks(Pattern, Unexpanded);
3074
3075 // Determine whether the set of unexpanded parameter packs can and should
3076 // be expanded.
3077 bool Expand = true;
3078 bool RetainExpansion = false;
3079 std::optional<unsigned> OrigNumExpansions =
3080 Expansion.getTypePtr()->getNumExpansions();
3081 std::optional<unsigned> NumExpansions = OrigNumExpansions;
3082 if (SemaRef.CheckParameterPacksForExpansion(Expansion.getEllipsisLoc(),
3083 Pattern.getSourceRange(),
3084 Unexpanded,
3085 TemplateArgs,
3086 Expand, RetainExpansion,
3087 NumExpansions))
3088 return nullptr;
3089
3090 if (Expand) {
3091 for (unsigned I = 0; I != *NumExpansions; ++I) {
3092 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
3093 TypeSourceInfo *NewDI = SemaRef.SubstType(Pattern, TemplateArgs,
3094 D->getLocation(),
3095 D->getDeclName());
3096 if (!NewDI)
3097 return nullptr;
3098
3099 QualType NewT =
3101 if (NewT.isNull())
3102 return nullptr;
3103
3104 ExpandedParameterPackTypesAsWritten.push_back(NewDI);
3105 ExpandedParameterPackTypes.push_back(NewT);
3106 }
3107
3108 // Note that we have an expanded parameter pack. The "type" of this
3109 // expanded parameter pack is the original expansion type, but callers
3110 // will end up using the expanded parameter pack types for type-checking.
3111 IsExpandedParameterPack = true;
3112 DI = D->getTypeSourceInfo();
3113 T = DI->getType();
3114 } else {
3115 // We cannot fully expand the pack expansion now, so substitute into the
3116 // pattern and create a new pack expansion type.
3117 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
3118 TypeSourceInfo *NewPattern = SemaRef.SubstType(Pattern, TemplateArgs,
3119 D->getLocation(),
3120 D->getDeclName());
3121 if (!NewPattern)
3122 return nullptr;
3123
3124 SemaRef.CheckNonTypeTemplateParameterType(NewPattern, D->getLocation());
3125 DI = SemaRef.CheckPackExpansion(NewPattern, Expansion.getEllipsisLoc(),
3126 NumExpansions);
3127 if (!DI)
3128 return nullptr;
3129
3130 T = DI->getType();
3131 }
3132 } else {
3133 // Simple case: substitution into a parameter that is not a parameter pack.
3134 DI = SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs,
3135 D->getLocation(), D->getDeclName());
3136 if (!DI)
3137 return nullptr;
3138
3139 // Check that this type is acceptable for a non-type template parameter.
3141 if (T.isNull()) {
3142 T = SemaRef.Context.IntTy;
3143 Invalid = true;
3144 }
3145 }
3146
3148 if (IsExpandedParameterPack)
3150 SemaRef.Context, Owner, D->getInnerLocStart(), D->getLocation(),
3151 D->getDepth() - TemplateArgs.getNumSubstitutedLevels(),
3152 D->getPosition(), D->getIdentifier(), T, DI, ExpandedParameterPackTypes,
3153 ExpandedParameterPackTypesAsWritten);
3154 else
3156 SemaRef.Context, Owner, D->getInnerLocStart(), D->getLocation(),
3157 D->getDepth() - TemplateArgs.getNumSubstitutedLevels(),
3158 D->getPosition(), D->getIdentifier(), T, D->isParameterPack(), DI);
3159
3160 if (AutoTypeLoc AutoLoc = DI->getTypeLoc().getContainedAutoTypeLoc())
3161 if (AutoLoc.isConstrained()) {
3162 SourceLocation EllipsisLoc;
3163 if (IsExpandedParameterPack)
3164 EllipsisLoc =
3165 DI->getTypeLoc().getAs<PackExpansionTypeLoc>().getEllipsisLoc();
3166 else if (auto *Constraint = dyn_cast_if_present<CXXFoldExpr>(
3167 D->getPlaceholderTypeConstraint()))
3168 EllipsisLoc = Constraint->getEllipsisLoc();
3169 // Note: We attach the uninstantiated constriant here, so that it can be
3170 // instantiated relative to the top level, like all our other
3171 // constraints.
3172 if (SemaRef.AttachTypeConstraint(AutoLoc, /*NewConstrainedParm=*/Param,
3173 /*OrigConstrainedParm=*/D, EllipsisLoc))
3174 Invalid = true;
3175 }
3176
3177 Param->setAccess(AS_public);
3178 Param->setImplicit(D->isImplicit());
3179 if (Invalid)
3180 Param->setInvalidDecl();
3181
3182 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited()) {
3183 EnterExpressionEvaluationContext ConstantEvaluated(
3186 if (!SemaRef.SubstTemplateArgument(D->getDefaultArgument(), TemplateArgs,
3187 Result))
3188 Param->setDefaultArgument(SemaRef.Context, Result);
3189 }
3190
3191 // Introduce this template parameter's instantiation into the instantiation
3192 // scope.
3194 return Param;
3195}
3196
3198 Sema &S,
3199 TemplateParameterList *Params,
3201 for (const auto &P : *Params) {
3202 if (P->isTemplateParameterPack())
3203 continue;
3204 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P))
3205 S.collectUnexpandedParameterPacks(NTTP->getTypeSourceInfo()->getTypeLoc(),
3206 Unexpanded);
3207 if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(P))
3208 collectUnexpandedParameterPacks(S, TTP->getTemplateParameters(),
3209 Unexpanded);
3210 }
3211}
3212
3213Decl *
3214TemplateDeclInstantiator::VisitTemplateTemplateParmDecl(
3216 // Instantiate the template parameter list of the template template parameter.
3217 TemplateParameterList *TempParams = D->getTemplateParameters();
3218 TemplateParameterList *InstParams;
3220
3221 bool IsExpandedParameterPack = false;
3222
3223 if (D->isExpandedParameterPack()) {
3224 // The template template parameter pack is an already-expanded pack
3225 // expansion of template parameters. Substitute into each of the expanded
3226 // parameters.
3227 ExpandedParams.reserve(D->getNumExpansionTemplateParameters());
3228 for (unsigned I = 0, N = D->getNumExpansionTemplateParameters();
3229 I != N; ++I) {
3231 TemplateParameterList *Expansion =
3232 SubstTemplateParams(D->getExpansionTemplateParameters(I));
3233 if (!Expansion)
3234 return nullptr;
3235 ExpandedParams.push_back(Expansion);
3236 }
3237
3238 IsExpandedParameterPack = true;
3239 InstParams = TempParams;
3240 } else if (D->isPackExpansion()) {
3241 // The template template parameter pack expands to a pack of template
3242 // template parameters. Determine whether we need to expand this parameter
3243 // pack into separate parameters.
3245 collectUnexpandedParameterPacks(SemaRef, D->getTemplateParameters(),
3246 Unexpanded);
3247
3248 // Determine whether the set of unexpanded parameter packs can and should
3249 // be expanded.
3250 bool Expand = true;
3251 bool RetainExpansion = false;
3252 std::optional<unsigned> NumExpansions;
3254 TempParams->getSourceRange(),
3255 Unexpanded,
3256 TemplateArgs,
3257 Expand, RetainExpansion,
3258 NumExpansions))
3259 return nullptr;
3260
3261 if (Expand) {
3262 for (unsigned I = 0; I != *NumExpansions; ++I) {
3263 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
3265 TemplateParameterList *Expansion = SubstTemplateParams(TempParams);
3266 if (!Expansion)
3267 return nullptr;
3268 ExpandedParams.push_back(Expansion);
3269 }
3270
3271 // Note that we have an expanded parameter pack. The "type" of this
3272 // expanded parameter pack is the original expansion type, but callers
3273 // will end up using the expanded parameter pack types for type-checking.
3274 IsExpandedParameterPack = true;
3275 InstParams = TempParams;
3276 } else {
3277 // We cannot fully expand the pack expansion now, so just substitute
3278 // into the pattern.
3279 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
3280
3282 InstParams = SubstTemplateParams(TempParams);
3283 if (!InstParams)
3284 return nullptr;
3285 }
3286 } else {
3287 // Perform the actual substitution of template parameters within a new,
3288 // local instantiation scope.
3290 InstParams = SubstTemplateParams(TempParams);
3291 if (!InstParams)
3292 return nullptr;
3293 }
3294
3295 // Build the template template parameter.
3297 if (IsExpandedParameterPack)
3299 SemaRef.Context, Owner, D->getLocation(),
3300 D->getDepth() - TemplateArgs.getNumSubstitutedLevels(),
3301 D->getPosition(), D->getIdentifier(), D->wasDeclaredWithTypename(),
3302 InstParams, ExpandedParams);
3303 else
3305 SemaRef.Context, Owner, D->getLocation(),
3306 D->getDepth() - TemplateArgs.getNumSubstitutedLevels(),
3307 D->getPosition(), D->isParameterPack(), D->getIdentifier(),
3308 D->wasDeclaredWithTypename(), InstParams);
3309 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited()) {
3310 NestedNameSpecifierLoc QualifierLoc =
3311 D->getDefaultArgument().getTemplateQualifierLoc();
3312 QualifierLoc =
3313 SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgs);
3314 TemplateName TName = SemaRef.SubstTemplateName(
3315 QualifierLoc, D->getDefaultArgument().getArgument().getAsTemplate(),
3316 D->getDefaultArgument().getTemplateNameLoc(), TemplateArgs);
3317 if (!TName.isNull())
3318 Param->setDefaultArgument(
3319 SemaRef.Context,
3321 D->getDefaultArgument().getTemplateQualifierLoc(),
3322 D->getDefaultArgument().getTemplateNameLoc()));
3323 }
3324 Param->setAccess(AS_public);
3325 Param->setImplicit(D->isImplicit());
3326
3327 // Introduce this template parameter's instantiation into the instantiation
3328 // scope.
3330
3331 return Param;
3332}
3333
3334Decl *TemplateDeclInstantiator::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
3335 // Using directives are never dependent (and never contain any types or
3336 // expressions), so they require no explicit instantiation work.
3337
3338 UsingDirectiveDecl *Inst
3339 = UsingDirectiveDecl::Create(SemaRef.Context, Owner, D->getLocation(),
3340 D->getNamespaceKeyLocation(),
3341 D->getQualifierLoc(),
3342 D->getIdentLocation(),
3343 D->getNominatedNamespace(),
3344 D->getCommonAncestor());
3345
3346 // Add the using directive to its declaration context
3347 // only if this is not a function or method.
3348 if (!Owner->isFunctionOrMethod())
3349 Owner->addDecl(Inst);
3350
3351 return Inst;
3352}
3353
3355 BaseUsingDecl *Inst,
3356 LookupResult *Lookup) {
3357
3358 bool isFunctionScope = Owner->isFunctionOrMethod();
3359
3360 for (auto *Shadow : D->shadows()) {
3361 // FIXME: UsingShadowDecl doesn't preserve its immediate target, so
3362 // reconstruct it in the case where it matters. Hm, can we extract it from
3363 // the DeclSpec when parsing and save it in the UsingDecl itself?
3364 NamedDecl *OldTarget = Shadow->getTargetDecl();
3365 if (auto *CUSD = dyn_cast<ConstructorUsingShadowDecl>(Shadow))
3366 if (auto *BaseShadow = CUSD->getNominatedBaseClassShadowDecl())
3367 OldTarget = BaseShadow;
3368
3369 NamedDecl *InstTarget = nullptr;
3370 if (auto *EmptyD =
3371 dyn_cast<UnresolvedUsingIfExistsDecl>(Shadow->getTargetDecl())) {
3373 SemaRef.Context, Owner, EmptyD->getLocation(), EmptyD->getDeclName());
3374 } else {
3375 InstTarget = cast_or_null<NamedDecl>(SemaRef.FindInstantiatedDecl(
3376 Shadow->getLocation(), OldTarget, TemplateArgs));
3377 }
3378 if (!InstTarget)
3379 return nullptr;
3380
3381 UsingShadowDecl *PrevDecl = nullptr;
3382 if (Lookup &&
3383 SemaRef.CheckUsingShadowDecl(Inst, InstTarget, *Lookup, PrevDecl))
3384 continue;
3385
3386 if (UsingShadowDecl *OldPrev = getPreviousDeclForInstantiation(Shadow))
3387 PrevDecl = cast_or_null<UsingShadowDecl>(SemaRef.FindInstantiatedDecl(
3388 Shadow->getLocation(), OldPrev, TemplateArgs));
3389
3390 UsingShadowDecl *InstShadow = SemaRef.BuildUsingShadowDecl(
3391 /*Scope*/ nullptr, Inst, InstTarget, PrevDecl);
3392 SemaRef.Context.setInstantiatedFromUsingShadowDecl(InstShadow, Shadow);
3393
3394 if (isFunctionScope)
3395 SemaRef.CurrentInstantiationScope->InstantiatedLocal(Shadow, InstShadow);
3396 }
3397
3398 return Inst;
3399}
3400
3401Decl *TemplateDeclInstantiator::VisitUsingDecl(UsingDecl *D) {
3402
3403 // The nested name specifier may be dependent, for example
3404 // template <typename T> struct t {
3405 // struct s1 { T f1(); };
3406 // struct s2 : s1 { using s1::f1; };
3407 // };
3408 // template struct t<int>;
3409 // Here, in using s1::f1, s1 refers to t<T>::s1;
3410 // we need to substitute for t<int>::s1.
3411 NestedNameSpecifierLoc QualifierLoc
3412 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
3413 TemplateArgs);
3414 if (!QualifierLoc)
3415 return nullptr;
3416
3417 // For an inheriting constructor declaration, the name of the using
3418 // declaration is the name of a constructor in this class, not in the
3419 // base class.
3420 DeclarationNameInfo NameInfo = D->getNameInfo();
3422 if (auto *RD = dyn_cast<CXXRecordDecl>(SemaRef.CurContext))
3424 SemaRef.Context.getCanonicalType(SemaRef.Context.getRecordType(RD))));
3425
3426 // We only need to do redeclaration lookups if we're in a class scope (in
3427 // fact, it's not really even possible in non-class scopes).
3428 bool CheckRedeclaration = Owner->isRecord();
3429 LookupResult Prev(SemaRef, NameInfo, Sema::LookupUsingDeclName,
3430 RedeclarationKind::ForVisibleRedeclaration);
3431
3432 UsingDecl *NewUD = UsingDecl::Create(SemaRef.Context, Owner,
3433 D->getUsingLoc(),
3434 QualifierLoc,
3435 NameInfo,
3436 D->hasTypename());
3437
3438 CXXScopeSpec SS;
3439 SS.Adopt(QualifierLoc);
3440 if (CheckRedeclaration) {
3441 Prev.setHideTags(false);
3442 SemaRef.LookupQualifiedName(Prev, Owner);
3443
3444 // Check for invalid redeclarations.
3445 if (SemaRef.CheckUsingDeclRedeclaration(D->getUsingLoc(),
3446 D->hasTypename(), SS,
3447 D->getLocation(), Prev))
3448 NewUD->setInvalidDecl();
3449 }
3450
3451 if (!NewUD->isInvalidDecl() &&
3452 SemaRef.CheckUsingDeclQualifier(D->getUsingLoc(), D->hasTypename(), SS,
3453 NameInfo, D->getLocation(), nullptr, D))
3454 NewUD->setInvalidDecl();
3455
3456 SemaRef.Context.setInstantiatedFromUsingDecl(NewUD, D);
3457 NewUD->setAccess(D->getAccess());
3458 Owner->addDecl(NewUD);
3459
3460 // Don't process the shadow decls for an invalid decl.
3461 if (NewUD->isInvalidDecl())
3462 return NewUD;
3463
3464 // If the using scope was dependent, or we had dependent bases, we need to
3465 // recheck the inheritance
3468
3469 return VisitBaseUsingDecls(D, NewUD, CheckRedeclaration ? &Prev : nullptr);
3470}
3471
3472Decl *TemplateDeclInstantiator::VisitUsingEnumDecl(UsingEnumDecl *D) {
3473 // Cannot be a dependent type, but still could be an instantiation
3474 EnumDecl *EnumD = cast_or_null<EnumDecl>(SemaRef.FindInstantiatedDecl(
3475 D->getLocation(), D->getEnumDecl(), TemplateArgs));
3476
3477 if (SemaRef.RequireCompleteEnumDecl(EnumD, EnumD->getLocation()))
3478 return nullptr;
3479
3480 TypeSourceInfo *TSI = SemaRef.SubstType(D->getEnumType(), TemplateArgs,
3481 D->getLocation(), D->getDeclName());
3482
3483 if (!TSI)
3484 return nullptr;
3485
3486 UsingEnumDecl *NewUD =
3487 UsingEnumDecl::Create(SemaRef.Context, Owner, D->getUsingLoc(),
3488 D->getEnumLoc(), D->getLocation(), TSI);
3489
3491 NewUD->setAccess(D->getAccess());
3492 Owner->addDecl(NewUD);
3493
3494 // Don't process the shadow decls for an invalid decl.
3495 if (NewUD->isInvalidDecl())
3496 return NewUD;
3497
3498 // We don't have to recheck for duplication of the UsingEnumDecl itself, as it
3499 // cannot be dependent, and will therefore have been checked during template
3500 // definition.
3501
3502 return VisitBaseUsingDecls(D, NewUD, nullptr);
3503}
3504
3505Decl *TemplateDeclInstantiator::VisitUsingShadowDecl(UsingShadowDecl *D) {
3506 // Ignore these; we handle them in bulk when processing the UsingDecl.
3507 return nullptr;
3508}
3509
3510Decl *TemplateDeclInstantiator::VisitConstructorUsingShadowDecl(
3512 // Ignore these; we handle them in bulk when processing the UsingDecl.
3513 return nullptr;
3514}
3515
3516template <typename T>
3517Decl *TemplateDeclInstantiator::instantiateUnresolvedUsingDecl(
3518 T *D, bool InstantiatingPackElement) {
3519 // If this is a pack expansion, expand it now.
3520 if (D->isPackExpansion() && !InstantiatingPackElement) {
3522 SemaRef.collectUnexpandedParameterPacks(D->getQualifierLoc(), Unexpanded);
3523 SemaRef.collectUnexpandedParameterPacks(D->getNameInfo(), Unexpanded);
3524
3525 // Determine whether the set of unexpanded parameter packs can and should
3526 // be expanded.
3527 bool Expand = true;
3528 bool RetainExpansion = false;
3529 std::optional<unsigned> NumExpansions;
3531 D->getEllipsisLoc(), D->getSourceRange(), Unexpanded, TemplateArgs,
3532 Expand, RetainExpansion, NumExpansions))
3533 return nullptr;
3534
3535 // This declaration cannot appear within a function template signature,
3536 // so we can't have a partial argument list for a parameter pack.
3537 assert(!RetainExpansion &&
3538 "should never need to retain an expansion for UsingPackDecl");
3539
3540 if (!Expand) {
3541 // We cannot fully expand the pack expansion now, so substitute into the
3542 // pattern and create a new pack expansion.
3543 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
3544 return instantiateUnresolvedUsingDecl(D, true);
3545 }
3546
3547 // Within a function, we don't have any normal way to check for conflicts
3548 // between shadow declarations from different using declarations in the
3549 // same pack expansion, but this is always ill-formed because all expansions
3550 // must produce (conflicting) enumerators.
3551 //
3552 // Sadly we can't just reject this in the template definition because it
3553 // could be valid if the pack is empty or has exactly one expansion.
3554 if (D->getDeclContext()->isFunctionOrMethod() && *NumExpansions > 1) {
3555 SemaRef.Diag(D->getEllipsisLoc(),
3556 diag::err_using_decl_redeclaration_expansion);
3557 return nullptr;
3558 }
3559
3560 // Instantiate the slices of this pack and build a UsingPackDecl.
3561 SmallVector<NamedDecl*, 8> Expansions;
3562 for (unsigned I = 0; I != *NumExpansions; ++I) {
3563 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
3564 Decl *Slice = instantiateUnresolvedUsingDecl(D, true);
3565 if (!Slice)
3566 return nullptr;
3567 // Note that we can still get unresolved using declarations here, if we
3568 // had arguments for all packs but the pattern also contained other
3569 // template arguments (this only happens during partial substitution, eg
3570 // into the body of a generic lambda in a function template).
3571 Expansions.push_back(cast<NamedDecl>(Slice));
3572 }
3573
3574 auto *NewD = SemaRef.BuildUsingPackDecl(D, Expansions);
3577 return NewD;
3578 }
3579
3580 UnresolvedUsingTypenameDecl *TD = dyn_cast<UnresolvedUsingTypenameDecl>(D);
3581 SourceLocation TypenameLoc = TD ? TD->getTypenameLoc() : SourceLocation();
3582
3583 NestedNameSpecifierLoc QualifierLoc
3584 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
3585 TemplateArgs);
3586 if (!QualifierLoc)
3587 return nullptr;
3588
3589 CXXScopeSpec SS;
3590 SS.Adopt(QualifierLoc);
3591
3592 DeclarationNameInfo NameInfo
3593 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
3594
3595 // Produce a pack expansion only if we're not instantiating a particular
3596 // slice of a pack expansion.
3597 bool InstantiatingSlice = D->getEllipsisLoc().isValid() &&
3598 SemaRef.ArgumentPackSubstitutionIndex != -1;
3599 SourceLocation EllipsisLoc =
3600 InstantiatingSlice ? SourceLocation() : D->getEllipsisLoc();
3601
3602 bool IsUsingIfExists = D->template hasAttr<UsingIfExistsAttr>();
3603 NamedDecl *UD = SemaRef.BuildUsingDeclaration(
3604 /*Scope*/ nullptr, D->getAccess(), D->getUsingLoc(),
3605 /*HasTypename*/ TD, TypenameLoc, SS, NameInfo, EllipsisLoc,
3607 /*IsInstantiation*/ true, IsUsingIfExists);
3608 if (UD) {
3609 SemaRef.InstantiateAttrs(TemplateArgs, D, UD);
3611 }
3612
3613 return UD;
3614}
3615
3616Decl *TemplateDeclInstantiator::VisitUnresolvedUsingTypenameDecl(
3618 return instantiateUnresolvedUsingDecl(D);
3619}
3620
3621Decl *TemplateDeclInstantiator::VisitUnresolvedUsingValueDecl(
3623 return instantiateUnresolvedUsingDecl(D);
3624}
3625
3626Decl *TemplateDeclInstantiator::VisitUnresolvedUsingIfExistsDecl(
3628 llvm_unreachable("referring to unresolved decl out of UsingShadowDecl");
3629}
3630
3631Decl *TemplateDeclInstantiator::VisitUsingPackDecl(UsingPackDecl *D) {
3632 SmallVector<NamedDecl*, 8> Expansions;
3633 for (auto *UD : D->expansions()) {
3634 if (NamedDecl *NewUD =
3635 SemaRef.FindInstantiatedDecl(D->getLocation(), UD, TemplateArgs))
3636 Expansions.push_back(NewUD);
3637 else
3638 return nullptr;
3639 }
3640
3641 auto *NewD = SemaRef.BuildUsingPackDecl(D, Expansions);
3644 return NewD;
3645}
3646
3647Decl *TemplateDeclInstantiator::VisitOMPThreadPrivateDecl(
3650 for (auto *I : D->varlist()) {
3651 Expr *Var = SemaRef.SubstExpr(I, TemplateArgs).get();
3652 assert(isa<DeclRefExpr>(Var) && "threadprivate arg is not a DeclRefExpr");
3653 Vars.push_back(Var);
3654 }
3655
3657 SemaRef.OpenMP().CheckOMPThreadPrivateDecl(D->getLocation(), Vars);
3658
3659 TD->setAccess(AS_public);
3660 Owner->addDecl(TD);
3661
3662 return TD;
3663}
3664
3665Decl *TemplateDeclInstantiator::VisitOMPAllocateDecl(OMPAllocateDecl *D) {
3667 for (auto *I : D->varlist()) {
3668 Expr *Var = SemaRef.SubstExpr(I, TemplateArgs).get();
3669 assert(isa<DeclRefExpr>(Var) && "allocate arg is not a DeclRefExpr");
3670 Vars.push_back(Var);
3671 }
3673 // Copy map clauses from the original mapper.
3674 for (OMPClause *C : D->clauselists()) {
3675 OMPClause *IC = nullptr;
3676 if (auto *AC = dyn_cast<OMPAllocatorClause>(C)) {
3677 ExprResult NewE = SemaRef.SubstExpr(AC->getAllocator(), TemplateArgs);
3678 if (!NewE.isUsable())
3679 continue;
3680 IC = SemaRef.OpenMP().ActOnOpenMPAllocatorClause(
3681 NewE.get(), AC->getBeginLoc(), AC->getLParenLoc(), AC->getEndLoc());
3682 } else if (auto *AC = dyn_cast<OMPAlignClause>(C)) {
3683 ExprResult NewE = SemaRef.SubstExpr(AC->getAlignment(), TemplateArgs);
3684 if (!NewE.isUsable())
3685 continue;
3686 IC = SemaRef.OpenMP().ActOnOpenMPAlignClause(
3687 NewE.get(), AC->getBeginLoc(), AC->getLParenLoc(), AC->getEndLoc());
3688 // If align clause value ends up being invalid, this can end up null.
3689 if (!IC)
3690 continue;
3691 }
3692 Clauses.push_back(IC);
3693 }
3694
3696 D->getLocation(), Vars, Clauses, Owner);
3697 if (Res.get().isNull())
3698 return nullptr;
3699 return Res.get().getSingleDecl();
3700}
3701
3702Decl *TemplateDeclInstantiator::VisitOMPRequiresDecl(OMPRequiresDecl *D) {
3703 llvm_unreachable(
3704 "Requires directive cannot be instantiated within a dependent context");
3705}
3706
3707Decl *TemplateDeclInstantiator::VisitOMPDeclareReductionDecl(
3709 // Instantiate type and check if it is allowed.
3710 const bool RequiresInstantiation =
3711 D->getType()->isDependentType() ||
3712 D->getType()->isInstantiationDependentType() ||
3713 D->getType()->containsUnexpandedParameterPack();
3714 QualType SubstReductionType;
3715 if (RequiresInstantiation) {
3716 SubstReductionType = SemaRef.OpenMP().ActOnOpenMPDeclareReductionType(
3717 D->getLocation(),
3719 D->getType(), TemplateArgs, D->getLocation(), DeclarationName())));
3720 } else {
3721 SubstReductionType = D->getType();
3722 }
3723 if (SubstReductionType.isNull())
3724 return nullptr;
3725 Expr *Combiner = D->getCombiner();
3726 Expr *Init = D->getInitializer();
3727 bool IsCorrect = true;
3728 // Create instantiated copy.
3729 std::pair<QualType, SourceLocation> ReductionTypes[] = {
3730 std::make_pair(SubstReductionType, D->getLocation())};
3731 auto *PrevDeclInScope = D->getPrevDeclInScope();
3732 if (PrevDeclInScope && !PrevDeclInScope->isInvalidDecl()) {
3733 PrevDeclInScope = cast<OMPDeclareReductionDecl>(
3734 cast<Decl *>(*SemaRef.CurrentInstantiationScope->findInstantiationOf(
3735 PrevDeclInScope)));
3736 }
3738 /*S=*/nullptr, Owner, D->getDeclName(), ReductionTypes, D->getAccess(),
3739 PrevDeclInScope);
3740 auto *NewDRD = cast<OMPDeclareReductionDecl>(DRD.get().getSingleDecl());
3742 Expr *SubstCombiner = nullptr;
3743 Expr *SubstInitializer = nullptr;
3744 // Combiners instantiation sequence.
3745 if (Combiner) {
3747 /*S=*/nullptr, NewDRD);
3749 cast<DeclRefExpr>(D->getCombinerIn())->getDecl(),
3750 cast<DeclRefExpr>(NewDRD->getCombinerIn())->getDecl());
3752 cast<DeclRefExpr>(D->getCombinerOut())->getDecl(),
3753 cast<DeclRefExpr>(NewDRD->getCombinerOut())->getDecl());
3754 auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(Owner);
3755 Sema::CXXThisScopeRAII ThisScope(SemaRef, ThisContext, Qualifiers(),
3756 ThisContext);
3757 SubstCombiner = SemaRef.SubstExpr(Combiner, TemplateArgs).get();
3759 SubstCombiner);
3760 }
3761 // Initializers instantiation sequence.
3762 if (Init) {
3763 VarDecl *OmpPrivParm =
3765 /*S=*/nullptr, NewDRD);
3767 cast<DeclRefExpr>(D->getInitOrig())->getDecl(),
3768 cast<DeclRefExpr>(NewDRD->getInitOrig())->getDecl());
3770 cast<DeclRefExpr>(D->getInitPriv())->getDecl(),
3771 cast<DeclRefExpr>(NewDRD->getInitPriv())->getDecl());
3772 if (D->getInitializerKind() == OMPDeclareReductionInitKind::Call) {
3773 SubstInitializer = SemaRef.SubstExpr(Init, TemplateArgs).get();
3774 } else {
3775 auto *OldPrivParm =
3776 cast<VarDecl>(cast<DeclRefExpr>(D->getInitPriv())->getDecl());
3777 IsCorrect = IsCorrect && OldPrivParm->hasInit();
3778 if (IsCorrect)
3779 SemaRef.InstantiateVariableInitializer(OmpPrivParm, OldPrivParm,
3780 TemplateArgs);
3781 }
3783 NewDRD, SubstInitializer, OmpPrivParm);
3784 }
3785 IsCorrect = IsCorrect && SubstCombiner &&
3786 (!Init ||
3787 (D->getInitializerKind() == OMPDeclareReductionInitKind::Call &&
3788 SubstInitializer) ||
3789 (D->getInitializerKind() != OMPDeclareReductionInitKind::Call &&
3790 !SubstInitializer));
3791
3793 /*S=*/nullptr, DRD, IsCorrect && !D->isInvalidDecl());
3794
3795 return NewDRD;
3796}
3797
3798Decl *
3799TemplateDeclInstantiator::VisitOMPDeclareMapperDecl(OMPDeclareMapperDecl *D) {
3800 // Instantiate type and check if it is allowed.
3801 const bool RequiresInstantiation =
3802 D->getType()->isDependentType() ||
3803 D->getType()->isInstantiationDependentType() ||
3804 D->getType()->containsUnexpandedParameterPack();
3805 QualType SubstMapperTy;
3806 DeclarationName VN = D->getVarName();
3807 if (RequiresInstantiation) {
3808 SubstMapperTy = SemaRef.OpenMP().ActOnOpenMPDeclareMapperType(
3809 D->getLocation(),
3810 ParsedType::make(SemaRef.SubstType(D->getType(), TemplateArgs,
3811 D->getLocation(), VN)));
3812 } else {
3813 SubstMapperTy = D->getType();
3814 }
3815 if (SubstMapperTy.isNull())
3816 return nullptr;
3817 // Create an instantiated copy of mapper.
3818 auto *PrevDeclInScope = D->getPrevDeclInScope();
3819 if (PrevDeclInScope && !PrevDeclInScope->isInvalidDecl()) {
3820 PrevDeclInScope = cast<OMPDeclareMapperDecl>(
3821 cast<Decl *>(*SemaRef.CurrentInstantiationScope->findInstantiationOf(
3822 PrevDeclInScope)));
3823 }
3824 bool IsCorrect = true;
3826 // Instantiate the mapper variable.
3827 DeclarationNameInfo DirName;
3828 SemaRef.OpenMP().StartOpenMPDSABlock(llvm::omp::OMPD_declare_mapper, DirName,
3829 /*S=*/nullptr,
3830 (*D->clauselist_begin())->getBeginLoc());
3831 ExprResult MapperVarRef =
3833 /*S=*/nullptr, SubstMapperTy, D->getLocation(), VN);
3835 cast<DeclRefExpr>(D->getMapperVarRef())->getDecl(),
3836 cast<DeclRefExpr>(MapperVarRef.get())->getDecl());
3837 auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(Owner);
3838 Sema::CXXThisScopeRAII ThisScope(SemaRef, ThisContext, Qualifiers(),
3839 ThisContext);
3840 // Instantiate map clauses.
3841 for (OMPClause *C : D->clauselists()) {
3842 auto *OldC = cast<OMPMapClause>(C);
3843 SmallVector<Expr *, 4> NewVars;
3844 for (Expr *OE : OldC->varlist()) {
3845 Expr *NE = SemaRef.SubstExpr(OE, TemplateArgs).get();
3846 if (!NE) {
3847 IsCorrect = false;
3848 break;
3849 }
3850 NewVars.push_back(NE);
3851 }
3852 if (!IsCorrect)
3853 break;
3854 NestedNameSpecifierLoc NewQualifierLoc =
3855 SemaRef.SubstNestedNameSpecifierLoc(OldC->getMapperQualifierLoc(),
3856 TemplateArgs);
3857 CXXScopeSpec SS;
3858 SS.Adopt(NewQualifierLoc);
3859 DeclarationNameInfo NewNameInfo =
3860 SemaRef.SubstDeclarationNameInfo(OldC->getMapperIdInfo(), TemplateArgs);
3861 OMPVarListLocTy Locs(OldC->getBeginLoc(), OldC->getLParenLoc(),
3862 OldC->getEndLoc());
3863 OMPClause *NewC = SemaRef.OpenMP().ActOnOpenMPMapClause(
3864 OldC->getIteratorModifier(), OldC->getMapTypeModifiers(),
3865 OldC->getMapTypeModifiersLoc(), SS, NewNameInfo, OldC->getMapType(),
3866 OldC->isImplicitMapType(), OldC->getMapLoc(), OldC->getColonLoc(),
3867 NewVars, Locs);
3868 Clauses.push_back(NewC);
3869 }
3870 SemaRef.OpenMP().EndOpenMPDSABlock(nullptr);
3871 if (!IsCorrect)
3872 return nullptr;
3874 /*S=*/nullptr, Owner, D->getDeclName(), SubstMapperTy, D->getLocation(),
3875 VN, D->getAccess(), MapperVarRef.get(), Clauses, PrevDeclInScope);
3876 Decl *NewDMD = DG.get().getSingleDecl();
3878 return NewDMD;
3879}
3880
3881Decl *TemplateDeclInstantiator::VisitOMPCapturedExprDecl(
3882 OMPCapturedExprDecl * /*D*/) {
3883 llvm_unreachable("Should not be met in templates");
3884}
3885
3887 return VisitFunctionDecl(D, nullptr);
3888}
3889
3890Decl *
3891TemplateDeclInstantiator::VisitCXXDeductionGuideDecl(CXXDeductionGuideDecl *D) {
3892 Decl *Inst = VisitFunctionDecl(D, nullptr);
3893 if (Inst && !D->getDescribedFunctionTemplate())
3894 Owner->addDecl(Inst);
3895 return Inst;
3896}
3897
3899 return VisitCXXMethodDecl(D, nullptr);
3900}
3901
3902Decl *TemplateDeclInstantiator::VisitRecordDecl(RecordDecl *D) {
3903 llvm_unreachable("There are only CXXRecordDecls in C++");
3904}
3905
3906Decl *
3907TemplateDeclInstantiator::VisitClassTemplateSpecializationDecl(
3909 // As a MS extension, we permit class-scope explicit specialization
3910 // of member class templates.
3911 ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
3912 assert(ClassTemplate->getDeclContext()->isRecord() &&
3913 D->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
3914 "can only instantiate an explicit specialization "
3915 "for a member class template");
3916
3917 // Lookup the already-instantiated declaration in the instantiation
3918 // of the class template.
3919 ClassTemplateDecl *InstClassTemplate =
3920 cast_or_null<ClassTemplateDecl>(SemaRef.FindInstantiatedDecl(
3921 D->getLocation(), ClassTemplate, TemplateArgs));
3922 if (!InstClassTemplate)
3923 return nullptr;
3924
3925 // Substitute into the template arguments of the class template explicit
3926 // specialization.
3927 TemplateArgumentListInfo InstTemplateArgs;
3928 if (const ASTTemplateArgumentListInfo *TemplateArgsInfo =
3929 D->getTemplateArgsAsWritten()) {
3930 InstTemplateArgs.setLAngleLoc(TemplateArgsInfo->getLAngleLoc());
3931 InstTemplateArgs.setRAngleLoc(TemplateArgsInfo->getRAngleLoc());
3932
3933 if (SemaRef.SubstTemplateArguments(TemplateArgsInfo->arguments(),
3934 TemplateArgs, InstTemplateArgs))
3935 return nullptr;
3936 }
3937
3938 // Check that the template argument list is well-formed for this
3939 // class template.
3940 SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
3941 if (SemaRef.CheckTemplateArgumentList(
3942 InstClassTemplate, D->getLocation(), InstTemplateArgs,
3943 /*DefaultArgs=*/{}, false, SugaredConverted, CanonicalConverted,
3944 /*UpdateArgsWithConversions=*/true))
3945 return nullptr;
3946
3947 // Figure out where to insert this class template explicit specialization
3948 // in the member template's set of class template explicit specializations.
3949 void *InsertPos = nullptr;
3951 InstClassTemplate->findSpecialization(CanonicalConverted, InsertPos);
3952
3953 // Check whether we've already seen a conflicting instantiation of this
3954 // declaration (for instance, if there was a prior implicit instantiation).
3955 bool Ignored;
3956 if (PrevDecl &&
3958 D->getSpecializationKind(),
3959 PrevDecl,
3960 PrevDecl->getSpecializationKind(),
3961 PrevDecl->getPointOfInstantiation(),
3962 Ignored))
3963 return nullptr;
3964
3965 // If PrevDecl was a definition and D is also a definition, diagnose.
3966 // This happens in cases like:
3967 //
3968 // template<typename T, typename U>
3969 // struct Outer {
3970 // template<typename X> struct Inner;
3971 // template<> struct Inner<T> {};
3972 // template<> struct Inner<U> {};
3973 // };
3974 //
3975 // Outer<int, int> outer; // error: the explicit specializations of Inner
3976 // // have the same signature.
3977 if (PrevDecl && PrevDecl->getDefinition() &&
3978 D->isThisDeclarationADefinition()) {
3979 SemaRef.Diag(D->getLocation(), diag::err_redefinition) << PrevDecl;
3980 SemaRef.Diag(PrevDecl->getDefinition()->getLocation(),
3981 diag::note_previous_definition);
3982 return nullptr;
3983 }
3984
3985 // Create the class template partial specialization declaration.
3988 SemaRef.Context, D->getTagKind(), Owner, D->getBeginLoc(),
3989 D->getLocation(), InstClassTemplate, CanonicalConverted, PrevDecl);
3990 InstD->setTemplateArgsAsWritten(InstTemplateArgs);
3991
3992 // Add this partial specialization to the set of class template partial
3993 // specializations.
3994 if (!PrevDecl)
3995 InstClassTemplate->AddSpecialization(InstD, InsertPos);
3996
3997 // Substitute the nested name specifier, if any.
3998 if (SubstQualifier(D, InstD))
3999 return nullptr;
4000
4001 InstD->setAccess(D->getAccess());
4003 InstD->setSpecializationKind(D->getSpecializationKind());
4004 InstD->setExternKeywordLoc(D->getExternKeywordLoc());
4005 InstD->setTemplateKeywordLoc(D->getTemplateKeywordLoc());
4006
4007 Owner->addDecl(InstD);
4008
4009 // Instantiate the members of the class-scope explicit specialization eagerly.
4010 // We don't have support for lazy instantiation of an explicit specialization
4011 // yet, and MSVC eagerly instantiates in this case.
4012 // FIXME: This is wrong in standard C++.
4013 if (D->isThisDeclarationADefinition() &&
4014 SemaRef.InstantiateClass(D->getLocation(), InstD, D, TemplateArgs,
4016 /*Complain=*/true))
4017 return nullptr;
4018
4019 return InstD;
4020}
4021
4024
4025 TemplateArgumentListInfo VarTemplateArgsInfo;
4026 VarTemplateDecl *VarTemplate = D->getSpecializedTemplate();
4027 assert(VarTemplate &&
4028 "A template specialization without specialized template?");
4029
4030 VarTemplateDecl *InstVarTemplate =
4031 cast_or_null<VarTemplateDecl>(SemaRef.FindInstantiatedDecl(
4032 D->getLocation(), VarTemplate, TemplateArgs));
4033 if (!InstVarTemplate)
4034 return nullptr;
4035
4036 // Substitute the current template arguments.
4037 if (const ASTTemplateArgumentListInfo *TemplateArgsInfo =
4038 D->getTemplateArgsAsWritten()) {
4039 VarTemplateArgsInfo.setLAngleLoc(TemplateArgsInfo->getLAngleLoc());
4040 VarTemplateArgsInfo.setRAngleLoc(TemplateArgsInfo->getRAngleLoc());
4041
4042 if (SemaRef.SubstTemplateArguments(TemplateArgsInfo->arguments(),
4043 TemplateArgs, VarTemplateArgsInfo))
4044 return nullptr;
4045 }
4046
4047 // Check that the template argument list is well-formed for this template.
4048 SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
4049 if (SemaRef.CheckTemplateArgumentList(
4050 InstVarTemplate, D->getLocation(), VarTemplateArgsInfo,
4051 /*DefaultArgs=*/{}, false, SugaredConverted, CanonicalConverted,
4052 /*UpdateArgsWithConversions=*/true))
4053 return nullptr;
4054
4055 // Check whether we've already seen a declaration of this specialization.
4056 void *InsertPos = nullptr;
4058 InstVarTemplate->findSpecialization(CanonicalConverted, InsertPos);
4059
4060 // Check whether we've already seen a conflicting instantiation of this
4061 // declaration (for instance, if there was a prior implicit instantiation).
4062 bool Ignored;
4063 if (PrevDecl && SemaRef.CheckSpecializationInstantiationRedecl(
4064 D->getLocation(), D->getSpecializationKind(), PrevDecl,
4065 PrevDecl->getSpecializationKind(),
4066 PrevDecl->getPointOfInstantiation(), Ignored))
4067 return nullptr;
4068
4070 InstVarTemplate, D, VarTemplateArgsInfo, CanonicalConverted, PrevDecl);
4071}
4072
4074 VarTemplateDecl *VarTemplate, VarDecl *D,
4075 const TemplateArgumentListInfo &TemplateArgsInfo,
4078
4079 // Do substitution on the type of the declaration
4080 TypeSourceInfo *DI =
4081 SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs,
4082 D->getTypeSpecStartLoc(), D->getDeclName());
4083 if (!DI)
4084 return nullptr;
4085
4086 if (DI->getType()->isFunctionType()) {
4087 SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function)
4088 << D->isStaticDataMember() << DI->getType();
4089 return nullptr;
4090 }
4091
4092 // Build the instantiated declaration
4094 SemaRef.Context, Owner, D->getInnerLocStart(), D->getLocation(),
4095 VarTemplate, DI->getType(), DI, D->getStorageClass(), Converted);
4096 Var->setTemplateArgsAsWritten(TemplateArgsInfo);
4097 if (!PrevDecl) {
4098 void *InsertPos = nullptr;
4099 VarTemplate->findSpecialization(Converted, InsertPos);
4100 VarTemplate->AddSpecialization(Var, InsertPos);
4101 }
4102
4103 if (SemaRef.getLangOpts().OpenCL)
4104 SemaRef.deduceOpenCLAddressSpace(Var);
4105
4106 // Substitute the nested name specifier, if any.
4107 if (SubstQualifier(D, Var))
4108 return nullptr;
4109
4110 SemaRef.BuildVariableInstantiation(Var, D, TemplateArgs, LateAttrs, Owner,
4111 StartingScope, false, PrevDecl);
4112
4113 return Var;
4114}
4115
4116Decl *TemplateDeclInstantiator::VisitObjCAtDefsFieldDecl(ObjCAtDefsFieldDecl *D) {
4117 llvm_unreachable("@defs is not supported in Objective-C++");
4118}
4119
4120Decl *TemplateDeclInstantiator::VisitFriendTemplateDecl(FriendTemplateDecl *D) {
4121 // FIXME: We need to be able to instantiate FriendTemplateDecls.
4122 unsigned DiagID = SemaRef.getDiagnostics().getCustomDiagID(
4124 "cannot instantiate %0 yet");
4125 SemaRef.Diag(D->getLocation(), DiagID)
4126 << D->getDeclKindName();
4127
4128 return nullptr;
4129}
4130
4131Decl *TemplateDeclInstantiator::VisitConceptDecl(ConceptDecl *D) {
4132 llvm_unreachable("Concept definitions cannot reside inside a template");
4133}
4134
4135Decl *TemplateDeclInstantiator::VisitImplicitConceptSpecializationDecl(
4137 llvm_unreachable("Concept specializations cannot reside inside a template");
4138}
4139
4140Decl *
4141TemplateDeclInstantiator::VisitRequiresExprBodyDecl(RequiresExprBodyDecl *D) {
4143 D->getBeginLoc());
4144}
4145
4147 llvm_unreachable("Unexpected decl");
4148}
4149
4151 const MultiLevelTemplateArgumentList &TemplateArgs) {
4152 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
4153 if (D->isInvalidDecl())
4154 return nullptr;
4155
4156 Decl *SubstD;
4158 SubstD = Instantiator.Visit(D);
4159 });
4160 return SubstD;
4161}
4162
4164 FunctionDecl *Orig, QualType &T,
4165 TypeSourceInfo *&TInfo,
4166 DeclarationNameInfo &NameInfo) {
4168
4169 // C++2a [class.compare.default]p3:
4170 // the return type is replaced with bool
4171 auto *FPT = T->castAs<FunctionProtoType>();
4172 T = SemaRef.Context.getFunctionType(
4173 SemaRef.Context.BoolTy, FPT->getParamTypes(), FPT->getExtProtoInfo());
4174
4175 // Update the return type in the source info too. The most straightforward
4176 // way is to create new TypeSourceInfo for the new type. Use the location of
4177 // the '= default' as the location of the new type.
4178 //
4179 // FIXME: Set the correct return type when we initially transform the type,
4180 // rather than delaying it to now.
4181 TypeSourceInfo *NewTInfo =
4182 SemaRef.Context.getTrivialTypeSourceInfo(T, Orig->getEndLoc());
4183 auto OldLoc = TInfo->getTypeLoc().getAsAdjusted<FunctionProtoTypeLoc>();
4184 assert(OldLoc && "type of function is not a function type?");
4185 auto NewLoc = NewTInfo->getTypeLoc().castAs<FunctionProtoTypeLoc>();
4186 for (unsigned I = 0, N = OldLoc.getNumParams(); I != N; ++I)
4187 NewLoc.setParam(I, OldLoc.getParam(I));
4188 TInfo = NewTInfo;
4189
4190 // and the declarator-id is replaced with operator==
4191 NameInfo.setName(
4192 SemaRef.Context.DeclarationNames.getCXXOperatorName(OO_EqualEqual));
4193}
4194
4196 FunctionDecl *Spaceship) {
4197 if (Spaceship->isInvalidDecl())
4198 return nullptr;
4199
4200 // C++2a [class.compare.default]p3:
4201 // an == operator function is declared implicitly [...] with the same
4202 // access and function-definition and in the same class scope as the
4203 // three-way comparison operator function
4204 MultiLevelTemplateArgumentList NoTemplateArgs;
4206 NoTemplateArgs.addOuterRetainedLevels(RD->getTemplateDepth());
4207 TemplateDeclInstantiator Instantiator(*this, RD, NoTemplateArgs);
4208 Decl *R;
4209 if (auto *MD = dyn_cast<CXXMethodDecl>(Spaceship)) {
4210 R = Instantiator.VisitCXXMethodDecl(
4211 MD, /*TemplateParams=*/nullptr,
4213 } else {
4214 assert(Spaceship->getFriendObjectKind() &&
4215 "defaulted spaceship is neither a member nor a friend");
4216
4217 R = Instantiator.VisitFunctionDecl(
4218 Spaceship, /*TemplateParams=*/nullptr,
4220 if (!R)
4221 return nullptr;
4222
4223 FriendDecl *FD =
4224 FriendDecl::Create(Context, RD, Spaceship->getLocation(),
4225 cast<NamedDecl>(R), Spaceship->getBeginLoc());
4226 FD->setAccess(AS_public);
4227 RD->addDecl(FD);
4228 }
4229 return cast_or_null<FunctionDecl>(R);
4230}
4231
4232/// Instantiates a nested template parameter list in the current
4233/// instantiation context.
4234///
4235/// \param L The parameter list to instantiate
4236///
4237/// \returns NULL if there was an error
4240 // Get errors for all the parameters before bailing out.
4241 bool Invalid = false;
4242
4243 unsigned N = L->size();
4244 typedef SmallVector<NamedDecl *, 8> ParamVector;
4245 ParamVector Params;
4246 Params.reserve(N);
4247 for (auto &P : *L) {
4248 NamedDecl *D = cast_or_null<NamedDecl>(Visit(P));
4249 Params.push_back(D);
4250 Invalid = Invalid || !D || D->isInvalidDecl();
4251 }
4252
4253 // Clean up if we had an error.
4254 if (Invalid)
4255 return nullptr;
4256
4257 Expr *InstRequiresClause = L->getRequiresClause();
4258
4261 L->getLAngleLoc(), Params,
4262 L->getRAngleLoc(), InstRequiresClause);
4263 return InstL;
4264}
4265
4268 const MultiLevelTemplateArgumentList &TemplateArgs,
4269 bool EvaluateConstraints) {
4270 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
4271 Instantiator.setEvaluateConstraints(EvaluateConstraints);
4272 return Instantiator.SubstTemplateParams(Params);
4273}
4274
4275/// Instantiate the declaration of a class template partial
4276/// specialization.
4277///
4278/// \param ClassTemplate the (instantiated) class template that is partially
4279// specialized by the instantiation of \p PartialSpec.
4280///
4281/// \param PartialSpec the (uninstantiated) class template partial
4282/// specialization that we are instantiating.
4283///
4284/// \returns The instantiated partial specialization, if successful; otherwise,
4285/// NULL to indicate an error.
4288 ClassTemplateDecl *ClassTemplate,
4290 // Create a local instantiation scope for this class template partial
4291 // specialization, which will contain the instantiations of the template
4292 // parameters.
4294
4295 // Substitute into the template parameters of the class template partial
4296 // specialization.
4297 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
4298 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
4299 if (!InstParams)
4300 return nullptr;
4301
4302 // Substitute into the template arguments of the class template partial
4303 // specialization.
4304 const ASTTemplateArgumentListInfo *TemplArgInfo
4305 = PartialSpec->getTemplateArgsAsWritten();
4306 TemplateArgumentListInfo InstTemplateArgs(TemplArgInfo->LAngleLoc,
4307 TemplArgInfo->RAngleLoc);
4308 if (SemaRef.SubstTemplateArguments(TemplArgInfo->arguments(), TemplateArgs,
4309 InstTemplateArgs))
4310 return nullptr;
4311
4312 // Check that the template argument list is well-formed for this
4313 // class template.
4314 SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
4315 if (SemaRef.CheckTemplateArgumentList(
4316 ClassTemplate, PartialSpec->getLocation(), InstTemplateArgs,
4317 /*DefaultArgs=*/{},
4318 /*PartialTemplateArgs=*/false, SugaredConverted, CanonicalConverted))
4319 return nullptr;
4320
4321 // Check these arguments are valid for a template partial specialization.
4323 PartialSpec->getLocation(), ClassTemplate, InstTemplateArgs.size(),
4324 CanonicalConverted))
4325 return nullptr;
4326
4327 // Figure out where to insert this class template partial specialization
4328 // in the member template's set of class template partial specializations.
4329 void *InsertPos = nullptr;
4331 ClassTemplate->findPartialSpecialization(CanonicalConverted, InstParams,
4332 InsertPos);
4333
4334 // Build the canonical type that describes the converted template
4335 // arguments of the class template partial specialization.
4337 TemplateName(ClassTemplate), CanonicalConverted);
4338
4339 // Create the class template partial specialization declaration.
4342 SemaRef.Context, PartialSpec->getTagKind(), Owner,
4343 PartialSpec->getBeginLoc(), PartialSpec->getLocation(), InstParams,
4344 ClassTemplate, CanonicalConverted, CanonType,
4345 /*PrevDecl=*/nullptr);
4346
4347 InstPartialSpec->setTemplateArgsAsWritten(InstTemplateArgs);
4348
4349 // Substitute the nested name specifier, if any.
4350 if (SubstQualifier(PartialSpec, InstPartialSpec))
4351 return nullptr;
4352
4353 InstPartialSpec->setInstantiatedFromMember(PartialSpec);
4354
4355 if (PrevDecl) {
4356 // We've already seen a partial specialization with the same template
4357 // parameters and template arguments. This can happen, for example, when
4358 // substituting the outer template arguments ends up causing two
4359 // class template partial specializations of a member class template
4360 // to have identical forms, e.g.,
4361 //
4362 // template<typename T, typename U>
4363 // struct Outer {
4364 // template<typename X, typename Y> struct Inner;
4365 // template<typename Y> struct Inner<T, Y>;
4366 // template<typename Y> struct Inner<U, Y>;
4367 // };
4368 //
4369 // Outer<int, int> outer; // error: the partial specializations of Inner
4370 // // have the same signature.
4371 SemaRef.Diag(InstPartialSpec->getLocation(),
4372 diag::err_partial_spec_redeclared)
4373 << InstPartialSpec;
4374 SemaRef.Diag(PrevDecl->getLocation(), diag::note_prev_partial_spec_here)
4375 << SemaRef.Context.getTypeDeclType(PrevDecl);
4376 return nullptr;
4377 }
4378
4379 // Check the completed partial specialization.
4380 SemaRef.CheckTemplatePartialSpecialization(InstPartialSpec);
4381
4382 // Add this partial specialization to the set of class template partial
4383 // specializations.
4384 ClassTemplate->AddPartialSpecialization(InstPartialSpec,
4385 /*InsertPos=*/nullptr);
4386 return InstPartialSpec;
4387}
4388
4389/// Instantiate the declaration of a variable template partial
4390/// specialization.
4391///
4392/// \param VarTemplate the (instantiated) variable template that is partially
4393/// specialized by the instantiation of \p PartialSpec.
4394///
4395/// \param PartialSpec the (uninstantiated) variable template partial
4396/// specialization that we are instantiating.
4397///
4398/// \returns The instantiated partial specialization, if successful; otherwise,
4399/// NULL to indicate an error.
4402 VarTemplateDecl *VarTemplate,
4404 // Create a local instantiation scope for this variable template partial
4405 // specialization, which will contain the instantiations of the template
4406 // parameters.
4408
4409 // Substitute into the template parameters of the variable template partial
4410 // specialization.
4411 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
4412 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
4413 if (!InstParams)
4414 return nullptr;
4415
4416 // Substitute into the template arguments of the variable template partial
4417 // specialization.
4418 const ASTTemplateArgumentListInfo *TemplArgInfo
4419 = PartialSpec->getTemplateArgsAsWritten();
4420 TemplateArgumentListInfo InstTemplateArgs(TemplArgInfo->LAngleLoc,
4421 TemplArgInfo->RAngleLoc);
4422 if (SemaRef.SubstTemplateArguments(TemplArgInfo->arguments(), TemplateArgs,
4423 InstTemplateArgs))
4424 return nullptr;
4425
4426 // Check that the template argument list is well-formed for this
4427 // class template.
4428 SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
4429 if (SemaRef.CheckTemplateArgumentList(VarTemplate, PartialSpec->getLocation(),
4430 InstTemplateArgs, /*DefaultArgs=*/{},
4431 /*PartialTemplateArgs=*/false,
4432 SugaredConverted, CanonicalConverted))
4433 return nullptr;
4434
4435 // Check these arguments are valid for a template partial specialization.
4437 PartialSpec->getLocation(), VarTemplate, InstTemplateArgs.size(),
4438 CanonicalConverted))
4439 return nullptr;
4440
4441 // Figure out where to insert this variable template partial specialization
4442 // in the member template's set of variable template partial specializations.
4443 void *InsertPos = nullptr;
4445 VarTemplate->findPartialSpecialization(CanonicalConverted, InstParams,
4446 InsertPos);
4447
4448 // Do substitution on the type of the declaration
4449 TypeSourceInfo *DI = SemaRef.SubstType(
4450 PartialSpec->getTypeSourceInfo(), TemplateArgs,
4451 PartialSpec->getTypeSpecStartLoc(), PartialSpec->getDeclName());
4452 if (!DI)
4453 return nullptr;
4454
4455 if (DI->getType()->isFunctionType()) {
4456 SemaRef.Diag(PartialSpec->getLocation(),
4457 diag::err_variable_instantiates_to_function)
4458 << PartialSpec->isStaticDataMember() << DI->getType();
4459 return nullptr;
4460 }
4461
4462 // Create the variable template partial specialization declaration.
4463 VarTemplatePartialSpecializationDecl *InstPartialSpec =
4465 SemaRef.Context, Owner, PartialSpec->getInnerLocStart(),
4466 PartialSpec->getLocation(), InstParams, VarTemplate, DI->getType(),
4467 DI, PartialSpec->getStorageClass(), CanonicalConverted);
4468
4469 InstPartialSpec->setTemplateArgsAsWritten(InstTemplateArgs);
4470
4471 // Substitute the nested name specifier, if any.
4472 if (SubstQualifier(PartialSpec, InstPartialSpec))
4473 return nullptr;
4474
4475 InstPartialSpec->setInstantiatedFromMember(PartialSpec);
4476
4477 if (PrevDecl) {
4478 // We've already seen a partial specialization with the same template
4479 // parameters and template arguments. This can happen, for example, when
4480 // substituting the outer template arguments ends up causing two
4481 // variable template partial specializations of a member variable template
4482 // to have identical forms, e.g.,
4483 //
4484 // template<typename T, typename U>
4485 // struct Outer {
4486 // template<typename X, typename Y> pair<X,Y> p;
4487 // template<typename Y> pair<T, Y> p;
4488 // template<typename Y> pair<U, Y> p;
4489 // };
4490 //
4491 // Outer<int, int> outer; // error: the partial specializations of Inner
4492 // // have the same signature.
4493 SemaRef.Diag(PartialSpec->getLocation(),
4494 diag::err_var_partial_spec_redeclared)
4495 << InstPartialSpec;
4496 SemaRef.Diag(PrevDecl->getLocation(),
4497 diag::note_var_prev_partial_spec_here);
4498 return nullptr;
4499 }
4500 // Check the completed partial specialization.
4501 SemaRef.CheckTemplatePartialSpecialization(InstPartialSpec);
4502
4503 // Add this partial specialization to the set of variable template partial
4504 // specializations. The instantiation of the initializer is not necessary.
4505 VarTemplate->AddPartialSpecialization(InstPartialSpec, /*InsertPos=*/nullptr);
4506
4507 SemaRef.BuildVariableInstantiation(InstPartialSpec, PartialSpec, TemplateArgs,
4508 LateAttrs, Owner, StartingScope);
4509
4510 return InstPartialSpec;
4511}
4512
4516 TypeSourceInfo *OldTInfo = D->getTypeSourceInfo();
4517 assert(OldTInfo && "substituting function without type source info");
4518 assert(Params.empty() && "parameter vector is non-empty at start");
4519
4520 CXXRecordDecl *ThisContext = nullptr;
4521 Qualifiers ThisTypeQuals;
4522 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
4523 ThisContext = cast<CXXRecordDecl>(Owner);
4524 ThisTypeQuals = Method->getFunctionObjectParameterType().getQualifiers();
4525 }
4526
4527 TypeSourceInfo *NewTInfo = SemaRef.SubstFunctionDeclType(
4528 OldTInfo, TemplateArgs, D->getTypeSpecStartLoc(), D->getDeclName(),
4529 ThisContext, ThisTypeQuals, EvaluateConstraints);
4530 if (!NewTInfo)
4531 return nullptr;
4532
4533 TypeLoc OldTL = OldTInfo->getTypeLoc().IgnoreParens();
4534 if (FunctionProtoTypeLoc OldProtoLoc = OldTL.getAs<FunctionProtoTypeLoc>()) {
4535 if (NewTInfo != OldTInfo) {
4536 // Get parameters from the new type info.
4537 TypeLoc NewTL = NewTInfo->getTypeLoc().IgnoreParens();
4538 FunctionProtoTypeLoc NewProtoLoc = NewTL.castAs<FunctionProtoTypeLoc>();
4539 unsigned NewIdx = 0;
4540 for (unsigned OldIdx = 0, NumOldParams = OldProtoLoc.getNumParams();
4541 OldIdx != NumOldParams; ++OldIdx) {
4542 ParmVarDecl *OldParam = OldProtoLoc.getParam(OldIdx);
4543 if (!OldParam)
4544 return nullptr;
4545
4547
4548 std::optional<unsigned> NumArgumentsInExpansion;
4549 if (OldParam->isParameterPack())
4550 NumArgumentsInExpansion =
4551 SemaRef.getNumArgumentsInExpansion(OldParam->getType(),
4552 TemplateArgs);
4553 if (!NumArgumentsInExpansion) {
4554 // Simple case: normal parameter, or a parameter pack that's
4555 // instantiated to a (still-dependent) parameter pack.
4556 ParmVarDecl *NewParam = NewProtoLoc.getParam(NewIdx++);
4557 Params.push_back(NewParam);
4558 Scope->InstantiatedLocal(OldParam, NewParam);
4559 } else {
4560 // Parameter pack expansion: make the instantiation an argument pack.
4561 Scope->MakeInstantiatedLocalArgPack(OldParam);
4562 for (unsigned I = 0; I != *NumArgumentsInExpansion; ++I) {
4563 ParmVarDecl *NewParam = NewProtoLoc.getParam(NewIdx++);
4564 Params.push_back(NewParam);
4565 Scope->InstantiatedLocalPackArg(OldParam, NewParam);
4566 }
4567 }
4568 }
4569 } else {
4570 // The function type itself was not dependent and therefore no
4571 // substitution occurred. However, we still need to instantiate
4572 // the function parameters themselves.
4573 const FunctionProtoType *OldProto =
4574 cast<FunctionProtoType>(OldProtoLoc.getType());
4575 for (unsigned i = 0, i_end = OldProtoLoc.getNumParams(); i != i_end;
4576 ++i) {
4577 ParmVarDecl *OldParam = OldProtoLoc.getParam(i);
4578 if (!OldParam) {
4579 Params.push_back(SemaRef.BuildParmVarDeclForTypedef(
4580 D, D->getLocation(), OldProto->getParamType(i)));
4581 continue;
4582 }
4583
4584 ParmVarDecl *Parm =
4585 cast_or_null<ParmVarDecl>(VisitParmVarDecl(OldParam));
4586 if (!Parm)
4587 return nullptr;
4588 Params.push_back(Parm);
4589 }
4590 }
4591 } else {
4592 // If the type of this function, after ignoring parentheses, is not
4593 // *directly* a function type, then we're instantiating a function that
4594 // was declared via a typedef or with attributes, e.g.,
4595 //
4596 // typedef int functype(int, int);
4597 // functype func;
4598 // int __cdecl meth(int, int);
4599 //
4600 // In this case, we'll just go instantiate the ParmVarDecls that we
4601 // synthesized in the method declaration.
4602 SmallVector<QualType, 4> ParamTypes;
4603 Sema::ExtParameterInfoBuilder ExtParamInfos;
4604 if (SemaRef.SubstParmTypes(D->getLocation(), D->parameters(), nullptr,
4605 TemplateArgs, ParamTypes, &Params,
4606 ExtParamInfos))
4607 return nullptr;
4608 }
4609
4610 return NewTInfo;
4611}
4612
4613void Sema::addInstantiatedLocalVarsToScope(FunctionDecl *Function,
4614 const FunctionDecl *PatternDecl,
4616 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(getFunctionScopes().back());
4617
4618 for (auto *decl : PatternDecl->decls()) {
4619 if (!isa<VarDecl>(decl) || isa<ParmVarDecl>(decl))
4620 continue;
4621
4622 VarDecl *VD = cast<VarDecl>(decl);
4623 IdentifierInfo *II = VD->getIdentifier();
4624
4625 auto it = llvm::find_if(Function->decls(), [&](Decl *inst) {
4626 VarDecl *InstVD = dyn_cast<VarDecl>(inst);
4627 return InstVD && InstVD->isLocalVarDecl() &&
4628 InstVD->getIdentifier() == II;
4629 });
4630
4631 if (it == Function->decls().end())
4632 continue;
4633
4634 Scope.InstantiatedLocal(VD, *it);
4635 LSI->addCapture(cast<VarDecl>(*it), /*isBlock=*/false, /*isByref=*/false,
4636 /*isNested=*/false, VD->getLocation(), SourceLocation(),
4637 VD->getType(), /*Invalid=*/false);
4638 }
4639}
4640
4641bool Sema::addInstantiatedParametersToScope(
4642 FunctionDecl *Function, const FunctionDecl *PatternDecl,
4644 const MultiLevelTemplateArgumentList &TemplateArgs) {
4645 unsigned FParamIdx = 0;
4646 for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I) {
4647 const ParmVarDecl *PatternParam = PatternDecl->getParamDecl(I);
4648 if (!PatternParam->isParameterPack()) {
4649 // Simple case: not a parameter pack.
4650 assert(FParamIdx < Function->getNumParams());
4651 ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
4652 FunctionParam->setDeclName(PatternParam->getDeclName());
4653 // If the parameter's type is not dependent, update it to match the type
4654 // in the pattern. They can differ in top-level cv-qualifiers, and we want
4655 // the pattern's type here. If the type is dependent, they can't differ,
4656 // per core issue 1668. Substitute into the type from the pattern, in case
4657 // it's instantiation-dependent.
4658 // FIXME: Updating the type to work around this is at best fragile.
4659 if (!PatternDecl->getType()->isDependentType()) {
4660 QualType T = SubstType(PatternParam->getType(), TemplateArgs,
4661 FunctionParam->getLocation(),
4662 FunctionParam->getDeclName());
4663 if (T.isNull())
4664 return true;
4665 FunctionParam->setType(T);
4666 }
4667
4668 Scope.InstantiatedLocal(PatternParam, FunctionParam);
4669 ++FParamIdx;
4670 continue;
4671 }
4672
4673 // Expand the parameter pack.
4674 Scope.MakeInstantiatedLocalArgPack(PatternParam);
4675 std::optional<unsigned> NumArgumentsInExpansion =
4676 getNumArgumentsInExpansion(PatternParam->getType(), TemplateArgs);
4677 if (NumArgumentsInExpansion) {
4678 QualType PatternType =
4679 PatternParam->getType()->castAs<PackExpansionType>()->getPattern();
4680 for (unsigned Arg = 0; Arg < *NumArgumentsInExpansion; ++Arg) {
4681 ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
4682 FunctionParam->setDeclName(PatternParam->getDeclName());
4683 if (!PatternDecl->getType()->isDependentType()) {
4684 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, Arg);
4685 QualType T =
4686 SubstType(PatternType, TemplateArgs, FunctionParam->getLocation(),
4687 FunctionParam->getDeclName());
4688 if (T.isNull())
4689 return true;
4690 FunctionParam->setType(T);
4691 }
4692
4693 Scope.InstantiatedLocalPackArg(PatternParam, FunctionParam);
4694 ++FParamIdx;
4695 }
4696 }
4697 }
4698
4699 return false;
4700}
4701
4703 ParmVarDecl *Param) {
4704 assert(Param->hasUninstantiatedDefaultArg());
4705
4706 // FIXME: We don't track member specialization info for non-defining
4707 // friend declarations, so we will not be able to later find the function
4708 // pattern. As a workaround, don't instantiate the default argument in this
4709 // case. This is correct per the standard and only an issue for recovery
4710 // purposes. [dcl.fct.default]p4:
4711 // if a friend declaration D specifies a default argument expression,
4712 // that declaration shall be a definition.
4713 if (FD->getFriendObjectKind() != Decl::FOK_None &&
4715 return true;
4716
4717 // Instantiate the expression.
4718 //
4719 // FIXME: Pass in a correct Pattern argument, otherwise
4720 // getTemplateInstantiationArgs uses the lexical context of FD, e.g.
4721 //
4722 // template<typename T>
4723 // struct A {
4724 // static int FooImpl();
4725 //
4726 // template<typename Tp>
4727 // // bug: default argument A<T>::FooImpl() is evaluated with 2-level
4728 // // template argument list [[T], [Tp]], should be [[Tp]].
4729 // friend A<Tp> Foo(int a);
4730 // };
4731 //
4732 // template<typename T>
4733 // A<T> Foo(int a = A<T>::FooImpl());
4735 FD, FD->getLexicalDeclContext(),
4736 /*Final=*/false, /*Innermost=*/std::nullopt,
4737 /*RelativeToPrimary=*/true, /*Pattern=*/nullptr,
4738 /*ForConstraintInstantiation=*/false, /*SkipForSpecialization=*/false,
4739 /*ForDefaultArgumentSubstitution=*/true);
4740
4741 if (SubstDefaultArgument(CallLoc, Param, TemplateArgs, /*ForCallExpr*/ true))
4742 return true;
4743
4745 L->DefaultArgumentInstantiated(Param);
4746
4747 return false;
4748}
4749
4751 FunctionDecl *Decl) {
4752 const FunctionProtoType *Proto = Decl->getType()->castAs<FunctionProtoType>();
4754 return;
4755
4756 InstantiatingTemplate Inst(*this, PointOfInstantiation, Decl,
4758 if (Inst.isInvalid()) {
4759 // We hit the instantiation depth limit. Clear the exception specification
4760 // so that our callers don't have to cope with EST_Uninstantiated.
4762 return;
4763 }
4764 if (Inst.isAlreadyInstantiating()) {
4765 // This exception specification indirectly depends on itself. Reject.
4766 // FIXME: Corresponding rule in the standard?
4767 Diag(PointOfInstantiation, diag::err_exception_spec_cycle) << Decl;
4769 return;
4770 }
4771
4772 // Enter the scope of this instantiation. We don't use
4773 // PushDeclContext because we don't have a scope.
4774 Sema::ContextRAII savedContext(*this, Decl);
4776
4777 MultiLevelTemplateArgumentList TemplateArgs =
4779 /*Final=*/false, /*Innermost=*/std::nullopt,
4780 /*RelativeToPrimary*/ true);
4781
4782 // FIXME: We can't use getTemplateInstantiationPattern(false) in general
4783 // here, because for a non-defining friend declaration in a class template,
4784 // we don't store enough information to map back to the friend declaration in
4785 // the template.
4786 FunctionDecl *Template = Proto->getExceptionSpecTemplate();
4787 if (addInstantiatedParametersToScope(Decl, Template, Scope, TemplateArgs)) {
4789 return;
4790 }
4791
4792 // The noexcept specification could reference any lambda captures. Ensure
4793 // those are added to the LocalInstantiationScope.
4795 *this, Decl, TemplateArgs, Scope,
4796 /*ShouldAddDeclsFromParentScope=*/false);
4797
4799 TemplateArgs);
4800}
4801
4802/// Initializes the common fields of an instantiation function
4803/// declaration (New) from the corresponding fields of its template (Tmpl).
4804///
4805/// \returns true if there was an error
4806bool
4808 FunctionDecl *Tmpl) {
4809 New->setImplicit(Tmpl->isImplicit());
4810
4811 // Forward the mangling number from the template to the instantiated decl.
4812 SemaRef.Context.setManglingNumber(New,
4813 SemaRef.Context.getManglingNumber(Tmpl));
4814
4815 // If we are performing substituting explicitly-specified template arguments
4816 // or deduced template arguments into a function template and we reach this
4817 // point, we are now past the point where SFINAE applies and have committed
4818 // to keeping the new function template specialization. We therefore
4819 // convert the active template instantiation for the function template
4820 // into a template instantiation for this specific function template
4821 // specialization, which is not a SFINAE context, so that we diagnose any
4822 // further errors in the declaration itself.
4823 //
4824 // FIXME: This is a hack.
4825 typedef Sema::CodeSynthesisContext ActiveInstType;
4826 ActiveInstType &ActiveInst = SemaRef.CodeSynthesisContexts.back();
4827 if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution ||
4828 ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) {
4829 if (isa<FunctionTemplateDecl>(ActiveInst.Entity)) {
4830 SemaRef.InstantiatingSpecializations.erase(
4831 {ActiveInst.Entity->getCanonicalDecl(), ActiveInst.Kind});
4832 atTemplateEnd(SemaRef.TemplateInstCallbacks, SemaRef, ActiveInst);
4833 ActiveInst.Kind = ActiveInstType::TemplateInstantiation;
4834 ActiveInst.Entity = New;
4835 atTemplateBegin(SemaRef.TemplateInstCallbacks, SemaRef, ActiveInst);
4836 }
4837 }
4838
4839 const FunctionProtoType *Proto = Tmpl->getType()->getAs<FunctionProtoType>();
4840 assert(Proto && "Function template without prototype?");
4841
4842 if (Proto->hasExceptionSpec() || Proto->getNoReturnAttr()) {
4844
4845 // DR1330: In C++11, defer instantiation of a non-trivial
4846 // exception specification.
4847 // DR1484: Local classes and their members are instantiated along with the
4848 // containing function.
4849 if (SemaRef.getLangOpts().CPlusPlus11 &&
4850 EPI.ExceptionSpec.Type != EST_None &&
4854 FunctionDecl *ExceptionSpecTemplate = Tmpl;
4856 ExceptionSpecTemplate = EPI.ExceptionSpec.SourceTemplate;
4859 NewEST = EST_Unevaluated;
4860
4861 // Mark the function has having an uninstantiated exception specification.
4862 const FunctionProtoType *NewProto
4863 = New->getType()->getAs<FunctionProtoType>();
4864 assert(NewProto && "Template instantiation without function prototype?");
4865 EPI = NewProto->getExtProtoInfo();
4866 EPI.ExceptionSpec.Type = NewEST;
4867 EPI.ExceptionSpec.SourceDecl = New;
4868 EPI.ExceptionSpec.SourceTemplate = ExceptionSpecTemplate;
4869 New->setType(SemaRef.Context.getFunctionType(
4870 NewProto->getReturnType(), NewProto->getParamTypes(), EPI));
4871 } else {
4872 Sema::ContextRAII SwitchContext(SemaRef, New);
4873 SemaRef.SubstExceptionSpec(New, Proto, TemplateArgs);
4874 }
4875 }
4876
4877 // Get the definition. Leaves the variable unchanged if undefined.
4878 const FunctionDecl *Definition = Tmpl;
4879 Tmpl->isDefined(Definition);
4880
4881 SemaRef.InstantiateAttrs(TemplateArgs, Definition, New,
4882 LateAttrs, StartingScope);
4883
4884 return false;
4885}
4886
4887/// Initializes common fields of an instantiated method
4888/// declaration (New) from the corresponding fields of its template
4889/// (Tmpl).
4890///
4891/// \returns true if there was an error
4892bool
4894 CXXMethodDecl *Tmpl) {
4895 if (InitFunctionInstantiation(New, Tmpl))
4896 return true;
4897
4898 if (isa<CXXDestructorDecl>(New) && SemaRef.getLangOpts().CPlusPlus11)
4899 SemaRef.AdjustDestructorExceptionSpec(cast<CXXDestructorDecl>(New));
4900
4901 New->setAccess(Tmpl->getAccess());
4902 if (Tmpl->isVirtualAsWritten())
4903 New->setVirtualAsWritten(true);
4904
4905 // FIXME: New needs a pointer to Tmpl
4906 return false;
4907}
4908
4910 FunctionDecl *Tmpl) {
4911 // Transfer across any unqualified lookups.
4912 if (auto *DFI = Tmpl->getDefalutedOrDeletedInfo()) {
4914 Lookups.reserve(DFI->getUnqualifiedLookups().size());
4915 bool AnyChanged = false;
4916 for (DeclAccessPair DA : DFI->getUnqualifiedLookups()) {
4917 NamedDecl *D = SemaRef.FindInstantiatedDecl(New->getLocation(),
4918 DA.getDecl(), TemplateArgs);
4919 if (!D)
4920 return true;
4921 AnyChanged |= (D != DA.getDecl());
4922 Lookups.push_back(DeclAccessPair::make(D, DA.getAccess()));
4923 }
4924
4925 // It's unlikely that substitution will change any declarations. Don't
4926 // store an unnecessary copy in that case.
4929 SemaRef.Context, Lookups)
4930 : DFI);
4931 }
4932
4933 SemaRef.SetDeclDefaulted(New, Tmpl->getLocation());
4934 return false;
4935}
4936
4940 FunctionDecl *FD = FTD->getTemplatedDecl();
4941
4943 InstantiatingTemplate Inst(*this, Loc, FTD, Args->asArray(), CSC, Info);
4944 if (Inst.isInvalid())
4945 return nullptr;
4946
4947 ContextRAII SavedContext(*this, FD);
4948 MultiLevelTemplateArgumentList MArgs(FTD, Args->asArray(),
4949 /*Final=*/false);
4950
4951 return cast_or_null<FunctionDecl>(SubstDecl(FD, FD->getParent(), MArgs));
4952}
4953
4956 bool Recursive,
4957 bool DefinitionRequired,
4958 bool AtEndOfTU) {
4959 if (Function->isInvalidDecl() || isa<CXXDeductionGuideDecl>(Function))
4960 return;
4961
4962 // Never instantiate an explicit specialization except if it is a class scope
4963 // explicit specialization.
4965 Function->getTemplateSpecializationKindForInstantiation();
4966 if (TSK == TSK_ExplicitSpecialization)
4967 return;
4968
4969 // Never implicitly instantiate a builtin; we don't actually need a function
4970 // body.
4971 if (Function->getBuiltinID() && TSK == TSK_ImplicitInstantiation &&
4972 !DefinitionRequired)
4973 return;
4974
4975 // Don't instantiate a definition if we already have one.
4976 const FunctionDecl *ExistingDefn = nullptr;
4977 if (Function->isDefined(ExistingDefn,
4978 /*CheckForPendingFriendDefinition=*/true)) {
4979 if (ExistingDefn->isThisDeclarationADefinition())
4980 return;
4981
4982 // If we're asked to instantiate a function whose body comes from an
4983 // instantiated friend declaration, attach the instantiated body to the
4984 // corresponding declaration of the function.
4986 Function = const_cast<FunctionDecl*>(ExistingDefn);
4987 }
4988
4989 // Find the function body that we'll be substituting.
4990 const FunctionDecl *PatternDecl = Function->getTemplateInstantiationPattern();
4991 assert(PatternDecl && "instantiating a non-template");
4992
4993 const FunctionDecl *PatternDef = PatternDecl->getDefinition();
4994 Stmt *Pattern = nullptr;
4995 if (PatternDef) {
4996 Pattern = PatternDef->getBody(PatternDef);
4997 PatternDecl = PatternDef;
4998 if (PatternDef->willHaveBody())
4999 PatternDef = nullptr;
5000 }
5001
5002 // FIXME: We need to track the instantiation stack in order to know which
5003 // definitions should be visible within this instantiation.
5004 if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Function,
5005 Function->getInstantiatedFromMemberFunction(),
5006 PatternDecl, PatternDef, TSK,
5007 /*Complain*/DefinitionRequired)) {
5008 if (DefinitionRequired)
5009 Function->setInvalidDecl();
5010 else if (TSK == TSK_ExplicitInstantiationDefinition ||
5011 (Function->isConstexpr() && !Recursive)) {
5012 // Try again at the end of the translation unit (at which point a
5013 // definition will be required).
5014 assert(!Recursive);
5015 Function->setInstantiationIsPending(true);
5016 PendingInstantiations.push_back(
5017 std::make_pair(Function, PointOfInstantiation));
5018
5019 if (llvm::isTimeTraceVerbose()) {
5020 llvm::timeTraceAddInstantEvent("DeferInstantiation", [&] {
5021 std::string Name;
5022 llvm::raw_string_ostream OS(Name);
5023 Function->getNameForDiagnostic(OS, getPrintingPolicy(),
5024 /*Qualified=*/true);
5025 return Name;
5026 });
5027 }
5028 } else if (TSK == TSK_ImplicitInstantiation) {
5029 if (AtEndOfTU && !getDiagnostics().hasErrorOccurred() &&
5030 !getSourceManager().isInSystemHeader(PatternDecl->getBeginLoc())) {
5031 Diag(PointOfInstantiation, diag::warn_func_template_missing)
5032 << Function;
5033 Diag(PatternDecl->getLocation(), diag::note_forward_template_decl);
5035 Diag(PointOfInstantiation, diag::note_inst_declaration_hint)
5036 << Function;
5037 }
5038 }
5039
5040 return;
5041 }
5042
5043 // Postpone late parsed template instantiations.
5044 if (PatternDecl->isLateTemplateParsed() &&
5046 Function->setInstantiationIsPending(true);
5047 LateParsedInstantiations.push_back(
5048 std::make_pair(Function, PointOfInstantiation));
5049 return;
5050 }
5051
5052 llvm::TimeTraceScope TimeScope("InstantiateFunction", [&]() {
5053 llvm::TimeTraceMetadata M;
5054 llvm::raw_string_ostream OS(M.Detail);
5055 Function->getNameForDiagnostic(OS, getPrintingPolicy(),
5056 /*Qualified=*/true);
5057 if (llvm::isTimeTraceVerbose()) {
5058 auto Loc = SourceMgr.getExpansionLoc(Function->getLocation());
5059 M.File = SourceMgr.getFilename(Loc);
5061 }
5062 return M;
5063 });
5064
5065 // If we're performing recursive template instantiation, create our own
5066 // queue of pending implicit instantiations that we will instantiate later,
5067 // while we're still within our own instantiation context.
5068 // This has to happen before LateTemplateParser below is called, so that
5069 // it marks vtables used in late parsed templates as used.
5070 GlobalEagerInstantiationScope GlobalInstantiations(*this,
5071 /*Enabled=*/Recursive);
5072 LocalEagerInstantiationScope LocalInstantiations(*this);
5073
5074 // Call the LateTemplateParser callback if there is a need to late parse
5075 // a templated function definition.
5076 if (!Pattern && PatternDecl->isLateTemplateParsed() &&
5078 // FIXME: Optimize to allow individual templates to be deserialized.
5079 if (PatternDecl->isFromASTFile())
5080 ExternalSource->ReadLateParsedTemplates(LateParsedTemplateMap);
5081
5082 auto LPTIter = LateParsedTemplateMap.find(PatternDecl);
5083 assert(LPTIter != LateParsedTemplateMap.end() &&
5084 "missing LateParsedTemplate");
5085 LateTemplateParser(OpaqueParser, *LPTIter->second);
5086 Pattern = PatternDecl->getBody(PatternDecl);
5088 }
5089
5090 // Note, we should never try to instantiate a deleted function template.
5091 assert((Pattern || PatternDecl->isDefaulted() ||
5092 PatternDecl->hasSkippedBody()) &&
5093 "unexpected kind of function template definition");
5094
5095 // C++1y [temp.explicit]p10:
5096 // Except for inline functions, declarations with types deduced from their
5097 // initializer or return value, and class template specializations, other
5098 // explicit instantiation declarations have the effect of suppressing the
5099 // implicit instantiation of the entity to which they refer.
5101 !PatternDecl->isInlined() &&
5102 !PatternDecl->getReturnType()->getContainedAutoType())
5103 return;
5104
5105 if (PatternDecl->isInlined()) {
5106 // Function, and all later redeclarations of it (from imported modules,
5107 // for instance), are now implicitly inline.
5108 for (auto *D = Function->getMostRecentDecl(); /**/;
5109 D = D->getPreviousDecl()) {
5110 D->setImplicitlyInline();
5111 if (D == Function)
5112 break;
5113 }
5114 }
5115
5116 InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
5117 if (Inst.isInvalid() || Inst.isAlreadyInstantiating())
5118 return;
5120 "instantiating function definition");
5121
5122 // The instantiation is visible here, even if it was first declared in an
5123 // unimported module.
5124 Function->setVisibleDespiteOwningModule();
5125
5126 // Copy the source locations from the pattern.
5127 Function->setLocation(PatternDecl->getLocation());
5128 Function->setInnerLocStart(PatternDecl->getInnerLocStart());
5129 Function->setRangeEnd(PatternDecl->getEndLoc());
5130 Function->setDeclarationNameLoc(PatternDecl->getNameInfo().getInfo());
5131
5134
5135 Qualifiers ThisTypeQuals;
5136 CXXRecordDecl *ThisContext = nullptr;
5137 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
5138 ThisContext = Method->getParent();
5139 ThisTypeQuals = Method->getMethodQualifiers();
5140 }
5141 CXXThisScopeRAII ThisScope(*this, ThisContext, ThisTypeQuals);
5142
5143 // Introduce a new scope where local variable instantiations will be
5144 // recorded, unless we're actually a member function within a local
5145 // class, in which case we need to merge our results with the parent
5146 // scope (of the enclosing function). The exception is instantiating
5147 // a function template specialization, since the template to be
5148 // instantiated already has references to locals properly substituted.
5149 bool MergeWithParentScope = false;
5150 if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Function->getDeclContext()))
5151 MergeWithParentScope =
5152 Rec->isLocalClass() && !Function->isFunctionTemplateSpecialization();
5153
5154 LocalInstantiationScope Scope(*this, MergeWithParentScope);
5155 auto RebuildTypeSourceInfoForDefaultSpecialMembers = [&]() {
5156 // Special members might get their TypeSourceInfo set up w.r.t the
5157 // PatternDecl context, in which case parameters could still be pointing
5158 // back to the original class, make sure arguments are bound to the
5159 // instantiated record instead.
5160 assert(PatternDecl->isDefaulted() &&
5161 "Special member needs to be defaulted");
5162 auto PatternSM = getDefaultedFunctionKind(PatternDecl).asSpecialMember();
5163 if (!(PatternSM == CXXSpecialMemberKind::CopyConstructor ||
5167 return;
5168
5169 auto *NewRec = dyn_cast<CXXRecordDecl>(Function->getDeclContext());
5170 const auto *PatternRec =
5171 dyn_cast<CXXRecordDecl>(PatternDecl->getDeclContext());
5172 if (!NewRec || !PatternRec)
5173 return;
5174 if (!PatternRec->isLambda())
5175 return;
5176
5177 struct SpecialMemberTypeInfoRebuilder
5178 : TreeTransform<SpecialMemberTypeInfoRebuilder> {
5180 const CXXRecordDecl *OldDecl;
5181 CXXRecordDecl *NewDecl;
5182
5183 SpecialMemberTypeInfoRebuilder(Sema &SemaRef, const CXXRecordDecl *O,
5184 CXXRecordDecl *N)
5185 : TreeTransform(SemaRef), OldDecl(O), NewDecl(N) {}
5186
5187 bool TransformExceptionSpec(SourceLocation Loc,
5189 SmallVectorImpl<QualType> &Exceptions,
5190 bool &Changed) {
5191 return false;
5192 }
5193
5194 QualType TransformRecordType(TypeLocBuilder &TLB, RecordTypeLoc TL) {
5195 const RecordType *T = TL.getTypePtr();
5196 RecordDecl *Record = cast_or_null<RecordDecl>(
5197 getDerived().TransformDecl(TL.getNameLoc(), T->getDecl()));
5198 if (Record != OldDecl)
5199 return Base::TransformRecordType(TLB, TL);
5200
5201 QualType Result = getDerived().RebuildRecordType(NewDecl);
5202 if (Result.isNull())
5203 return QualType();
5204
5205 RecordTypeLoc NewTL = TLB.push<RecordTypeLoc>(Result);
5206 NewTL.setNameLoc(TL.getNameLoc());
5207 return Result;
5208 }
5209 } IR{*this, PatternRec, NewRec};
5210
5211 TypeSourceInfo *NewSI = IR.TransformType(Function->getTypeSourceInfo());
5212 assert(NewSI && "Type Transform failed?");
5213 Function->setType(NewSI->getType());
5214 Function->setTypeSourceInfo(NewSI);
5215
5216 ParmVarDecl *Parm = Function->getParamDecl(0);
5217 TypeSourceInfo *NewParmSI = IR.TransformType(Parm->getTypeSourceInfo());
5218 assert(NewParmSI && "Type transformation failed.");
5219 Parm->setType(NewParmSI->getType());
5220 Parm->setTypeSourceInfo(NewParmSI);
5221 };
5222
5223 if (PatternDecl->isDefaulted()) {
5224 RebuildTypeSourceInfoForDefaultSpecialMembers();
5225 SetDeclDefaulted(Function, PatternDecl->getLocation());
5226 } else {
5228 Function, Function->getLexicalDeclContext(), /*Final=*/false,
5229 /*Innermost=*/std::nullopt, false, PatternDecl);
5230
5231 // Substitute into the qualifier; we can get a substitution failure here
5232 // through evil use of alias templates.
5233 // FIXME: Is CurContext correct for this? Should we go to the (instantiation
5234 // of the) lexical context of the pattern?
5235 SubstQualifier(*this, PatternDecl, Function, TemplateArgs);
5236
5238
5239 // Enter the scope of this instantiation. We don't use
5240 // PushDeclContext because we don't have a scope.
5241 Sema::ContextRAII savedContext(*this, Function);
5242
5243 FPFeaturesStateRAII SavedFPFeatures(*this);
5245 FpPragmaStack.CurrentValue = FPOptionsOverride();
5246
5247 if (addInstantiatedParametersToScope(Function, PatternDecl, Scope,
5248 TemplateArgs))
5249 return;
5250
5251 StmtResult Body;
5252 if (PatternDecl->hasSkippedBody()) {
5254 Body = nullptr;
5255 } else {
5256 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Function)) {
5257 // If this is a constructor, instantiate the member initializers.
5258 InstantiateMemInitializers(Ctor, cast<CXXConstructorDecl>(PatternDecl),
5259 TemplateArgs);
5260
5261 // If this is an MS ABI dllexport default constructor, instantiate any
5262 // default arguments.
5264 Ctor->isDefaultConstructor()) {
5266 }
5267 }
5268
5269 // Instantiate the function body.
5270 Body = SubstStmt(Pattern, TemplateArgs);
5271
5272 if (Body.isInvalid())
5273 Function->setInvalidDecl();
5274 }
5275 // FIXME: finishing the function body while in an expression evaluation
5276 // context seems wrong. Investigate more.
5277 ActOnFinishFunctionBody(Function, Body.get(), /*IsInstantiation=*/true);
5278
5279 PerformDependentDiagnostics(PatternDecl, TemplateArgs);
5280
5281 if (auto *Listener = getASTMutationListener())
5282 Listener->FunctionDefinitionInstantiated(Function);
5283
5284 savedContext.pop();
5285 }
5286
5289
5290 // This class may have local implicit instantiations that need to be
5291 // instantiation within this scope.
5292 LocalInstantiations.perform();
5293 Scope.Exit();
5294 GlobalInstantiations.perform();
5295}
5296
5298 VarTemplateDecl *VarTemplate, VarDecl *FromVar,
5299 const TemplateArgumentList *PartialSpecArgs,
5300 const TemplateArgumentListInfo &TemplateArgsInfo,
5302 SourceLocation PointOfInstantiation, LateInstantiatedAttrVec *LateAttrs,
5303 LocalInstantiationScope *StartingScope) {
5304 if (FromVar->isInvalidDecl())
5305 return nullptr;
5306
5307 InstantiatingTemplate Inst(*this, PointOfInstantiation, FromVar);
5308 if (Inst.isInvalid())
5309 return nullptr;
5310
5311 // Instantiate the first declaration of the variable template: for a partial
5312 // specialization of a static data member template, the first declaration may
5313 // or may not be the declaration in the class; if it's in the class, we want
5314 // to instantiate a member in the class (a declaration), and if it's outside,
5315 // we want to instantiate a definition.
5316 //
5317 // If we're instantiating an explicitly-specialized member template or member
5318 // partial specialization, don't do this. The member specialization completely
5319 // replaces the original declaration in this case.
5320 bool IsMemberSpec = false;
5321 MultiLevelTemplateArgumentList MultiLevelList;
5322 if (auto *PartialSpec =
5323 dyn_cast<VarTemplatePartialSpecializationDecl>(FromVar)) {
5324 assert(PartialSpecArgs);
5325 IsMemberSpec = PartialSpec->isMemberSpecialization();
5326 MultiLevelList.addOuterTemplateArguments(
5327 PartialSpec, PartialSpecArgs->asArray(), /*Final=*/false);
5328 } else {
5329 assert(VarTemplate == FromVar->getDescribedVarTemplate());
5330 IsMemberSpec = VarTemplate->isMemberSpecialization();
5331 MultiLevelList.addOuterTemplateArguments(VarTemplate, Converted,
5332 /*Final=*/false);
5333 }
5334 if (!IsMemberSpec)
5335 FromVar = FromVar->getFirstDecl();
5336
5337 TemplateDeclInstantiator Instantiator(*this, FromVar->getDeclContext(),
5338 MultiLevelList);
5339
5340 // TODO: Set LateAttrs and StartingScope ...
5341
5342 return cast_or_null<VarTemplateSpecializationDecl>(
5344 VarTemplate, FromVar, TemplateArgsInfo, Converted));
5345}
5346
5348 VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl,
5349 const MultiLevelTemplateArgumentList &TemplateArgs) {
5350 assert(PatternDecl->isThisDeclarationADefinition() &&
5351 "don't have a definition to instantiate from");
5352
5353 // Do substitution on the type of the declaration
5354 TypeSourceInfo *DI =
5355 SubstType(PatternDecl->getTypeSourceInfo(), TemplateArgs,
5356 PatternDecl->getTypeSpecStartLoc(), PatternDecl->getDeclName());
5357 if (!DI)
5358 return nullptr;
5359
5360 // Update the type of this variable template specialization.
5361 VarSpec->setType(DI->getType());
5362
5363 // Convert the declaration into a definition now.
5364 VarSpec->setCompleteDefinition();
5365
5366 // Instantiate the initializer.
5367 InstantiateVariableInitializer(VarSpec, PatternDecl, TemplateArgs);
5368
5369 if (getLangOpts().OpenCL)
5370 deduceOpenCLAddressSpace(VarSpec);
5371
5372 return VarSpec;
5373}
5374
5376 VarDecl *NewVar, VarDecl *OldVar,
5377 const MultiLevelTemplateArgumentList &TemplateArgs,
5378 LateInstantiatedAttrVec *LateAttrs, DeclContext *Owner,
5379 LocalInstantiationScope *StartingScope,
5380 bool InstantiatingVarTemplate,
5381 VarTemplateSpecializationDecl *PrevDeclForVarTemplateSpecialization) {
5382 // Instantiating a partial specialization to produce a partial
5383 // specialization.
5384 bool InstantiatingVarTemplatePartialSpec =
5385 isa<VarTemplatePartialSpecializationDecl>(OldVar) &&
5386 isa<VarTemplatePartialSpecializationDecl>(NewVar);
5387 // Instantiating from a variable template (or partial specialization) to
5388 // produce a variable template specialization.
5389 bool InstantiatingSpecFromTemplate =
5390 isa<VarTemplateSpecializationDecl>(NewVar) &&
5391 (OldVar->getDescribedVarTemplate() ||
5392 isa<VarTemplatePartialSpecializationDecl>(OldVar));
5393
5394 // If we are instantiating a local extern declaration, the
5395 // instantiation belongs lexically to the containing function.
5396 // If we are instantiating a static data member defined
5397 // out-of-line, the instantiation will have the same lexical
5398 // context (which will be a namespace scope) as the template.
5399 if (OldVar->isLocalExternDecl()) {
5400 NewVar->setLocalExternDecl();
5401 NewVar->setLexicalDeclContext(Owner);
5402 } else if (OldVar->isOutOfLine())
5404 NewVar->setTSCSpec(OldVar->getTSCSpec());
5405 NewVar->setInitStyle(OldVar->getInitStyle());
5406 NewVar->setCXXForRangeDecl(OldVar->isCXXForRangeDecl());
5407 NewVar->setObjCForDecl(OldVar->isObjCForDecl());
5408 NewVar->setConstexpr(OldVar->isConstexpr());
5409 NewVar->setInitCapture(OldVar->isInitCapture());
5412 NewVar->setAccess(OldVar->getAccess());
5413
5414 if (!OldVar->isStaticDataMember()) {
5415 if (OldVar->isUsed(false))
5416 NewVar->setIsUsed();
5417 NewVar->setReferenced(OldVar->isReferenced());
5418 }
5419
5420 InstantiateAttrs(TemplateArgs, OldVar, NewVar, LateAttrs, StartingScope);
5421
5423 *this, NewVar->getDeclName(), NewVar->getLocation(),
5426 NewVar->isLocalExternDecl() ? RedeclarationKind::ForExternalRedeclaration
5428
5429 if (NewVar->isLocalExternDecl() && OldVar->getPreviousDecl() &&
5431 OldVar->getPreviousDecl()->getDeclContext()==OldVar->getDeclContext())) {
5432 // We have a previous declaration. Use that one, so we merge with the
5433 // right type.
5434 if (NamedDecl *NewPrev = FindInstantiatedDecl(
5435 NewVar->getLocation(), OldVar->getPreviousDecl(), TemplateArgs))
5436 Previous.addDecl(NewPrev);
5437 } else if (!isa<VarTemplateSpecializationDecl>(NewVar) &&
5438 OldVar->hasLinkage()) {
5439 LookupQualifiedName(Previous, NewVar->getDeclContext(), false);
5440 } else if (PrevDeclForVarTemplateSpecialization) {
5441 Previous.addDecl(PrevDeclForVarTemplateSpecialization);
5442 }
5444
5445 if (!InstantiatingVarTemplate) {
5446 NewVar->getLexicalDeclContext()->addHiddenDecl(NewVar);
5447 if (!NewVar->isLocalExternDecl() || !NewVar->getPreviousDecl())
5448 NewVar->getDeclContext()->makeDeclVisibleInContext(NewVar);
5449 }
5450
5451 if (!OldVar->isOutOfLine()) {
5452 if (NewVar->getDeclContext()->isFunctionOrMethod())
5454 }
5455
5456 // Link instantiations of static data members back to the template from
5457 // which they were instantiated.
5458 //
5459 // Don't do this when instantiating a template (we link the template itself
5460 // back in that case) nor when instantiating a static data member template
5461 // (that's not a member specialization).
5462 if (NewVar->isStaticDataMember() && !InstantiatingVarTemplate &&
5463 !InstantiatingSpecFromTemplate)
5466
5467 // If the pattern is an (in-class) explicit specialization, then the result
5468 // is also an explicit specialization.
5469 if (VarTemplateSpecializationDecl *OldVTSD =
5470 dyn_cast<VarTemplateSpecializationDecl>(OldVar)) {
5471 if (OldVTSD->getSpecializationKind() == TSK_ExplicitSpecialization &&
5472 !isa<VarTemplatePartialSpecializationDecl>(OldVTSD))
5473 cast<VarTemplateSpecializationDecl>(NewVar)->setSpecializationKind(
5475 }
5476
5477 // Forward the mangling number from the template to the instantiated decl.
5480
5481 // Figure out whether to eagerly instantiate the initializer.
5482 if (InstantiatingVarTemplate || InstantiatingVarTemplatePartialSpec) {
5483 // We're producing a template. Don't instantiate the initializer yet.
5484 } else if (NewVar->getType()->isUndeducedType()) {
5485 // We need the type to complete the declaration of the variable.
5486 InstantiateVariableInitializer(NewVar, OldVar, TemplateArgs);
5487 } else if (InstantiatingSpecFromTemplate ||
5488 (OldVar->isInline() && OldVar->isThisDeclarationADefinition() &&
5489 !NewVar->isThisDeclarationADefinition())) {
5490 // Delay instantiation of the initializer for variable template
5491 // specializations or inline static data members until a definition of the
5492 // variable is needed.
5493 } else {
5494 InstantiateVariableInitializer(NewVar, OldVar, TemplateArgs);
5495 }
5496
5497 // Diagnose unused local variables with dependent types, where the diagnostic
5498 // will have been deferred.
5499 if (!NewVar->isInvalidDecl() &&
5500 NewVar->getDeclContext()->isFunctionOrMethod() &&
5501 OldVar->getType()->isDependentType())
5502 DiagnoseUnusedDecl(NewVar);
5503}
5504
5506 VarDecl *Var, VarDecl *OldVar,
5507 const MultiLevelTemplateArgumentList &TemplateArgs) {
5509 L->VariableDefinitionInstantiated(Var);
5510
5511 // We propagate the 'inline' flag with the initializer, because it
5512 // would otherwise imply that the variable is a definition for a
5513 // non-static data member.
5514 if (OldVar->isInlineSpecified())
5515 Var->setInlineSpecified();
5516 else if (OldVar->isInline())
5517 Var->setImplicitlyInline();
5518
5519 if (OldVar->getInit()) {
5522
5527 // Instantiate the initializer.
5529
5530 {
5531 ContextRAII SwitchContext(*this, Var->getDeclContext());
5532 Init = SubstInitializer(OldVar->getInit(), TemplateArgs,
5533 OldVar->getInitStyle() == VarDecl::CallInit);
5534 }
5535
5536 if (!Init.isInvalid()) {
5537 Expr *InitExpr = Init.get();
5538
5539 if (Var->hasAttr<DLLImportAttr>() &&
5540 (!InitExpr ||
5541 !InitExpr->isConstantInitializer(getASTContext(), false))) {
5542 // Do not dynamically initialize dllimport variables.
5543 } else if (InitExpr) {
5544 bool DirectInit = OldVar->isDirectInit();
5545 AddInitializerToDecl(Var, InitExpr, DirectInit);
5546 } else
5548 } else {
5549 // FIXME: Not too happy about invalidating the declaration
5550 // because of a bogus initializer.
5551 Var->setInvalidDecl();
5552 }
5553 } else {
5554 // `inline` variables are a definition and declaration all in one; we won't
5555 // pick up an initializer from anywhere else.
5556 if (Var->isStaticDataMember() && !Var->isInline()) {
5557 if (!Var->isOutOfLine())
5558 return;
5559
5560 // If the declaration inside the class had an initializer, don't add
5561 // another one to the out-of-line definition.
5562 if (OldVar->getFirstDecl()->hasInit())
5563 return;
5564 }
5565
5566 // We'll add an initializer to a for-range declaration later.
5567 if (Var->isCXXForRangeDecl() || Var->isObjCForDecl())
5568 return;
5569
5571 }
5572
5573 if (getLangOpts().CUDA)
5575}
5576
5578 VarDecl *Var, bool Recursive,
5579 bool DefinitionRequired, bool AtEndOfTU) {
5580 if (Var->isInvalidDecl())
5581 return;
5582
5583 // Never instantiate an explicitly-specialized entity.
5586 if (TSK == TSK_ExplicitSpecialization)
5587 return;
5588
5589 // Find the pattern and the arguments to substitute into it.
5590 VarDecl *PatternDecl = Var->getTemplateInstantiationPattern();
5591 assert(PatternDecl && "no pattern for templated variable");
5592 MultiLevelTemplateArgumentList TemplateArgs =
5594
5596 dyn_cast<VarTemplateSpecializationDecl>(Var);
5597 if (VarSpec) {
5598 // If this is a static data member template, there might be an
5599 // uninstantiated initializer on the declaration. If so, instantiate
5600 // it now.
5601 //
5602 // FIXME: This largely duplicates what we would do below. The difference
5603 // is that along this path we may instantiate an initializer from an
5604 // in-class declaration of the template and instantiate the definition
5605 // from a separate out-of-class definition.
5606 if (PatternDecl->isStaticDataMember() &&
5607 (PatternDecl = PatternDecl->getFirstDecl())->hasInit() &&
5608 !Var->hasInit()) {
5609 // FIXME: Factor out the duplicated instantiation context setup/tear down
5610 // code here.
5611 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
5612 if (Inst.isInvalid() || Inst.isAlreadyInstantiating())
5613 return;
5615 "instantiating variable initializer");
5616
5617 // The instantiation is visible here, even if it was first declared in an
5618 // unimported module.
5620
5621 // If we're performing recursive template instantiation, create our own
5622 // queue of pending implicit instantiations that we will instantiate
5623 // later, while we're still within our own instantiation context.
5624 GlobalEagerInstantiationScope GlobalInstantiations(*this,
5625 /*Enabled=*/Recursive);
5626 LocalInstantiationScope Local(*this);
5627 LocalEagerInstantiationScope LocalInstantiations(*this);
5628
5629 // Enter the scope of this instantiation. We don't use
5630 // PushDeclContext because we don't have a scope.
5631 ContextRAII PreviousContext(*this, Var->getDeclContext());
5632 InstantiateVariableInitializer(Var, PatternDecl, TemplateArgs);
5633 PreviousContext.pop();
5634
5635 // This variable may have local implicit instantiations that need to be
5636 // instantiated within this scope.
5637 LocalInstantiations.perform();
5638 Local.Exit();
5639 GlobalInstantiations.perform();
5640 }
5641 } else {
5642 assert(Var->isStaticDataMember() && PatternDecl->isStaticDataMember() &&
5643 "not a static data member?");
5644 }
5645
5646 VarDecl *Def = PatternDecl->getDefinition(getASTContext());
5647
5648 // If we don't have a definition of the variable template, we won't perform
5649 // any instantiation. Rather, we rely on the user to instantiate this
5650 // definition (or provide a specialization for it) in another translation
5651 // unit.
5652 if (!Def && !DefinitionRequired) {
5654 PendingInstantiations.push_back(
5655 std::make_pair(Var, PointOfInstantiation));
5656 } else if (TSK == TSK_ImplicitInstantiation) {
5657 // Warn about missing definition at the end of translation unit.
5658 if (AtEndOfTU && !getDiagnostics().hasErrorOccurred() &&
5659 !getSourceManager().isInSystemHeader(PatternDecl->getBeginLoc())) {
5660 Diag(PointOfInstantiation, diag::warn_var_template_missing)
5661 << Var;
5662 Diag(PatternDecl->getLocation(), diag::note_forward_template_decl);
5664 Diag(PointOfInstantiation, diag::note_inst_declaration_hint) << Var;
5665 }
5666 return;
5667 }
5668 }
5669
5670 // FIXME: We need to track the instantiation stack in order to know which
5671 // definitions should be visible within this instantiation.
5672 // FIXME: Produce diagnostics when Var->getInstantiatedFromStaticDataMember().
5673 if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Var,
5674 /*InstantiatedFromMember*/false,
5675 PatternDecl, Def, TSK,
5676 /*Complain*/DefinitionRequired))
5677 return;
5678
5679 // C++11 [temp.explicit]p10:
5680 // Except for inline functions, const variables of literal types, variables
5681 // of reference types, [...] explicit instantiation declarations
5682 // have the effect of suppressing the implicit instantiation of the entity
5683 // to which they refer.
5684 //
5685 // FIXME: That's not exactly the same as "might be usable in constant
5686 // expressions", which only allows constexpr variables and const integral
5687 // types, not arbitrary const literal types.
5690 return;
5691
5692 // Make sure to pass the instantiated variable to the consumer at the end.
5693 struct PassToConsumerRAII {
5694 ASTConsumer &Consumer;
5695 VarDecl *Var;
5696
5697 PassToConsumerRAII(ASTConsumer &Consumer, VarDecl *Var)
5698 : Consumer(Consumer), Var(Var) { }
5699
5700 ~PassToConsumerRAII() {
5702 }
5703 } PassToConsumerRAII(Consumer, Var);
5704
5705 // If we already have a definition, we're done.
5706 if (VarDecl *Def = Var->getDefinition()) {
5707 // We may be explicitly instantiating something we've already implicitly
5708 // instantiated.
5710 PointOfInstantiation);
5711 return;
5712 }
5713
5714 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
5715 if (Inst.isInvalid() || Inst.isAlreadyInstantiating())
5716 return;
5718 "instantiating variable definition");
5719
5720 // If we're performing recursive template instantiation, create our own
5721 // queue of pending implicit instantiations that we will instantiate later,
5722 // while we're still within our own instantiation context.
5723 GlobalEagerInstantiationScope GlobalInstantiations(*this,
5724 /*Enabled=*/Recursive);
5725
5726 // Enter the scope of this instantiation. We don't use
5727 // PushDeclContext because we don't have a scope.
5728 ContextRAII PreviousContext(*this, Var->getDeclContext());
5729 LocalInstantiationScope Local(*this);
5730
5731 LocalEagerInstantiationScope LocalInstantiations(*this);
5732
5733 VarDecl *OldVar = Var;
5734 if (Def->isStaticDataMember() && !Def->isOutOfLine()) {
5735 // We're instantiating an inline static data member whose definition was
5736 // provided inside the class.
5737 InstantiateVariableInitializer(Var, Def, TemplateArgs);
5738 } else if (!VarSpec) {
5739 Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(),
5740 TemplateArgs));
5741 } else if (Var->isStaticDataMember() &&
5742 Var->getLexicalDeclContext()->isRecord()) {
5743 // We need to instantiate the definition of a static data member template,
5744 // and all we have is the in-class declaration of it. Instantiate a separate
5745 // declaration of the definition.
5746 TemplateDeclInstantiator Instantiator(*this, Var->getDeclContext(),
5747 TemplateArgs);
5748
5749 TemplateArgumentListInfo TemplateArgInfo;
5750 if (const ASTTemplateArgumentListInfo *ArgInfo =
5751 VarSpec->getTemplateArgsAsWritten()) {
5752 TemplateArgInfo.setLAngleLoc(ArgInfo->getLAngleLoc());
5753 TemplateArgInfo.setRAngleLoc(ArgInfo->getRAngleLoc());
5754 for (const TemplateArgumentLoc &Arg : ArgInfo->arguments())
5755 TemplateArgInfo.addArgument(Arg);
5756 }
5757
5758 Var = cast_or_null<VarDecl>(Instantiator.VisitVarTemplateSpecializationDecl(
5759 VarSpec->getSpecializedTemplate(), Def, TemplateArgInfo,
5760 VarSpec->getTemplateArgs().asArray(), VarSpec));
5761 if (Var) {
5762 llvm::PointerUnion<VarTemplateDecl *,
5766 PatternPtr.dyn_cast<VarTemplatePartialSpecializationDecl *>())
5767 cast<VarTemplateSpecializationDecl>(Var)->setInstantiationOf(
5768 Partial, &VarSpec->getTemplateInstantiationArgs());
5769
5770 // Attach the initializer.
5771 InstantiateVariableInitializer(Var, Def, TemplateArgs);
5772 }
5773 } else
5774 // Complete the existing variable's definition with an appropriately
5775 // substituted type and initializer.
5776 Var = CompleteVarTemplateSpecializationDecl(VarSpec, Def, TemplateArgs);
5777
5778 PreviousContext.pop();
5779
5780 if (Var) {
5781 PassToConsumerRAII.Var = Var;
5783 OldVar->getPointOfInstantiation());
5784 }
5785
5786 // This variable may have local implicit instantiations that need to be
5787 // instantiated within this scope.
5788 LocalInstantiations.perform();
5789 Local.Exit();
5790 GlobalInstantiations.perform();
5791}
5792
5793void
5795 const CXXConstructorDecl *Tmpl,
5796 const MultiLevelTemplateArgumentList &TemplateArgs) {
5797
5799 bool AnyErrors = Tmpl->isInvalidDecl();
5800
5801 // Instantiate all the initializers.
5802 for (const auto *Init : Tmpl->inits()) {
5803 // Only instantiate written initializers, let Sema re-construct implicit
5804 // ones.
5805 if (!Init->isWritten())
5806 continue;
5807
5808 SourceLocation EllipsisLoc;
5809
5810 if (Init->isPackExpansion()) {
5811 // This is a pack expansion. We should expand it now.
5812 TypeLoc BaseTL = Init->getTypeSourceInfo()->getTypeLoc();
5814 collectUnexpandedParameterPacks(BaseTL, Unexpanded);
5815 collectUnexpandedParameterPacks(Init->getInit(), Unexpanded);
5816 bool ShouldExpand = false;
5817 bool RetainExpansion = false;
5818 std::optional<unsigned> NumExpansions;
5819 if (CheckParameterPacksForExpansion(Init->getEllipsisLoc(),
5820 BaseTL.getSourceRange(),
5821 Unexpanded,
5822 TemplateArgs, ShouldExpand,
5823 RetainExpansion,
5824 NumExpansions)) {
5825 AnyErrors = true;
5826 New->setInvalidDecl();
5827 continue;
5828 }
5829 assert(ShouldExpand && "Partial instantiation of base initializer?");
5830
5831 // Loop over all of the arguments in the argument pack(s),
5832 for (unsigned I = 0; I != *NumExpansions; ++I) {
5833 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
5834
5835 // Instantiate the initializer.
5836 ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs,
5837 /*CXXDirectInit=*/true);
5838 if (TempInit.isInvalid()) {
5839 AnyErrors = true;
5840 break;
5841 }
5842
5843 // Instantiate the base type.
5844 TypeSourceInfo *BaseTInfo = SubstType(Init->getTypeSourceInfo(),
5845 TemplateArgs,
5846 Init->getSourceLocation(),
5847 New->getDeclName());
5848 if (!BaseTInfo) {
5849 AnyErrors = true;
5850 break;
5851 }
5852
5853 // Build the initializer.
5854 MemInitResult NewInit = BuildBaseInitializer(BaseTInfo->getType(),
5855 BaseTInfo, TempInit.get(),
5856 New->getParent(),
5857 SourceLocation());
5858 if (NewInit.isInvalid()) {
5859 AnyErrors = true;
5860 break;
5861 }
5862
5863 NewInits.push_back(NewInit.get());
5864 }
5865
5866 continue;
5867 }
5868
5869 // Instantiate the initializer.
5870 ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs,
5871 /*CXXDirectInit=*/true);
5872 if (TempInit.isInvalid()) {
5873 AnyErrors = true;
5874 continue;
5875 }
5876
5877 MemInitResult NewInit;
5878 if (Init->isDelegatingInitializer() || Init->isBaseInitializer()) {
5879 TypeSourceInfo *TInfo = SubstType(Init->getTypeSourceInfo(),
5880 TemplateArgs,
5881 Init->getSourceLocation(),
5882 New->getDeclName());
5883 if (!TInfo) {
5884 AnyErrors = true;
5885 New->setInvalidDecl();
5886 continue;
5887 }
5888
5889 if (Init->isBaseInitializer())
5890 NewInit = BuildBaseInitializer(TInfo->getType(), TInfo, TempInit.get(),
5891 New->getParent(), EllipsisLoc);
5892 else
5893 NewInit = BuildDelegatingInitializer(TInfo, TempInit.get(),
5894 cast<CXXRecordDecl>(CurContext->getParent()));
5895 } else if (Init->isMemberInitializer()) {
5896 FieldDecl *Member = cast_or_null<FieldDecl>(FindInstantiatedDecl(
5897 Init->getMemberLocation(),
5898 Init->getMember(),
5899 TemplateArgs));
5900 if (!Member) {
5901 AnyErrors = true;
5902 New->setInvalidDecl();
5903 continue;
5904 }
5905
5906 NewInit = BuildMemberInitializer(Member, TempInit.get(),
5907 Init->getSourceLocation());
5908 } else if (Init->isIndirectMemberInitializer()) {
5909 IndirectFieldDecl *IndirectMember =
5910 cast_or_null<IndirectFieldDecl>(FindInstantiatedDecl(
5911 Init->getMemberLocation(),
5912 Init->getIndirectMember(), TemplateArgs));
5913
5914 if (!IndirectMember) {
5915 AnyErrors = true;
5916 New->setInvalidDecl();
5917 continue;
5918 }
5919
5920 NewInit = BuildMemberInitializer(IndirectMember, TempInit.get(),
5921 Init->getSourceLocation());
5922 }
5923
5924 if (NewInit.isInvalid()) {
5925 AnyErrors = true;
5926 New->setInvalidDecl();
5927 } else {
5928 NewInits.push_back(NewInit.get());
5929 }
5930 }
5931
5932 // Assign all the initializers to the new constructor.
5934 /*FIXME: ColonLoc */
5936 NewInits,
5937 AnyErrors);
5938}
5939
5940// TODO: this could be templated if the various decl types used the
5941// same method name.
5943 ClassTemplateDecl *Instance) {
5944 Pattern = Pattern->getCanonicalDecl();
5945
5946 do {
5947 Instance = Instance->getCanonicalDecl();
5948 if (Pattern == Instance) return true;
5949 Instance = Instance->getInstantiatedFromMemberTemplate();
5950 } while (Instance);
5951
5952 return false;
5953}
5954
5956 FunctionTemplateDecl *Instance) {
5957 Pattern = Pattern->getCanonicalDecl();
5958
5959 do {
5960 Instance = Instance->getCanonicalDecl();
5961 if (Pattern == Instance) return true;
5962 Instance = Instance->getInstantiatedFromMemberTemplate();
5963 } while (Instance);
5964
5965 return false;
5966}
5967
5968static bool
5971 Pattern
5972 = cast<ClassTemplatePartialSpecializationDecl>(Pattern->getCanonicalDecl());
5973 do {
5974 Instance = cast<ClassTemplatePartialSpecializationDecl>(
5975 Instance->getCanonicalDecl());
5976 if (Pattern == Instance)
5977 return true;
5978 Instance = Instance->getInstantiatedFromMember();
5979 } while (Instance);
5980
5981 return false;
5982}
5983
5985 CXXRecordDecl *Instance) {
5986 Pattern = Pattern->getCanonicalDecl();
5987
5988 do {
5989 Instance = Instance->getCanonicalDecl();
5990 if (Pattern == Instance) return true;
5991 Instance = Instance->getInstantiatedFromMemberClass();
5992 } while (Instance);
5993
5994 return false;
5995}
5996
5997static bool isInstantiationOf(FunctionDecl *Pattern,
5998 FunctionDecl *Instance) {
5999 Pattern = Pattern->getCanonicalDecl();
6000
6001 do {
6002 Instance = Instance->getCanonicalDecl();
6003 if (Pattern == Instance) return true;
6004 Instance = Instance->getInstantiatedFromMemberFunction();
6005 } while (Instance);
6006
6007 return false;
6008}
6009
6010static bool isInstantiationOf(EnumDecl *Pattern,
6011 EnumDecl *Instance) {
6012 Pattern = Pattern->getCanonicalDecl();
6013
6014 do {
6015 Instance = Instance->getCanonicalDecl();
6016 if (Pattern == Instance) return true;
6017 Instance = Instance->getInstantiatedFromMemberEnum();
6018 } while (Instance);
6019
6020 return false;
6021}
6022
6024 UsingShadowDecl *Instance,
6025 ASTContext &C) {
6026 return declaresSameEntity(C.getInstantiatedFromUsingShadowDecl(Instance),
6027 Pattern);
6028}
6029
6030static bool isInstantiationOf(UsingDecl *Pattern, UsingDecl *Instance,
6031 ASTContext &C) {
6032 return declaresSameEntity(C.getInstantiatedFromUsingDecl(Instance), Pattern);
6033}
6034
6035template<typename T>
6037 ASTContext &Ctx) {
6038 // An unresolved using declaration can instantiate to an unresolved using
6039 // declaration, or to a using declaration or a using declaration pack.
6040 //
6041 // Multiple declarations can claim to be instantiated from an unresolved
6042 // using declaration if it's a pack expansion. We want the UsingPackDecl
6043 // in that case, not the individual UsingDecls within the pack.
6044 bool OtherIsPackExpansion;
6045 NamedDecl *OtherFrom;
6046 if (auto *OtherUUD = dyn_cast<T>(Other)) {
6047 OtherIsPackExpansion = OtherUUD->isPackExpansion();
6048 OtherFrom = Ctx.getInstantiatedFromUsingDecl(OtherUUD);
6049 } else if (auto *OtherUPD = dyn_cast<UsingPackDecl>(Other)) {
6050 OtherIsPackExpansion = true;
6051 OtherFrom = OtherUPD->getInstantiatedFromUsingDecl();
6052 } else if (auto *OtherUD = dyn_cast<UsingDecl>(Other)) {
6053 OtherIsPackExpansion = false;
6054 OtherFrom = Ctx.getInstantiatedFromUsingDecl(OtherUD);
6055 } else {
6056 return false;
6057 }
6058 return Pattern->isPackExpansion() == OtherIsPackExpansion &&
6059 declaresSameEntity(OtherFrom, Pattern);
6060}
6061
6063 VarDecl *Instance) {
6064 assert(Instance->isStaticDataMember());
6065
6066 Pattern = Pattern->getCanonicalDecl();
6067
6068 do {
6069 Instance = Instance->getCanonicalDecl();
6070 if (Pattern == Instance) return true;
6071 Instance = Instance->getInstantiatedFromStaticDataMember();
6072 } while (Instance);
6073
6074 return false;
6075}
6076
6077// Other is the prospective instantiation
6078// D is the prospective pattern
6080 if (auto *UUD = dyn_cast<UnresolvedUsingTypenameDecl>(D))
6082
6083 if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(D))
6085
6086 if (D->getKind() != Other->getKind())
6087 return false;
6088
6089 if (auto *Record = dyn_cast<CXXRecordDecl>(Other))
6090 return isInstantiationOf(cast<CXXRecordDecl>(D), Record);
6091
6092 if (auto *Function = dyn_cast<FunctionDecl>(Other))
6093 return isInstantiationOf(cast<FunctionDecl>(D), Function);
6094
6095 if (auto *Enum = dyn_cast<EnumDecl>(Other))
6096 return isInstantiationOf(cast<EnumDecl>(D), Enum);
6097
6098 if (auto *Var = dyn_cast<VarDecl>(Other))
6099 if (Var->isStaticDataMember())
6100 return isInstantiationOfStaticDataMember(cast<VarDecl>(D), Var);
6101
6102 if (auto *Temp = dyn_cast<ClassTemplateDecl>(Other))
6103 return isInstantiationOf(cast<ClassTemplateDecl>(D), Temp);
6104
6105 if (auto *Temp = dyn_cast<FunctionTemplateDecl>(Other))
6106 return isInstantiationOf(cast<FunctionTemplateDecl>(D), Temp);
6107
6108 if (auto *PartialSpec =
6109 dyn_cast<ClassTemplatePartialSpecializationDecl>(Other))
6110 return isInstantiationOf(cast<ClassTemplatePartialSpecializationDecl>(D),
6111 PartialSpec);
6112
6113 if (auto *Field = dyn_cast<FieldDecl>(Other)) {
6114 if (!Field->getDeclName()) {
6115 // This is an unnamed field.
6117 cast<FieldDecl>(D));
6118 }
6119 }
6120
6121 if (auto *Using = dyn_cast<UsingDecl>(Other))
6122 return isInstantiationOf(cast<UsingDecl>(D), Using, Ctx);
6123
6124 if (auto *Shadow = dyn_cast<UsingShadowDecl>(Other))
6125 return isInstantiationOf(cast<UsingShadowDecl>(D), Shadow, Ctx);
6126
6127 return D->getDeclName() &&
6128 D->getDeclName() == cast<NamedDecl>(Other)->getDeclName();
6129}
6130
6131template<typename ForwardIterator>
6133 NamedDecl *D,
6134 ForwardIterator first,
6135 ForwardIterator last) {
6136 for (; first != last; ++first)
6137 if (isInstantiationOf(Ctx, D, *first))
6138 return cast<NamedDecl>(*first);
6139
6140 return nullptr;
6141}
6142
6144 const MultiLevelTemplateArgumentList &TemplateArgs) {
6145 if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) {
6146 Decl* ID = FindInstantiatedDecl(Loc, D, TemplateArgs, true);
6147 return cast_or_null<DeclContext>(ID);
6148 } else return DC;
6149}
6150
6151/// Determine whether the given context is dependent on template parameters at
6152/// level \p Level or below.
6153///
6154/// Sometimes we only substitute an inner set of template arguments and leave
6155/// the outer templates alone. In such cases, contexts dependent only on the
6156/// outer levels are not effectively dependent.
6157static bool isDependentContextAtLevel(DeclContext *DC, unsigned Level) {
6158 if (!DC->isDependentContext())
6159 return false;
6160 if (!Level)
6161 return true;
6162 return cast<Decl>(DC)->getTemplateDepth() > Level;
6163}
6164
6166 const MultiLevelTemplateArgumentList &TemplateArgs,
6167 bool FindingInstantiatedContext) {
6168 DeclContext *ParentDC = D->getDeclContext();
6169 // Determine whether our parent context depends on any of the template
6170 // arguments we're currently substituting.
6171 bool ParentDependsOnArgs = isDependentContextAtLevel(
6172 ParentDC, TemplateArgs.getNumRetainedOuterLevels());
6173 // FIXME: Parameters of pointer to functions (y below) that are themselves
6174 // parameters (p below) can have their ParentDC set to the translation-unit
6175 // - thus we can not consistently check if the ParentDC of such a parameter
6176 // is Dependent or/and a FunctionOrMethod.
6177 // For e.g. this code, during Template argument deduction tries to
6178 // find an instantiated decl for (T y) when the ParentDC for y is
6179 // the translation unit.
6180 // e.g. template <class T> void Foo(auto (*p)(T y) -> decltype(y())) {}
6181 // float baz(float(*)()) { return 0.0; }
6182 // Foo(baz);
6183 // The better fix here is perhaps to ensure that a ParmVarDecl, by the time
6184 // it gets here, always has a FunctionOrMethod as its ParentDC??
6185 // For now:
6186 // - as long as we have a ParmVarDecl whose parent is non-dependent and
6187 // whose type is not instantiation dependent, do nothing to the decl
6188 // - otherwise find its instantiated decl.
6189 if (isa<ParmVarDecl>(D) && !ParentDependsOnArgs &&
6190 !cast<ParmVarDecl>(D)->getType()->isInstantiationDependentType())
6191 return D;
6192 if (isa<ParmVarDecl>(D) || isa<NonTypeTemplateParmDecl>(D) ||
6193 isa<TemplateTypeParmDecl>(D) || isa<TemplateTemplateParmDecl>(D) ||
6194 (ParentDependsOnArgs && (ParentDC->isFunctionOrMethod() ||
6195 isa<OMPDeclareReductionDecl>(ParentDC) ||
6196 isa<OMPDeclareMapperDecl>(ParentDC))) ||
6197 (isa<CXXRecordDecl>(D) && cast<CXXRecordDecl>(D)->isLambda() &&
6198 cast<CXXRecordDecl>(D)->getTemplateDepth() >
6199 TemplateArgs.getNumRetainedOuterLevels())) {
6200 // D is a local of some kind. Look into the map of local
6201 // declarations to their instantiations.
6204 if (Decl *FD = Found->dyn_cast<Decl *>())
6205 return cast<NamedDecl>(FD);
6206
6207 int PackIdx = ArgumentPackSubstitutionIndex;
6208 assert(PackIdx != -1 &&
6209 "found declaration pack but not pack expanding");
6210 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
6211 return cast<NamedDecl>((*cast<DeclArgumentPack *>(*Found))[PackIdx]);
6212 }
6213 }
6214
6215 // If we're performing a partial substitution during template argument
6216 // deduction, we may not have values for template parameters yet. They
6217 // just map to themselves.
6218 if (isa<NonTypeTemplateParmDecl>(D) || isa<TemplateTypeParmDecl>(D) ||
6219 isa<TemplateTemplateParmDecl>(D))
6220 return D;
6221
6222 if (D->isInvalidDecl())
6223 return nullptr;
6224
6225 // Normally this function only searches for already instantiated declaration
6226 // however we have to make an exclusion for local types used before
6227 // definition as in the code:
6228 //
6229 // template<typename T> void f1() {
6230 // void g1(struct x1);
6231 // struct x1 {};
6232 // }
6233 //
6234 // In this case instantiation of the type of 'g1' requires definition of
6235 // 'x1', which is defined later. Error recovery may produce an enum used
6236 // before definition. In these cases we need to instantiate relevant
6237 // declarations here.
6238 bool NeedInstantiate = false;
6239 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
6240 NeedInstantiate = RD->isLocalClass();
6241 else if (isa<TypedefNameDecl>(D) &&
6242 isa<CXXDeductionGuideDecl>(D->getDeclContext()))
6243 NeedInstantiate = true;
6244 else
6245 NeedInstantiate = isa<EnumDecl>(D);
6246 if (NeedInstantiate) {
6247 Decl *Inst = SubstDecl(D, CurContext, TemplateArgs);
6249 return cast<TypeDecl>(Inst);
6250 }
6251
6252 // If we didn't find the decl, then we must have a label decl that hasn't
6253 // been found yet. Lazily instantiate it and return it now.
6254 assert(isa<LabelDecl>(D));
6255
6256 Decl *Inst = SubstDecl(D, CurContext, TemplateArgs);
6257 assert(Inst && "Failed to instantiate label??");
6258
6260 return cast<LabelDecl>(Inst);
6261 }
6262
6263 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
6264 if (!Record->isDependentContext())
6265 return D;
6266
6267 // Determine whether this record is the "templated" declaration describing
6268 // a class template or class template specialization.
6269 ClassTemplateDecl *ClassTemplate = Record->getDescribedClassTemplate();
6270 if (ClassTemplate)
6271 ClassTemplate = ClassTemplate->getCanonicalDecl();
6272 else if (ClassTemplateSpecializationDecl *Spec =
6273 dyn_cast<ClassTemplateSpecializationDecl>(Record))
6274 ClassTemplate = Spec->getSpecializedTemplate()->getCanonicalDecl();
6275
6276 // Walk the current context to find either the record or an instantiation of
6277 // it.
6278 DeclContext *DC = CurContext;
6279 while (!DC->isFileContext()) {
6280 // If we're performing substitution while we're inside the template
6281 // definition, we'll find our own context. We're done.
6282 if (DC->Equals(Record))
6283 return Record;
6284
6285 if (CXXRecordDecl *InstRecord = dyn_cast<CXXRecordDecl>(DC)) {
6286 // Check whether we're in the process of instantiating a class template
6287 // specialization of the template we're mapping.
6289 = dyn_cast<ClassTemplateSpecializationDecl>(InstRecord)){
6290 ClassTemplateDecl *SpecTemplate = InstSpec->getSpecializedTemplate();
6291 if (ClassTemplate && isInstantiationOf(ClassTemplate, SpecTemplate))
6292 return InstRecord;
6293 }
6294
6295 // Check whether we're in the process of instantiating a member class.
6296 if (isInstantiationOf(Record, InstRecord))
6297 return InstRecord;
6298 }
6299
6300 // Move to the outer template scope.
6301 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC)) {
6302 if (FD->getFriendObjectKind() &&
6304 DC = FD->getLexicalDeclContext();
6305 continue;
6306 }
6307 // An implicit deduction guide acts as if it's within the class template
6308 // specialization described by its name and first N template params.
6309 auto *Guide = dyn_cast<CXXDeductionGuideDecl>(FD);
6310 if (Guide && Guide->isImplicit()) {
6311 TemplateDecl *TD = Guide->getDeducedTemplate();
6312 // Convert the arguments to an "as-written" list.
6314 for (TemplateArgument Arg : TemplateArgs.getInnermost().take_front(
6315 TD->getTemplateParameters()->size())) {
6316 ArrayRef<TemplateArgument> Unpacked(Arg);
6317 if (Arg.getKind() == TemplateArgument::Pack)
6318 Unpacked = Arg.pack_elements();
6319 for (TemplateArgument UnpackedArg : Unpacked)
6320 Args.addArgument(
6321 getTrivialTemplateArgumentLoc(UnpackedArg, QualType(), Loc));
6322 }
6324 // We may get a non-null type with errors, in which case
6325 // `getAsCXXRecordDecl` will return `nullptr`. For instance, this
6326 // happens when one of the template arguments is an invalid
6327 // expression. We return early to avoid triggering the assertion
6328 // about the `CodeSynthesisContext`.
6329 if (T.isNull() || T->containsErrors())
6330 return nullptr;
6331 CXXRecordDecl *SubstRecord = T->getAsCXXRecordDecl();
6332
6333 if (!SubstRecord) {
6334 // T can be a dependent TemplateSpecializationType when performing a
6335 // substitution for building a deduction guide or for template
6336 // argument deduction in the process of rebuilding immediate
6337 // expressions. (Because the default argument that involves a lambda
6338 // is untransformed and thus could be dependent at this point.)
6340 CodeSynthesisContexts.back().Kind ==
6342 // Return a nullptr as a sentinel value, we handle it properly in
6343 // the TemplateInstantiator::TransformInjectedClassNameType
6344 // override, which we transform it to a TemplateSpecializationType.
6345 return nullptr;
6346 }
6347 // Check that this template-id names the primary template and not a
6348 // partial or explicit specialization. (In the latter cases, it's
6349 // meaningless to attempt to find an instantiation of D within the
6350 // specialization.)
6351 // FIXME: The standard doesn't say what should happen here.
6352 if (FindingInstantiatedContext &&
6354 Loc, cast<ClassTemplateSpecializationDecl>(SubstRecord))) {
6355 Diag(Loc, diag::err_specialization_not_primary_template)
6356 << T << (SubstRecord->getTemplateSpecializationKind() ==
6358 return nullptr;
6359 }
6360 DC = SubstRecord;
6361 continue;
6362 }
6363 }
6364
6365 DC = DC->getParent();
6366 }
6367
6368 // Fall through to deal with other dependent record types (e.g.,
6369 // anonymous unions in class templates).
6370 }
6371
6372 if (!ParentDependsOnArgs)
6373 return D;
6374
6375 ParentDC = FindInstantiatedContext(Loc, ParentDC, TemplateArgs);
6376 if (!ParentDC)
6377 return nullptr;
6378
6379 if (ParentDC != D->getDeclContext()) {
6380 // We performed some kind of instantiation in the parent context,
6381 // so now we need to look into the instantiated parent context to
6382 // find the instantiation of the declaration D.
6383
6384 // If our context used to be dependent, we may need to instantiate
6385 // it before performing lookup into that context.
6386 bool IsBeingInstantiated = false;
6387 if (CXXRecordDecl *Spec = dyn_cast<CXXRecordDecl>(ParentDC)) {
6388 if (!Spec->isDependentContext()) {
6390 const RecordType *Tag = T->getAs<RecordType>();
6391 assert(Tag && "type of non-dependent record is not a RecordType");
6392 if (Tag->isBeingDefined())
6393 IsBeingInstantiated = true;
6394 if (!Tag->isBeingDefined() &&
6395 RequireCompleteType(Loc, T, diag::err_incomplete_type))
6396 return nullptr;
6397
6398 ParentDC = Tag->getDecl();
6399 }
6400 }
6401
6402 NamedDecl *Result = nullptr;
6403 // FIXME: If the name is a dependent name, this lookup won't necessarily
6404 // find it. Does that ever matter?
6405 if (auto Name = D->getDeclName()) {
6406 DeclarationNameInfo NameInfo(Name, D->getLocation());
6407 DeclarationNameInfo NewNameInfo =
6408 SubstDeclarationNameInfo(NameInfo, TemplateArgs);
6409 Name = NewNameInfo.getName();
6410 if (!Name)
6411 return nullptr;
6412 DeclContext::lookup_result Found = ParentDC->lookup(Name);
6413
6414 Result = findInstantiationOf(Context, D, Found.begin(), Found.end());
6415 } else {
6416 // Since we don't have a name for the entity we're looking for,
6417 // our only option is to walk through all of the declarations to
6418 // find that name. This will occur in a few cases:
6419 //
6420 // - anonymous struct/union within a template
6421 // - unnamed class/struct/union/enum within a template
6422 //
6423 // FIXME: Find a better way to find these instantiations!
6425 ParentDC->decls_begin(),
6426 ParentDC->decls_end());
6427 }
6428
6429 if (!Result) {
6430 if (isa<UsingShadowDecl>(D)) {
6431 // UsingShadowDecls can instantiate to nothing because of using hiding.
6432 } else if (hasUncompilableErrorOccurred()) {
6433 // We've already complained about some ill-formed code, so most likely
6434 // this declaration failed to instantiate. There's no point in
6435 // complaining further, since this is normal in invalid code.
6436 // FIXME: Use more fine-grained 'invalid' tracking for this.
6437 } else if (IsBeingInstantiated) {
6438 // The class in which this member exists is currently being
6439 // instantiated, and we haven't gotten around to instantiating this
6440 // member yet. This can happen when the code uses forward declarations
6441 // of member classes, and introduces ordering dependencies via
6442 // template instantiation.
6443 Diag(Loc, diag::err_member_not_yet_instantiated)
6444 << D->getDeclName()
6445 << Context.getTypeDeclType(cast<CXXRecordDecl>(ParentDC));
6446 Diag(D->getLocation(), diag::note_non_instantiated_member_here);
6447 } else if (EnumConstantDecl *ED = dyn_cast<EnumConstantDecl>(D)) {
6448 // This enumeration constant was found when the template was defined,
6449 // but can't be found in the instantiation. This can happen if an
6450 // unscoped enumeration member is explicitly specialized.
6451 EnumDecl *Enum = cast<EnumDecl>(ED->getLexicalDeclContext());
6452 EnumDecl *Spec = cast<EnumDecl>(FindInstantiatedDecl(Loc, Enum,
6453 TemplateArgs));
6454 assert(Spec->getTemplateSpecializationKind() ==
6456 Diag(Loc, diag::err_enumerator_does_not_exist)
6457 << D->getDeclName()
6458 << Context.getTypeDeclType(cast<TypeDecl>(Spec->getDeclContext()));
6459 Diag(Spec->getLocation(), diag::note_enum_specialized_here)
6460 << Context.getTypeDeclType(Spec);
6461 } else {
6462 // We should have found something, but didn't.
6463 llvm_unreachable("Unable to find instantiation of declaration!");
6464 }
6465 }
6466
6467 D = Result;
6468 }
6469
6470 return D;
6471}
6472
6474 std::deque<PendingImplicitInstantiation> delayedPCHInstantiations;
6475 while (!PendingLocalImplicitInstantiations.empty() ||
6476 (!LocalOnly && !PendingInstantiations.empty())) {
6478
6480 Inst = PendingInstantiations.front();
6481 PendingInstantiations.pop_front();
6482 } else {
6485 }
6486
6487 // Instantiate function definitions
6488 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) {
6489 bool DefinitionRequired = Function->getTemplateSpecializationKind() ==
6491 if (Function->isMultiVersion()) {
6493 Function, [this, Inst, DefinitionRequired](FunctionDecl *CurFD) {
6494 InstantiateFunctionDefinition(/*FIXME:*/ Inst.second, CurFD, true,
6495 DefinitionRequired, true);
6496 if (CurFD->isDefined())
6497 CurFD->setInstantiationIsPending(false);
6498 });
6499 } else {
6500 InstantiateFunctionDefinition(/*FIXME:*/ Inst.second, Function, true,
6501 DefinitionRequired, true);
6502 if (Function->isDefined())
6503 Function->setInstantiationIsPending(false);
6504 }
6505 // Definition of a PCH-ed template declaration may be available only in the TU.
6506 if (!LocalOnly && LangOpts.PCHInstantiateTemplates &&
6507 TUKind == TU_Prefix && Function->instantiationIsPending())
6508 delayedPCHInstantiations.push_back(Inst);
6509 continue;
6510 }
6511
6512 // Instantiate variable definitions
6513 VarDecl *Var = cast<VarDecl>(Inst.first);
6514
6515 assert((Var->isStaticDataMember() ||
6516 isa<VarTemplateSpecializationDecl>(Var)) &&
6517 "Not a static data member, nor a variable template"
6518 " specialization?");
6519
6520 // Don't try to instantiate declarations if the most recent redeclaration
6521 // is invalid.
6522 if (Var->getMostRecentDecl()->isInvalidDecl())
6523 continue;
6524
6525 // Check if the most recent declaration has changed the specialization kind
6526 // and removed the need for implicit instantiation.
6527 switch (Var->getMostRecentDecl()
6529 case TSK_Undeclared:
6530 llvm_unreachable("Cannot instantitiate an undeclared specialization.");
6533 continue; // No longer need to instantiate this type.
6535 // We only need an instantiation if the pending instantiation *is* the
6536 // explicit instantiation.
6537 if (Var != Var->getMostRecentDecl())
6538 continue;
6539 break;
6541 break;
6542 }
6543
6545 "instantiating variable definition");
6546 bool DefinitionRequired = Var->getTemplateSpecializationKind() ==
6548
6549 // Instantiate static data member definitions or variable template
6550 // specializations.
6551 InstantiateVariableDefinition(/*FIXME:*/ Inst.second, Var, true,
6552 DefinitionRequired, true);
6553 }
6554
6555 if (!LocalOnly && LangOpts.PCHInstantiateTemplates)
6556 PendingInstantiations.swap(delayedPCHInstantiations);
6557}
6558
6560 const MultiLevelTemplateArgumentList &TemplateArgs) {
6561 for (auto *DD : Pattern->ddiags()) {
6562 switch (DD->getKind()) {
6564 HandleDependentAccessCheck(*DD, TemplateArgs);
6565 break;
6566 }
6567 }
6568}
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:2716
bool hasSameType(QualType T1, QualType T2) const
Determine whether the given types T1 and T2 are equivalent.
Definition: ASTContext.h:2732
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
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:799
void setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst, FieldDecl *Tmpl)
void addTypedefNameForUnnamedTagDecl(TagDecl *TD, TypedefNameDecl *TND)
An abstract interface that should be implemented by listeners that want to be notified when an AST en...
Represents an access specifier followed by colon ':'.
Definition: DeclCXX.h:86
static AccessSpecDecl * Create(ASTContext &C, AccessSpecifier AS, DeclContext *DC, SourceLocation ASLoc, SourceLocation ColonLoc)
Definition: DeclCXX.h:117
PtrTy get() const
Definition: Ownership.h:170
bool isInvalid() const
Definition: Ownership.h:166
bool isUsable() const
Definition: Ownership.h:168
Attr - This represents one attribute.
Definition: Attr.h: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:3435
A binding in a decomposition declaration.
Definition: DeclCXX.h:4125
static BindingDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation IdLoc, IdentifierInfo *Id)
Definition: DeclCXX.cpp:3404
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:2553
bool isDefaultConstructor() const
Whether this constructor is a default constructor (C++ [class.ctor]p5), which can be used to default-...
Definition: DeclCXX.cpp:2845
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:2815
Represents a C++ conversion function within a class.
Definition: DeclCXX.h:2880
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:2982
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)
Definition: DeclCXX.cpp:2250
Represents a C++ destructor within a class.
Definition: DeclCXX.h:2817
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:2949
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:2078
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition: DeclCXX.h:2204
bool isMoveAssignmentOperator() const
Determine whether this is a move assignment operator.
Definition: DeclCXX.cpp:2582
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:2368
bool isCopyAssignmentOperator() const
Determine whether this is a copy-assignment operator, regardless of whether it was declared implicitl...
Definition: DeclCXX.cpp:2560
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:147
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:131
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine whether this particular class is a specialization or instantiation of a class template or m...
Definition: DeclCXX.cpp:1999
void setInstantiationOfMemberClass(CXXRecordDecl *RD, TemplateSpecializationKind TSK)
Specify that this record is an instantiation of the member class RD.
Definition: DeclCXX.cpp:1982
void setDescribedClassTemplate(ClassTemplateDecl *Template)
Definition: DeclCXX.cpp:1995
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:421
Represents a shadow constructor declaration introduced into a class by a C++11 using-declaration that...
Definition: DeclCXX.h:3616
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:1368
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1435
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:2089
bool Equals(const DeclContext *DC) const
Determine whether this declaration context is equivalent to the declaration context DC.
Definition: DeclBase.h:2218
bool isFileContext() const
Definition: DeclBase.h:2160
void makeDeclVisibleInContext(NamedDecl *D)
Makes a declaration visible within this context.
Definition: DeclBase.cpp:2045
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
Definition: DeclBase.cpp:1334
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
Definition: DeclBase.cpp:1854
bool isRecord() const
Definition: DeclBase.h:2169
DeclContext * getRedeclContext()
getRedeclContext - Retrieve the context in which an entity conflicts with other entities of the same ...
Definition: DeclBase.cpp:1990
void addDecl(Decl *D)
Add the declaration D into this context.
Definition: DeclBase.cpp:1768
decl_iterator decls_end() const
Definition: DeclBase.h:2351
ddiag_range ddiags() const
decl_range decls() const
decls_begin/decls_end - Iterate over the declarations stored in this context.
Definition: DeclBase.h:2349
bool isFunctionOrMethod() const
Definition: DeclBase.h:2141
void addHiddenDecl(Decl *D)
Add the declaration D to this context without modifying any lookup tables.
Definition: DeclBase.cpp:1742
decl_iterator decls_begin() const
Definition: DeclBase.cpp:1624
static DeclRefExpr * Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, ValueDecl *D, bool RefersToEnclosingVariableOrCapture, SourceLocation NameLoc, QualType T, ExprValueKind VK, NamedDecl *FoundD=nullptr, const TemplateArgumentListInfo *TemplateArgs=nullptr, NonOdrUseReason NOUR=NOUR_None)
Definition: Expr.cpp:488
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:86
Decl * getPreviousDecl()
Retrieve the previous declaration that declares the same entity as this declaration,...
Definition: DeclBase.h:1050
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:1215
T * getAttr() const
Definition: DeclBase.h:576
void addAttr(Attr *A)
Definition: DeclBase.cpp:1010
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:1140
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:239
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
Definition: DeclBase.cpp:151
bool isInIdentifierNamespace(unsigned NS) const
Definition: DeclBase.h:882
@ FOK_None
Not a friend object.
Definition: DeclBase.h:1206
bool isReferenced() const
Whether any declaration of this entity was referenced.
Definition: DeclBase.cpp:574
unsigned getTemplateDepth() const
Determine the number of levels of template parameter surrounding this declaration.
Definition: DeclBase.cpp:293
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:1169
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:395
DeclContext * getNonTransparentDeclContext()
Return the non transparent context.
Definition: DeclBase.cpp:1217
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:1082
bool isInvalidDecl() const
Definition: DeclBase.h:591
bool isLocalExternDecl() const
Determine whether this is a block-scope declaration with linkage.
Definition: DeclBase.h:1158
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:142
@ 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:549
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:907
bool hasAttr() const
Definition: DeclBase.h:580
void setNonMemberOperator()
Specifies that this declaration is a C++ overloaded non-member.
Definition: DeclBase.h:1224
void setLexicalDeclContext(DeclContext *DC)
Definition: DeclBase.cpp:359
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclBase.h:967
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:859
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:5874
Expr * getUnderlyingExpr() const
Definition: Type.h:5884
A decomposition declaration.
Definition: DeclCXX.h:4184
static DecompositionDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation LSquareLoc, QualType T, TypeSourceInfo *TInfo, StorageClass S, ArrayRef< BindingDecl * > Bindings)
Definition: DeclCXX.cpp:3428
Provides information about a dependent function-template specialization declaration.
Definition: DeclTemplate.h:694
Represents a qualified type name for which the type name is dependent.
Definition: Type.h:7024
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:3277
Represents an enum.
Definition: Decl.h:3847
enumerator_range enumerators() const
Definition: Decl.h:3980
bool isScoped() const
Returns true if this is a C++11 scoped enumeration.
Definition: Decl.h:4052
static EnumDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, EnumDecl *PrevDecl, bool IsScoped, bool IsScopedUsingClassTag, bool IsFixed)
Definition: Decl.cpp:4875
TypeSourceInfo * getIntegerTypeSourceInfo() const
Return the type source info for the underlying integer type, if no type source info exists,...
Definition: Decl.h:4023
EnumDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: Decl.h:3928
TemplateSpecializationKind getTemplateSpecializationKind() const
If this enumeration is a member of a specialization of a templated class, determine what kind of temp...
Definition: Decl.cpp:4928
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:2237
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:3090
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:3318
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:978
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:4057
FunctionTemplateDecl * getDescribedFunctionTemplate() const
Retrieves the function template that is described by this function declaration.
Definition: Decl.cpp:4052
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:4123
FunctionDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: Decl.cpp:3623
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:3702
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:5102
ExceptionSpecificationType getExceptionSpecType() const
Get the kind of exception specification on this function.
Definition: Type.h:5382
QualType getParamType(unsigned i) const
Definition: Type.h:5357
bool hasExceptionSpec() const
Return whether this function has any kind of exception spec.
Definition: Type.h:5388
ExtProtoInfo getExtProtoInfo() const
Definition: Type.h:5366
FunctionDecl * getExceptionSpecTemplate() const
If this function type has an uninstantiated exception specification, this is the function whose excep...
Definition: Type.h:5461
ArrayRef< QualType > getParamTypes() const
Definition: Type.h:5362
Declaration of a template function.
Definition: DeclTemplate.h:959
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:1537
void setParam(unsigned i, ParmVarDecl *VD)
Definition: TypeLoc.h:1538
ExtInfo getExtInfo() const
Definition: Type.h:4655
bool getNoReturnAttr() const
Determine whether this function type includes the GNU noreturn attribute.
Definition: Type.h:4651
QualType getReturnType() const
Definition: Type.h:4643
HLSLBufferDecl - Represent a cbuffer or tbuffer declaration.
Definition: Decl.h:4927
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:3321
static IndirectFieldDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, const IdentifierInfo *Id, QualType T, llvm::MutableArrayRef< NamedDecl * > CH)
Definition: Decl.cpp:5504
Description of a constructor that was inherited from a base class.
Definition: DeclCXX.h:2524
const TypeClass * getTypePtr() const
Definition: TypeLoc.h:514
static IntegerLiteral * Create(const ASTContext &C, const llvm::APInt &V, QualType type, SourceLocation l)
Returns a new integer literal with value 'V' and type 'type'.
Definition: Expr.cpp:973
Represents the declaration of a label.
Definition: Decl.h:503
static LabelDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation IdentL, IdentifierInfo *II)
Definition: Decl.cpp:5362
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:4307
An instance of this class represents the declaration of a property member.
Definition: DeclCXX.h:4253
static MSPropertyDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, DeclarationName N, QualType T, TypeSourceInfo *TInfo, SourceLocation StartL, IdentifierInfo *Getter, IdentifierInfo *Setter)
Definition: DeclCXX.cpp:3469
Provides information a specialization of a member of a class template, which may be a member function...
Definition: DeclTemplate.h:620
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:3138
static NamespaceAliasDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation NamespaceLoc, SourceLocation AliasLoc, IdentifierInfo *Alias, NestedNameSpecifierLoc QualifierLoc, SourceLocation IdentLoc, NamedDecl *Namespace)
Definition: DeclCXX.cpp:3107
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:2609
TypeLoc getPatternLoc() const
Definition: TypeLoc.h:2625
Represents a pack expansion of types.
Definition: Type.h:7141
std::optional< unsigned > getNumExpansions() const
Retrieve the number of expansions that this pack expansion will generate, if known.
Definition: Type.h:7166
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:8134
The collection of all-type qualifiers we support.
Definition: Type.h:324
Represents a struct/union/class.
Definition: Decl.h:4148
Wrapper for source info for record types.
Definition: TypeLoc.h:741
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:6072
void setInstantiatedFromMemberTemplate(RedeclarableTemplateDecl *TD)
Definition: DeclTemplate.h:910
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:4981
Represents the body of a requires-expression.
Definition: DeclCXX.h:2047
static RequiresExprBodyDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc)
Definition: DeclCXX.cpp:2268
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:2483
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:13193
RAII object used to temporarily allow the C++ 'this' expression to be used, with the given qualifiers...
Definition: Sema.h:8041
A RAII object to temporarily push a declaration context.
Definition: Sema.h:3003
CXXSpecialMemberKind asSpecialMember() const
Definition: Sema.h:5913
A helper class for building up ExtParameterInfos.
Definition: Sema.h:12607
Records and restores the CurFPFeatures state on entry/exit of compound statements.
Definition: Sema.h:13562
RAII class used to indicate that we are performing provisional semantic analysis to determine the val...
Definition: Sema.h:12118
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:463
SemaAMDGPU & AMDGPU()
Definition: Sema.h:1045
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:13127
LocalInstantiationScope * CurrentInstantiationScope
The current instantiation scope used to store local variables.
Definition: Sema.h:12636
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:8983
@ LookupUsingDeclName
Look up all declarations in a scope with the given name, including resolved using declarations.
Definition: Sema.h:9010
@ LookupRedeclarationWithLinkage
Look up an ordinary name that is going to be redeclared as a name with linkage.
Definition: Sema.h:9015
Decl * ActOnSkippedFunctionBody(Decl *Decl)
Definition: SemaDecl.cpp:15876
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:4604
bool InstantiateDefaultArgument(SourceLocation CallLoc, FunctionDecl *FD, ParmVarDecl *Param)
SemaOpenMP & OpenMP()
Definition: Sema.h:1125
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:866
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:1070
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:6440
llvm::DenseSet< std::pair< Decl *, unsigned > > InstantiatingSpecializations
Specializations whose definitions are currently being instantiated.
Definition: Sema.h:13130
void deduceOpenCLAddressSpace(ValueDecl *decl)
Definition: SemaDecl.cpp:6828
PragmaStack< FPOptionsOverride > FpPragmaStack
Definition: Sema.h:1657
FunctionDecl * InstantiateFunctionDeclaration(FunctionTemplateDecl *FTD, const TemplateArgumentList *Args, SourceLocation Loc, CodeSynthesisContext::SynthesisKind CSC=CodeSynthesisContext::ExplicitTemplateArgumentSubstitution)
Instantiate (or find existing instantiation of) a function template with a given set of template argu...
bool tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec)
tryResolveExplicitSpecifier - Attempt to resolve the explict specifier.
ExprResult SubstInitializer(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs, bool CXXDirectInit)
MemInitResult BuildMemberInitializer(ValueDecl *Member, Expr *Init, SourceLocation IdLoc)
UsingShadowDecl * BuildUsingShadowDecl(Scope *S, BaseUsingDecl *BUD, NamedDecl *Target, UsingShadowDecl *PrevDecl)
Builds a shadow declaration corresponding to a 'using' declaration.
void CheckThreadLocalForLargeAlignment(VarDecl *VD)
Definition: SemaDecl.cpp:14657
void SubstExceptionSpec(FunctionDecl *New, const FunctionProtoType *Proto, const MultiLevelTemplateArgumentList &Args)
ExpressionEvaluationContextRecord & parentEvaluationContext()
Definition: Sema.h:6452
LateParsedTemplateMapT LateParsedTemplateMap
Definition: Sema.h:11054
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:15164
ASTContext & Context
Definition: Sema.h:908
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:528
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:1110
DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType=nullptr)
Definition: SemaDecl.cpp:70
void InstantiateMemInitializers(CXXConstructorDecl *New, const CXXConstructorDecl *Tmpl, const MultiLevelTemplateArgumentList &TemplateArgs)
void CleanupVarDeclMarking()
Definition: SemaExpr.cpp:19660
ASTContext & getASTContext() const
Definition: Sema.h:531
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:816
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:11782
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:3283
bool CheckEnumUnderlyingType(TypeSourceInfo *TI)
Check that this is a valid underlying type for an enum declaration.
Definition: SemaDecl.cpp:16850
void InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs, const Decl *Pattern, Decl *Inst, LateInstantiatedAttrVec *LateAttrs=nullptr, LocalInstantiationScope *OuterMostScope=nullptr)
const LangOptions & getLangOpts() const
Definition: Sema.h:524
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:952
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:906
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:15352
SemaHLSL & HLSL()
Definition: Sema.h:1075
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:11912
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:18485
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:13523
DeclarationNameInfo SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo, const MultiLevelTemplateArgumentList &TemplateArgs)
Do template substitution on declaration name info.
SemaSwift & Swift()
Definition: Sema.h:1150
std::vector< std::unique_ptr< TemplateInstantiationCallback > > TemplateInstCallbacks
The template instantiation callbacks to trace or track instantiations (objects can be chained).
Definition: Sema.h:13179
const VarDecl * getCopyElisionCandidate(NamedReturnInfo &Info, QualType ReturnType)
Updates given NamedReturnInfo's move-eligible and copy-elidable statuses, considering the function re...
Definition: SemaStmt.cpp:3361
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:8914
int ArgumentPackSubstitutionIndex
The current index into pack expansion arguments that will be used for substitution of parameter packs...
Definition: Sema.h:13187
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:2359
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition: Sema.h:1043
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:1120
std::deque< PendingImplicitInstantiation > PendingLocalImplicitInstantiations
The queue of implicit template instantiations that are required and must be performed within the curr...
Definition: Sema.h:13536
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:20110
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:529
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:20011
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:15886
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:19542
ASTConsumer & Consumer
Definition: Sema.h:909
void DiagnoseUnusedNestedTypedefs(const RecordDecl *D)
Definition: SemaDecl.cpp:2050
bool hasUncompilableErrorOccurred() const
Whether uncompilable error has occurred.
Definition: Sema.cpp:1684
std::deque< PendingImplicitInstantiation > PendingInstantiations
The queue of implicit template instantiations that are required but have not yet been performed.
Definition: Sema.h:13519
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:14620
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:9068
LateTemplateParserCB * LateTemplateParser
Definition: Sema.h:950
bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, bool InUnqualifiedLookup=false)
Perform qualified name lookup into a given context.
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)
Check that the given template arguments can be provided to the given template, converting the argumen...
bool RebuildingImmediateInvocation
Whether the AST is currently being rebuilt to correct immediate invocations.
Definition: Sema.h:7760
SourceManager & SourceMgr
Definition: Sema.h:911
bool CheckAlignasTypeArgument(StringRef KWName, TypeSourceInfo *TInfo, SourceLocation OpLoc, SourceRange R)
Definition: SemaExpr.cpp:4703
NamedDecl * BuildUsingPackDecl(NamedDecl *InstantiatedFrom, ArrayRef< NamedDecl * > Expansions)
void SetDeclDeleted(Decl *dcl, SourceLocation DelLoc, StringLiteral *Message=nullptr)
FPOptions CurFPFeatures
Definition: Sema.h:904
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:7253
Attr * CreateAnnotationAttr(const AttributeCommonInfo &CI, StringRef Annot, MutableArrayRef< Expr * > Args)
CreateAnnotationAttr - Creates an annotation Annot with Args arguments.
Definition: Sema.cpp:2780
@ TPC_ClassTemplate
Definition: Sema.h:11271
@ TPC_FriendFunctionTemplate
Definition: Sema.h:11276
@ TPC_FriendFunctionTemplateDefinition
Definition: Sema.h:11277
void DiagnoseUnusedDecl(const NamedDecl *ND)
Definition: SemaDecl.cpp:2068
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:1579
void ActOnUninitializedDecl(Decl *dcl)
Definition: SemaDecl.cpp:13945
void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit)
AddInitializerToDecl - Adds the initializer Init to the declaration dcl.
Definition: SemaDecl.cpp:13386
void runWithSufficientStackSpace(SourceLocation Loc, llvm::function_ref< void()> Fn)
Run some code with "sufficient" stack space.
Definition: Sema.cpp:562
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:18078
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:21161
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:13515
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:2435
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:11046
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:16867
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:5332
ASTMutationListener * getASTMutationListener() const
Definition: Sema.cpp:588
ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue)
Definition: Sema.h:8261
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:4076
Stmt - This represents one statement.
Definition: Stmt.h:84
SourceLocation getEndLoc() const LLVM_READONLY
Definition: Stmt.cpp:357
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Stmt.cpp:345
Represents the declaration of a struct/union/class/enum.
Definition: Decl.h:3564
NestedNameSpecifierLoc getQualifierLoc() const
Retrieve the nested-name-specifier (with source-location information) that qualifies the name of this...
Definition: Decl.h:3809
TypedefNameDecl * getTypedefNameForAnonDecl() const
Definition: Decl.h:3792
void setTypedefNameForAnonDecl(TypedefNameDecl *TDD)
Definition: Decl.cpp:4751
void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc)
Definition: Decl.cpp:4806
bool hasNameForLinkage() const
Is this tag type named, either directly or via being defined in a typedef of this type?
Definition: Decl.h:3788
TagKind getTagKind() const
Definition: Decl.h:3759
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:399
TemplateParameterList * getTemplateParameters() const
Get the list of template parameters.
Definition: DeclTemplate.h:418
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:3535
static TypeAliasDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, TypeSourceInfo *TInfo)
Definition: Decl.cpp:5576
void setDescribedAliasTemplate(TypeAliasTemplateDecl *TAT)
Definition: Decl.h:3554
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:3396
const Type * getTypeForDecl() const
Definition: Decl.h:3395
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Decl.h:3398
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:1256
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:2715
A container of type source information.
Definition: Type.h:7902
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:7913
SourceLocation getNameLoc() const
Definition: TypeLoc.h:535
void setNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:539
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.cpp:1916
bool isRValueReferenceType() const
Definition: Type.h:8212
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:8800
bool isReferenceType() const
Definition: Type.h:8204
AutoType * getContainedAutoType() const
Get the AutoType whose type will be deduced for a variable with an initializer of this type.
Definition: Type.h:2811
bool isInstantiationDependentType() const
Determine whether this type is an instantiation-dependent type, meaning that the type involves a temp...
Definition: Type.h:2714
bool isLValueReferenceType() const
Definition: Type.h:8208
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: Type.h:2706
bool containsErrors() const
Whether this type is an error type.
Definition: Type.h:2700
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition: Type.h:2724
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition: Type.h:8644
bool isFunctionType() const
Definition: Type.h:8182
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:8731
Represents the declaration of a typedef-name via the 'typedef' type specifier.
Definition: Decl.h:3514
static TypedefDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, TypeSourceInfo *TInfo)
Definition: Decl.cpp:5525
Base class for declarations which introduce a typedef-name.
Definition: Decl.h:3413
An artificial decl, representing a global anonymous constant value which is uniquified by value withi...
Definition: DeclCXX.h:4364
This node is generated when a using-declaration that was annotated with attribute((using_if_exists)) ...
Definition: DeclCXX.h:4058
static UnresolvedUsingIfExistsDecl * Create(ASTContext &Ctx, DeclContext *DC, SourceLocation Loc, DeclarationName Name)
Definition: DeclCXX.cpp:3356
Represents a dependent using declaration which was marked with typename.
Definition: DeclCXX.h:3977
SourceLocation getTypenameLoc() const
Returns the source location of the 'typename' keyword.
Definition: DeclCXX.h:4007
Represents a dependent using declaration which was not marked with typename.
Definition: DeclCXX.h:3880
Represents a C++ using-declaration.
Definition: DeclCXX.h:3530
static UsingDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation UsingL, NestedNameSpecifierLoc QualifierLoc, const DeclarationNameInfo &NameInfo, bool HasTypenameKeyword)
Definition: DeclCXX.cpp:3242
Represents C++ using-directive.
Definition: DeclCXX.h:3033
static UsingDirectiveDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation UsingLoc, SourceLocation NamespaceLoc, NestedNameSpecifierLoc QualifierLoc, SourceLocation IdentLoc, NamedDecl *Nominated, DeclContext *CommonAncestor)
Definition: DeclCXX.cpp:3029
Represents a C++ using-enum-declaration.
Definition: DeclCXX.h:3731
static UsingEnumDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation UsingL, SourceLocation EnumL, SourceLocation NameL, TypeSourceInfo *EnumType)
Definition: DeclCXX.cpp:3263
Represents a pack of using declarations that a single using-declarator pack-expanded into.
Definition: DeclCXX.h:3812
Represents a shadow declaration implicitly introduced into a scope by a (resolved) using-declaration ...
Definition: DeclCXX.h:3338
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:1102
@ 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:1274
TemplateSpecializationKind
Describes the kind of template specialization that a particular template specialization declaration r...
Definition: Specifiers.h:188
@ TSK_ExplicitInstantiationDefinition
This template specialization was instantiated from a template due to an explicit instantiation defini...
Definition: Specifiers.h:206
@ TSK_ExplicitInstantiationDeclaration
This template specialization was instantiated from a template due to an explicit instantiation declar...
Definition: Specifiers.h:202
@ TSK_ExplicitSpecialization
This template specialization was declared or defined by an explicit specialization (C++ [temp....
Definition: Specifiers.h:198
@ TSK_ImplicitInstantiation
This template specialization was implicitly instantiated from a template.
Definition: Specifiers.h:194
@ TSK_Undeclared
This template specialization was formed from a template-id but has not yet been declared,...
Definition: Specifiers.h:191
@ Enum
The "enum" keyword introduces the elaborated-type-specifier.
@ Other
Other implicit parameter.
ExceptionSpecificationType
The various types of exception specifications that exist in C++11.
@ EST_DynamicNone
throw()
@ EST_Uninstantiated
not instantiated yet
@ EST_None
no exception specification
@ EST_BasicNoexcept
noexcept
@ EST_Unevaluated
not evaluated yet, for special member function
@ AS_public
Definition: Specifiers.h:124
@ AS_none
Definition: Specifiers.h:127
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:5159
FunctionDecl * SourceDecl
The function whose exception specification this is, for EST_Unevaluated and EST_Uninstantiated.
Definition: Type.h:5171
FunctionDecl * SourceTemplate
The function template whose exception specification this is instantiated from, for EST_Uninstantiated...
Definition: Type.h:5175
ExceptionSpecificationType Type
The kind of exception specification this is.
Definition: Type.h:5161
Extra information about a function prototype.
Definition: Type.h:5187
ExceptionSpecInfo ExceptionSpec
Definition: Type.h:5194
FunctionType::ExtInfo ExtInfo
Definition: Type.h:5188
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:12653
SynthesisKind
The kind of template instantiation we are performing.
Definition: Sema.h:12655
@ BuildingDeductionGuides
We are building deduction guides for a class.
Definition: Sema.h:12760
@ DeducedTemplateArgumentSubstitution
We are substituting template argument determined as part of template argument deduction for either a ...
Definition: Sema.h:12681
bool InLifetimeExtendingContext
Whether we are currently in a context in which all temporaries must be lifetime-extended,...
Definition: Sema.h:6366
bool RebuildDefaultArgOrDefaultInit
Whether we should rebuild CXXDefaultArgExpr and CXXDefaultInitExpr.
Definition: Sema.h:6369
A stack object to be created when performing template instantiation.
Definition: Sema.h:12838
bool isInvalid() const
Determines whether we have exceeded the maximum recursive template instantiations.
Definition: Sema.h:12992
bool isAlreadyInstantiating() const
Determine whether we are already instantiating this specialization in some surrounding active instant...
Definition: Sema.h:12996