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