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