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