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