clang 22.0.0git
SemaTemplateInstantiateDecl.cpp
Go to the documentation of this file.
1//===--- SemaTemplateInstantiateDecl.cpp - C++ Template Decl Instantiation ===/
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//===----------------------------------------------------------------------===/
7//
8// This file implements C++ template instantiation for declarations.
9//
10//===----------------------------------------------------------------------===/
11
12#include "TreeTransform.h"
18#include "clang/AST/Expr.h"
19#include "clang/AST/ExprCXX.h"
21#include "clang/AST/TypeLoc.h"
26#include "clang/Sema/Lookup.h"
29#include "clang/Sema/SemaCUDA.h"
30#include "clang/Sema/SemaHLSL.h"
31#include "clang/Sema/SemaObjC.h"
34#include "clang/Sema/Template.h"
36#include "llvm/Support/TimeProfiler.h"
37#include <optional>
38
39using namespace clang;
40
41static bool isDeclWithinFunction(const Decl *D) {
42 const DeclContext *DC = D->getDeclContext();
43 if (DC->isFunctionOrMethod())
44 return true;
45
46 if (DC->isRecord())
47 return cast<CXXRecordDecl>(DC)->isLocalClass();
48
49 return false;
50}
51
52template<typename DeclT>
53static bool SubstQualifier(Sema &SemaRef, const DeclT *OldDecl, DeclT *NewDecl,
54 const MultiLevelTemplateArgumentList &TemplateArgs) {
55 if (!OldDecl->getQualifierLoc())
56 return false;
57
58 assert((NewDecl->getFriendObjectKind() ||
59 !OldDecl->getLexicalDeclContext()->isDependentContext()) &&
60 "non-friend with qualified name defined in dependent context");
61 Sema::ContextRAII SavedContext(
62 SemaRef,
63 const_cast<DeclContext *>(NewDecl->getFriendObjectKind()
64 ? NewDecl->getLexicalDeclContext()
65 : OldDecl->getLexicalDeclContext()));
66
67 NestedNameSpecifierLoc NewQualifierLoc
68 = SemaRef.SubstNestedNameSpecifierLoc(OldDecl->getQualifierLoc(),
69 TemplateArgs);
70
71 if (!NewQualifierLoc)
72 return true;
73
74 NewDecl->setQualifierInfo(NewQualifierLoc);
75 return false;
76}
77
79 DeclaratorDecl *NewDecl) {
80 return ::SubstQualifier(SemaRef, OldDecl, NewDecl, TemplateArgs);
81}
82
84 TagDecl *NewDecl) {
85 return ::SubstQualifier(SemaRef, OldDecl, NewDecl, TemplateArgs);
86}
87
88// Include attribute instantiation code.
89#include "clang/Sema/AttrTemplateInstantiate.inc"
90
92 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
93 const AlignedAttr *Aligned, Decl *New, bool IsPackExpansion) {
94 if (Aligned->isAlignmentExpr()) {
95 // The alignment expression is a constant expression.
98 ExprResult Result = S.SubstExpr(Aligned->getAlignmentExpr(), TemplateArgs);
99 if (!Result.isInvalid())
100 S.AddAlignedAttr(New, *Aligned, Result.getAs<Expr>(), IsPackExpansion);
101 } else {
102 if (TypeSourceInfo *Result =
103 S.SubstType(Aligned->getAlignmentType(), TemplateArgs,
104 Aligned->getLocation(), DeclarationName())) {
105 if (!S.CheckAlignasTypeArgument(Aligned->getSpelling(), Result,
106 Aligned->getLocation(),
107 Result->getTypeLoc().getSourceRange()))
108 S.AddAlignedAttr(New, *Aligned, Result, IsPackExpansion);
109 }
110 }
111}
112
114 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
115 const AlignedAttr *Aligned, Decl *New) {
116 if (!Aligned->isPackExpansion()) {
117 instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, false);
118 return;
119 }
120
122 if (Aligned->isAlignmentExpr())
123 S.collectUnexpandedParameterPacks(Aligned->getAlignmentExpr(),
124 Unexpanded);
125 else
126 S.collectUnexpandedParameterPacks(Aligned->getAlignmentType()->getTypeLoc(),
127 Unexpanded);
128 assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
129
130 // Determine whether we can expand this attribute pack yet.
131 bool Expand = true, RetainExpansion = false;
132 UnsignedOrNone NumExpansions = std::nullopt;
133 // FIXME: Use the actual location of the ellipsis.
134 SourceLocation EllipsisLoc = Aligned->getLocation();
135 if (S.CheckParameterPacksForExpansion(EllipsisLoc, Aligned->getRange(),
136 Unexpanded, TemplateArgs,
137 /*FailOnPackProducingTemplates=*/true,
138 Expand, RetainExpansion, NumExpansions))
139 return;
140
141 if (!Expand) {
142 Sema::ArgPackSubstIndexRAII SubstIndex(S, std::nullopt);
143 instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, true);
144 } else {
145 for (unsigned I = 0; I != *NumExpansions; ++I) {
146 Sema::ArgPackSubstIndexRAII SubstIndex(S, I);
147 instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, false);
148 }
149 }
150}
151
153 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
154 const AssumeAlignedAttr *Aligned, Decl *New) {
155 // The alignment expression is a constant expression.
158
159 Expr *E, *OE = nullptr;
160 ExprResult Result = S.SubstExpr(Aligned->getAlignment(), TemplateArgs);
161 if (Result.isInvalid())
162 return;
163 E = Result.getAs<Expr>();
164
165 if (Aligned->getOffset()) {
166 Result = S.SubstExpr(Aligned->getOffset(), TemplateArgs);
167 if (Result.isInvalid())
168 return;
169 OE = Result.getAs<Expr>();
170 }
171
172 S.AddAssumeAlignedAttr(New, *Aligned, E, OE);
173}
174
176 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
177 const AlignValueAttr *Aligned, Decl *New) {
178 // The alignment expression is a constant expression.
181 ExprResult Result = S.SubstExpr(Aligned->getAlignment(), TemplateArgs);
182 if (!Result.isInvalid())
183 S.AddAlignValueAttr(New, *Aligned, Result.getAs<Expr>());
184}
185
187 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
188 const AllocAlignAttr *Align, Decl *New) {
190 S.getASTContext(),
191 llvm::APInt(64, Align->getParamIndex().getSourceIndex()),
192 S.getASTContext().UnsignedLongLongTy, Align->getLocation());
193 S.AddAllocAlignAttr(New, *Align, Param);
194}
195
197 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
198 const AnnotateAttr *Attr, Decl *New) {
201
202 // If the attribute has delayed arguments it will have to instantiate those
203 // and handle them as new arguments for the attribute.
204 bool HasDelayedArgs = Attr->delayedArgs_size();
205
206 ArrayRef<Expr *> ArgsToInstantiate =
207 HasDelayedArgs
208 ? ArrayRef<Expr *>{Attr->delayedArgs_begin(), Attr->delayedArgs_end()}
209 : ArrayRef<Expr *>{Attr->args_begin(), Attr->args_end()};
210
212 if (S.SubstExprs(ArgsToInstantiate,
213 /*IsCall=*/false, TemplateArgs, Args))
214 return;
215
216 StringRef Str = Attr->getAnnotation();
217 if (HasDelayedArgs) {
218 if (Args.size() < 1) {
219 S.Diag(Attr->getLoc(), diag::err_attribute_too_few_arguments)
220 << Attr << 1;
221 return;
222 }
223
224 if (!S.checkStringLiteralArgumentAttr(*Attr, Args[0], Str))
225 return;
226
228 ActualArgs.insert(ActualArgs.begin(), Args.begin() + 1, Args.end());
229 std::swap(Args, ActualArgs);
230 }
231 auto *AA = S.CreateAnnotationAttr(*Attr, Str, Args);
232 if (AA) {
233 New->addAttr(AA);
234 }
235}
236
237template <typename Attr>
239 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, const Attr *A,
240 Decl *New, ASTContext &C) {
241 Expr *tempInstPriority = nullptr;
242 {
245 ExprResult Result = S.SubstExpr(A->getPriority(), TemplateArgs);
246 if (Result.isInvalid())
247 return;
248 tempInstPriority = Result.get();
249 if (std::optional<llvm::APSInt> CE =
250 tempInstPriority->getIntegerConstantExpr(C)) {
251 // Consistent with non-templated priority arguments, which must fit in a
252 // 32-bit unsigned integer.
253 if (!CE->isIntN(32)) {
254 S.Diag(tempInstPriority->getExprLoc(), diag::err_ice_too_large)
255 << toString(*CE, 10, false) << /*Size=*/32 << /*Unsigned=*/1;
256 return;
257 }
258 }
259 }
260 New->addAttr(Attr::Create(C, tempInstPriority, *A));
261}
262
264 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
265 const Attr *A, Expr *OldCond, const Decl *Tmpl, FunctionDecl *New) {
266 Expr *Cond = nullptr;
267 {
268 Sema::ContextRAII SwitchContext(S, New);
271 ExprResult Result = S.SubstExpr(OldCond, TemplateArgs);
272 if (Result.isInvalid())
273 return nullptr;
274 Cond = Result.getAs<Expr>();
275 }
276 if (!Cond->isTypeDependent()) {
278 if (Converted.isInvalid())
279 return nullptr;
280 Cond = Converted.get();
281 }
282
284 if (OldCond->isValueDependent() && !Cond->isValueDependent() &&
286 S.Diag(A->getLocation(), diag::err_attr_cond_never_constant_expr) << A;
287 for (const auto &P : Diags)
288 S.Diag(P.first, P.second);
289 return nullptr;
290 }
291 return Cond;
292}
293
295 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
296 const EnableIfAttr *EIA, const Decl *Tmpl, FunctionDecl *New) {
298 S, TemplateArgs, EIA, EIA->getCond(), Tmpl, New);
299
300 if (Cond)
301 New->addAttr(new (S.getASTContext()) EnableIfAttr(S.getASTContext(), *EIA,
302 Cond, EIA->getMessage()));
303}
304
306 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
307 const DiagnoseIfAttr *DIA, const Decl *Tmpl, FunctionDecl *New) {
309 S, TemplateArgs, DIA, DIA->getCond(), Tmpl, New);
310
311 if (Cond)
312 New->addAttr(new (S.getASTContext()) DiagnoseIfAttr(
313 S.getASTContext(), *DIA, Cond, DIA->getMessage(),
314 DIA->getDefaultSeverity(), DIA->getWarningGroup(),
315 DIA->getArgDependent(), New));
316}
317
318// Constructs and adds to New a new instance of CUDALaunchBoundsAttr using
319// template A as the base and arguments from TemplateArgs.
321 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
322 const CUDALaunchBoundsAttr &Attr, Decl *New) {
323 // The alignment expression is a constant expression.
326
327 ExprResult Result = S.SubstExpr(Attr.getMaxThreads(), TemplateArgs);
328 if (Result.isInvalid())
329 return;
330 Expr *MaxThreads = Result.getAs<Expr>();
331
332 Expr *MinBlocks = nullptr;
333 if (Attr.getMinBlocks()) {
334 Result = S.SubstExpr(Attr.getMinBlocks(), TemplateArgs);
335 if (Result.isInvalid())
336 return;
337 MinBlocks = Result.getAs<Expr>();
338 }
339
340 Expr *MaxBlocks = nullptr;
341 if (Attr.getMaxBlocks()) {
342 Result = S.SubstExpr(Attr.getMaxBlocks(), TemplateArgs);
343 if (Result.isInvalid())
344 return;
345 MaxBlocks = Result.getAs<Expr>();
346 }
347
348 S.AddLaunchBoundsAttr(New, Attr, MaxThreads, MinBlocks, MaxBlocks);
349}
350
351static void
353 const MultiLevelTemplateArgumentList &TemplateArgs,
354 const ModeAttr &Attr, Decl *New) {
355 S.AddModeAttr(New, Attr, Attr.getMode(),
356 /*InInstantiation=*/true);
357}
358
359/// Instantiation of 'declare simd' attribute and its arguments.
361 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
362 const OMPDeclareSimdDeclAttr &Attr, Decl *New) {
363 // Allow 'this' in clauses with varlist.
364 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(New))
365 New = FTD->getTemplatedDecl();
366 auto *FD = cast<FunctionDecl>(New);
367 auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(FD->getDeclContext());
368 SmallVector<Expr *, 4> Uniforms, Aligneds, Alignments, Linears, Steps;
369 SmallVector<unsigned, 4> LinModifiers;
370
371 auto SubstExpr = [&](Expr *E) -> ExprResult {
372 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
373 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
374 Sema::ContextRAII SavedContext(S, FD);
376 if (FD->getNumParams() > PVD->getFunctionScopeIndex())
377 Local.InstantiatedLocal(
378 PVD, FD->getParamDecl(PVD->getFunctionScopeIndex()));
379 return S.SubstExpr(E, TemplateArgs);
380 }
381 Sema::CXXThisScopeRAII ThisScope(S, ThisContext, Qualifiers(),
382 FD->isCXXInstanceMember());
383 return S.SubstExpr(E, TemplateArgs);
384 };
385
386 // Substitute a single OpenMP clause, which is a potentially-evaluated
387 // full-expression.
388 auto Subst = [&](Expr *E) -> ExprResult {
391 ExprResult Res = SubstExpr(E);
392 if (Res.isInvalid())
393 return Res;
394 return S.ActOnFinishFullExpr(Res.get(), false);
395 };
396
397 ExprResult Simdlen;
398 if (auto *E = Attr.getSimdlen())
399 Simdlen = Subst(E);
400
401 if (Attr.uniforms_size() > 0) {
402 for(auto *E : Attr.uniforms()) {
403 ExprResult Inst = Subst(E);
404 if (Inst.isInvalid())
405 continue;
406 Uniforms.push_back(Inst.get());
407 }
408 }
409
410 auto AI = Attr.alignments_begin();
411 for (auto *E : Attr.aligneds()) {
412 ExprResult Inst = Subst(E);
413 if (Inst.isInvalid())
414 continue;
415 Aligneds.push_back(Inst.get());
416 Inst = ExprEmpty();
417 if (*AI)
418 Inst = S.SubstExpr(*AI, TemplateArgs);
419 Alignments.push_back(Inst.get());
420 ++AI;
421 }
422
423 auto SI = Attr.steps_begin();
424 for (auto *E : Attr.linears()) {
425 ExprResult Inst = Subst(E);
426 if (Inst.isInvalid())
427 continue;
428 Linears.push_back(Inst.get());
429 Inst = ExprEmpty();
430 if (*SI)
431 Inst = S.SubstExpr(*SI, TemplateArgs);
432 Steps.push_back(Inst.get());
433 ++SI;
434 }
435 LinModifiers.append(Attr.modifiers_begin(), Attr.modifiers_end());
437 S.ConvertDeclToDeclGroup(New), Attr.getBranchState(), Simdlen.get(),
438 Uniforms, Aligneds, Alignments, Linears, LinModifiers, Steps,
439 Attr.getRange());
440}
441
442/// Instantiation of 'declare variant' attribute and its arguments.
444 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
445 const OMPDeclareVariantAttr &Attr, Decl *New) {
446 // Allow 'this' in clauses with varlist.
447 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(New))
448 New = FTD->getTemplatedDecl();
449 auto *FD = cast<FunctionDecl>(New);
450 auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(FD->getDeclContext());
451
452 auto &&SubstExpr = [FD, ThisContext, &S, &TemplateArgs](Expr *E) {
453 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
454 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
455 Sema::ContextRAII SavedContext(S, FD);
457 if (FD->getNumParams() > PVD->getFunctionScopeIndex())
458 Local.InstantiatedLocal(
459 PVD, FD->getParamDecl(PVD->getFunctionScopeIndex()));
460 return S.SubstExpr(E, TemplateArgs);
461 }
462 Sema::CXXThisScopeRAII ThisScope(S, ThisContext, Qualifiers(),
463 FD->isCXXInstanceMember());
464 return S.SubstExpr(E, TemplateArgs);
465 };
466
467 // Substitute a single OpenMP clause, which is a potentially-evaluated
468 // full-expression.
469 auto &&Subst = [&SubstExpr, &S](Expr *E) {
472 ExprResult Res = SubstExpr(E);
473 if (Res.isInvalid())
474 return Res;
475 return S.ActOnFinishFullExpr(Res.get(), false);
476 };
477
478 ExprResult VariantFuncRef;
479 if (Expr *E = Attr.getVariantFuncRef()) {
480 // Do not mark function as is used to prevent its emission if this is the
481 // only place where it is used.
484 VariantFuncRef = Subst(E);
485 }
486
487 // Copy the template version of the OMPTraitInfo and run substitute on all
488 // score and condition expressiosn.
490 TI = *Attr.getTraitInfos();
491
492 // Try to substitute template parameters in score and condition expressions.
493 auto SubstScoreOrConditionExpr = [&S, Subst](Expr *&E, bool) {
494 if (E) {
497 ExprResult ER = Subst(E);
498 if (ER.isUsable())
499 E = ER.get();
500 else
501 return true;
502 }
503 return false;
504 };
505 if (TI.anyScoreOrCondition(SubstScoreOrConditionExpr))
506 return;
507
508 Expr *E = VariantFuncRef.get();
509
510 // Check function/variant ref for `omp declare variant` but not for `omp
511 // begin declare variant` (which use implicit attributes).
512 std::optional<std::pair<FunctionDecl *, Expr *>> DeclVarData =
514 S.ConvertDeclToDeclGroup(New), E, TI, Attr.appendArgs_size(),
515 Attr.getRange());
516
517 if (!DeclVarData)
518 return;
519
520 E = DeclVarData->second;
521 FD = DeclVarData->first;
522
523 if (auto *VariantDRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts())) {
524 if (auto *VariantFD = dyn_cast<FunctionDecl>(VariantDRE->getDecl())) {
525 if (auto *VariantFTD = VariantFD->getDescribedFunctionTemplate()) {
526 if (!VariantFTD->isThisDeclarationADefinition())
527 return;
530 S.Context, TemplateArgs.getInnermost());
531
532 auto *SubstFD = S.InstantiateFunctionDeclaration(VariantFTD, TAL,
533 New->getLocation());
534 if (!SubstFD)
535 return;
537 SubstFD->getType(), FD->getType(),
538 /* OfBlockPointer */ false,
539 /* Unqualified */ false, /* AllowCXX */ true);
540 if (NewType.isNull())
541 return;
543 New->getLocation(), SubstFD, /* Recursive */ true,
544 /* DefinitionRequired */ false, /* AtEndOfTU */ false);
545 SubstFD->setInstantiationIsPending(!SubstFD->isDefined());
547 SourceLocation(), SubstFD,
548 /* RefersToEnclosingVariableOrCapture */ false,
549 /* NameLoc */ SubstFD->getLocation(),
550 SubstFD->getType(), ExprValueKind::VK_PRValue);
551 }
552 }
553 }
554
555 SmallVector<Expr *, 8> NothingExprs;
556 SmallVector<Expr *, 8> NeedDevicePtrExprs;
557 SmallVector<Expr *, 8> NeedDeviceAddrExprs;
559
560 for (Expr *E : Attr.adjustArgsNothing()) {
561 ExprResult ER = Subst(E);
562 if (ER.isInvalid())
563 continue;
564 NothingExprs.push_back(ER.get());
565 }
566 for (Expr *E : Attr.adjustArgsNeedDevicePtr()) {
567 ExprResult ER = Subst(E);
568 if (ER.isInvalid())
569 continue;
570 NeedDevicePtrExprs.push_back(ER.get());
571 }
572 for (Expr *E : Attr.adjustArgsNeedDeviceAddr()) {
573 ExprResult ER = Subst(E);
574 if (ER.isInvalid())
575 continue;
576 NeedDeviceAddrExprs.push_back(ER.get());
577 }
578 for (OMPInteropInfo &II : Attr.appendArgs()) {
579 // When prefer_type is implemented for append_args handle them here too.
580 AppendArgs.emplace_back(II.IsTarget, II.IsTargetSync);
581 }
582
584 FD, E, TI, NothingExprs, NeedDevicePtrExprs, NeedDeviceAddrExprs,
585 AppendArgs, SourceLocation(), SourceLocation(), Attr.getRange());
586}
587
589 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
590 const AMDGPUFlatWorkGroupSizeAttr &Attr, Decl *New) {
591 // Both min and max expression are constant expressions.
594
595 ExprResult Result = S.SubstExpr(Attr.getMin(), TemplateArgs);
596 if (Result.isInvalid())
597 return;
598 Expr *MinExpr = Result.getAs<Expr>();
599
600 Result = S.SubstExpr(Attr.getMax(), TemplateArgs);
601 if (Result.isInvalid())
602 return;
603 Expr *MaxExpr = Result.getAs<Expr>();
604
605 S.AMDGPU().addAMDGPUFlatWorkGroupSizeAttr(New, Attr, MinExpr, MaxExpr);
606}
607
609 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
610 const ReqdWorkGroupSizeAttr &Attr, Decl *New) {
611 // Both min and max expression are constant expressions.
614
615 ExprResult Result = S.SubstExpr(Attr.getXDim(), TemplateArgs);
616 if (Result.isInvalid())
617 return;
618 Expr *X = Result.getAs<Expr>();
619
620 Result = S.SubstExpr(Attr.getYDim(), TemplateArgs);
621 if (Result.isInvalid())
622 return;
623 Expr *Y = Result.getAs<Expr>();
624
625 Result = S.SubstExpr(Attr.getZDim(), TemplateArgs);
626 if (Result.isInvalid())
627 return;
628 Expr *Z = Result.getAs<Expr>();
629
630 ASTContext &Context = S.getASTContext();
631 New->addAttr(::new (Context) ReqdWorkGroupSizeAttr(Context, Attr, X, Y, Z));
632}
633
635 const MultiLevelTemplateArgumentList &TemplateArgs, ExplicitSpecifier ES) {
636 if (!ES.getExpr())
637 return ES;
638 Expr *OldCond = ES.getExpr();
639 Expr *Cond = nullptr;
640 {
643 ExprResult SubstResult = SubstExpr(OldCond, TemplateArgs);
644 if (SubstResult.isInvalid()) {
646 }
647 Cond = SubstResult.get();
648 }
650 if (!Cond->isTypeDependent())
652 return Result;
653}
654
656 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
657 const AMDGPUWavesPerEUAttr &Attr, Decl *New) {
658 // Both min and max expression are constant expressions.
661
662 ExprResult Result = S.SubstExpr(Attr.getMin(), TemplateArgs);
663 if (Result.isInvalid())
664 return;
665 Expr *MinExpr = Result.getAs<Expr>();
666
667 Expr *MaxExpr = nullptr;
668 if (auto Max = Attr.getMax()) {
669 Result = S.SubstExpr(Max, TemplateArgs);
670 if (Result.isInvalid())
671 return;
672 MaxExpr = Result.getAs<Expr>();
673 }
674
675 S.AMDGPU().addAMDGPUWavesPerEUAttr(New, Attr, MinExpr, MaxExpr);
676}
677
679 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
680 const AMDGPUMaxNumWorkGroupsAttr &Attr, Decl *New) {
683
684 Expr *XExpr = nullptr;
685 Expr *YExpr = nullptr;
686 Expr *ZExpr = nullptr;
687
688 if (Attr.getMaxNumWorkGroupsX()) {
689 ExprResult ResultX = S.SubstExpr(Attr.getMaxNumWorkGroupsX(), TemplateArgs);
690 if (ResultX.isUsable())
691 XExpr = ResultX.getAs<Expr>();
692 }
693
694 if (Attr.getMaxNumWorkGroupsY()) {
695 ExprResult ResultY = S.SubstExpr(Attr.getMaxNumWorkGroupsY(), TemplateArgs);
696 if (ResultY.isUsable())
697 YExpr = ResultY.getAs<Expr>();
698 }
699
700 if (Attr.getMaxNumWorkGroupsZ()) {
701 ExprResult ResultZ = S.SubstExpr(Attr.getMaxNumWorkGroupsZ(), TemplateArgs);
702 if (ResultZ.isUsable())
703 ZExpr = ResultZ.getAs<Expr>();
704 }
705
706 if (XExpr)
707 S.AMDGPU().addAMDGPUMaxNumWorkGroupsAttr(New, Attr, XExpr, YExpr, ZExpr);
708}
709
711 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
712 const CUDAClusterDimsAttr &Attr, Decl *New) {
715
716 auto SubstElt = [&S, &TemplateArgs](Expr *E) {
717 return E ? S.SubstExpr(E, TemplateArgs).get() : nullptr;
718 };
719
720 Expr *XExpr = SubstElt(Attr.getX());
721 Expr *YExpr = SubstElt(Attr.getY());
722 Expr *ZExpr = SubstElt(Attr.getZ());
723
724 S.addClusterDimsAttr(New, Attr, XExpr, YExpr, ZExpr);
725}
726
727// This doesn't take any template parameters, but we have a custom action that
728// needs to happen when the kernel itself is instantiated. We need to run the
729// ItaniumMangler to mark the names required to name this kernel.
731 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
732 const SYCLKernelAttr &Attr, Decl *New) {
733 New->addAttr(Attr.clone(S.getASTContext()));
734}
735
736/// Determine whether the attribute A might be relevant to the declaration D.
737/// If not, we can skip instantiating it. The attribute may or may not have
738/// been instantiated yet.
739static bool isRelevantAttr(Sema &S, const Decl *D, const Attr *A) {
740 // 'preferred_name' is only relevant to the matching specialization of the
741 // template.
742 if (const auto *PNA = dyn_cast<PreferredNameAttr>(A)) {
743 QualType T = PNA->getTypedefType();
744 const auto *RD = cast<CXXRecordDecl>(D);
745 if (!T->isDependentType() && !RD->isDependentContext() &&
746 !declaresSameEntity(T->getAsCXXRecordDecl(), RD))
747 return false;
748 for (const auto *ExistingPNA : D->specific_attrs<PreferredNameAttr>())
749 if (S.Context.hasSameType(ExistingPNA->getTypedefType(),
750 PNA->getTypedefType()))
751 return false;
752 return true;
753 }
754
755 if (const auto *BA = dyn_cast<BuiltinAttr>(A)) {
756 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
757 switch (BA->getID()) {
758 case Builtin::BIforward:
759 // Do not treat 'std::forward' as a builtin if it takes an rvalue reference
760 // type and returns an lvalue reference type. The library implementation
761 // will produce an error in this case; don't get in its way.
762 if (FD && FD->getNumParams() >= 1 &&
765 return false;
766 }
767 [[fallthrough]];
768 case Builtin::BImove:
769 case Builtin::BImove_if_noexcept:
770 // HACK: Super-old versions of libc++ (3.1 and earlier) provide
771 // std::forward and std::move overloads that sometimes return by value
772 // instead of by reference when building in C++98 mode. Don't treat such
773 // cases as builtins.
774 if (FD && !FD->getReturnType()->isReferenceType())
775 return false;
776 break;
777 }
778 }
779
780 return true;
781}
782
784 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
785 const HLSLParamModifierAttr *Attr, const Decl *Old, Decl *New) {
787 NewParm->addAttr(Attr->clone(S.getASTContext()));
788
789 const Type *OldParmTy = cast<ParmVarDecl>(Old)->getType().getTypePtr();
790 if (OldParmTy->isDependentType() && Attr->isAnyOut())
791 NewParm->setType(S.HLSL().getInoutParameterType(NewParm->getType()));
792
793 assert(
794 (!Attr->isAnyOut() || (NewParm->getType().isRestrictQualified() &&
795 NewParm->getType()->isReferenceType())) &&
796 "out or inout parameter type must be a reference and restrict qualified");
797}
798
800 const MultiLevelTemplateArgumentList &TemplateArgs, const Decl *Tmpl,
801 Decl *New, LateInstantiatedAttrVec *LateAttrs,
802 LocalInstantiationScope *OuterMostScope) {
803 if (NamedDecl *ND = dyn_cast<NamedDecl>(New)) {
804 // FIXME: This function is called multiple times for the same template
805 // specialization. We should only instantiate attributes that were added
806 // since the previous instantiation.
807 for (const auto *TmplAttr : Tmpl->attrs()) {
808 if (!isRelevantAttr(*this, New, TmplAttr))
809 continue;
810
811 // FIXME: If any of the special case versions from InstantiateAttrs become
812 // applicable to template declaration, we'll need to add them here.
813 CXXThisScopeRAII ThisScope(
814 *this, dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext()),
815 Qualifiers(), ND->isCXXInstanceMember());
816
818 TmplAttr, Context, *this, TemplateArgs);
819 if (NewAttr && isRelevantAttr(*this, New, NewAttr))
820 New->addAttr(NewAttr);
821 }
822 }
823}
824
827 switch (A->getKind()) {
828 case clang::attr::CFConsumed:
830 case clang::attr::OSConsumed:
832 case clang::attr::NSConsumed:
834 default:
835 llvm_unreachable("Wrong argument supplied");
836 }
837}
838
839// Implementation is down with the rest of the OpenACC Decl instantiations.
841 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
842 const OpenACCRoutineDeclAttr *OldAttr, const Decl *Old, Decl *New);
843
845 const Decl *Tmpl, Decl *New,
846 LateInstantiatedAttrVec *LateAttrs,
847 LocalInstantiationScope *OuterMostScope) {
848 for (const auto *TmplAttr : Tmpl->attrs()) {
849 if (!isRelevantAttr(*this, New, TmplAttr))
850 continue;
851
852 // FIXME: This should be generalized to more than just the AlignedAttr.
853 const AlignedAttr *Aligned = dyn_cast<AlignedAttr>(TmplAttr);
854 if (Aligned && Aligned->isAlignmentDependent()) {
855 instantiateDependentAlignedAttr(*this, TemplateArgs, Aligned, New);
856 continue;
857 }
858
859 if (const auto *AssumeAligned = dyn_cast<AssumeAlignedAttr>(TmplAttr)) {
860 instantiateDependentAssumeAlignedAttr(*this, TemplateArgs, AssumeAligned, New);
861 continue;
862 }
863
864 if (const auto *AlignValue = dyn_cast<AlignValueAttr>(TmplAttr)) {
865 instantiateDependentAlignValueAttr(*this, TemplateArgs, AlignValue, New);
866 continue;
867 }
868
869 if (const auto *AllocAlign = dyn_cast<AllocAlignAttr>(TmplAttr)) {
870 instantiateDependentAllocAlignAttr(*this, TemplateArgs, AllocAlign, New);
871 continue;
872 }
873
874 if (const auto *Annotate = dyn_cast<AnnotateAttr>(TmplAttr)) {
875 instantiateDependentAnnotationAttr(*this, TemplateArgs, Annotate, New);
876 continue;
877 }
878
879 if (auto *Constructor = dyn_cast<ConstructorAttr>(TmplAttr)) {
882 continue;
883 }
884
885 if (auto *Destructor = dyn_cast<DestructorAttr>(TmplAttr)) {
888 continue;
889 }
890
891 if (const auto *EnableIf = dyn_cast<EnableIfAttr>(TmplAttr)) {
892 instantiateDependentEnableIfAttr(*this, TemplateArgs, EnableIf, Tmpl,
894 continue;
895 }
896
897 if (const auto *DiagnoseIf = dyn_cast<DiagnoseIfAttr>(TmplAttr)) {
898 instantiateDependentDiagnoseIfAttr(*this, TemplateArgs, DiagnoseIf, Tmpl,
900 continue;
901 }
902
903 if (const auto *CUDALaunchBounds =
904 dyn_cast<CUDALaunchBoundsAttr>(TmplAttr)) {
906 *CUDALaunchBounds, New);
907 continue;
908 }
909
910 if (const auto *Mode = dyn_cast<ModeAttr>(TmplAttr)) {
911 instantiateDependentModeAttr(*this, TemplateArgs, *Mode, New);
912 continue;
913 }
914
915 if (const auto *OMPAttr = dyn_cast<OMPDeclareSimdDeclAttr>(TmplAttr)) {
916 instantiateOMPDeclareSimdDeclAttr(*this, TemplateArgs, *OMPAttr, New);
917 continue;
918 }
919
920 if (const auto *OMPAttr = dyn_cast<OMPDeclareVariantAttr>(TmplAttr)) {
921 instantiateOMPDeclareVariantAttr(*this, TemplateArgs, *OMPAttr, New);
922 continue;
923 }
924
925 if (const auto *ReqdWorkGroupSize =
926 dyn_cast<ReqdWorkGroupSizeAttr>(TmplAttr)) {
928 *ReqdWorkGroupSize, New);
929 }
930
931 if (const auto *AMDGPUFlatWorkGroupSize =
932 dyn_cast<AMDGPUFlatWorkGroupSizeAttr>(TmplAttr)) {
934 *this, TemplateArgs, *AMDGPUFlatWorkGroupSize, New);
935 }
936
937 if (const auto *AMDGPUFlatWorkGroupSize =
938 dyn_cast<AMDGPUWavesPerEUAttr>(TmplAttr)) {
940 *AMDGPUFlatWorkGroupSize, New);
941 }
942
943 if (const auto *AMDGPUMaxNumWorkGroups =
944 dyn_cast<AMDGPUMaxNumWorkGroupsAttr>(TmplAttr)) {
946 *this, TemplateArgs, *AMDGPUMaxNumWorkGroups, New);
947 }
948
949 if (const auto *CUDAClusterDims = dyn_cast<CUDAClusterDimsAttr>(TmplAttr)) {
950 instantiateDependentCUDAClusterDimsAttr(*this, TemplateArgs,
951 *CUDAClusterDims, New);
952 }
953
954 if (const auto *ParamAttr = dyn_cast<HLSLParamModifierAttr>(TmplAttr)) {
955 instantiateDependentHLSLParamModifierAttr(*this, TemplateArgs, ParamAttr,
956 Tmpl, New);
957 continue;
958 }
959
960 if (const auto *RoutineAttr = dyn_cast<OpenACCRoutineDeclAttr>(TmplAttr)) {
962 RoutineAttr, Tmpl, New);
963 continue;
964 }
965
966 // Existing DLL attribute on the instantiation takes precedence.
967 if (TmplAttr->getKind() == attr::DLLExport ||
968 TmplAttr->getKind() == attr::DLLImport) {
969 if (New->hasAttr<DLLExportAttr>() || New->hasAttr<DLLImportAttr>()) {
970 continue;
971 }
972 }
973
974 if (const auto *ABIAttr = dyn_cast<ParameterABIAttr>(TmplAttr)) {
975 Swift().AddParameterABIAttr(New, *ABIAttr, ABIAttr->getABI());
976 continue;
977 }
978
979 if (isa<NSConsumedAttr>(TmplAttr) || isa<OSConsumedAttr>(TmplAttr) ||
980 isa<CFConsumedAttr>(TmplAttr)) {
981 ObjC().AddXConsumedAttr(New, *TmplAttr,
983 /*template instantiation=*/true);
984 continue;
985 }
986
987 if (auto *A = dyn_cast<PointerAttr>(TmplAttr)) {
988 if (!New->hasAttr<PointerAttr>())
989 New->addAttr(A->clone(Context));
990 continue;
991 }
992
993 if (auto *A = dyn_cast<OwnerAttr>(TmplAttr)) {
994 if (!New->hasAttr<OwnerAttr>())
995 New->addAttr(A->clone(Context));
996 continue;
997 }
998
999 if (auto *A = dyn_cast<SYCLKernelAttr>(TmplAttr)) {
1000 instantiateDependentSYCLKernelAttr(*this, TemplateArgs, *A, New);
1001 continue;
1002 }
1003
1004 if (auto *A = dyn_cast<CUDAGridConstantAttr>(TmplAttr)) {
1005 if (!New->hasAttr<CUDAGridConstantAttr>())
1006 New->addAttr(A->clone(Context));
1007 continue;
1008 }
1009
1010 assert(!TmplAttr->isPackExpansion());
1011 if (TmplAttr->isLateParsed() && LateAttrs) {
1012 // Late parsed attributes must be instantiated and attached after the
1013 // enclosing class has been instantiated. See Sema::InstantiateClass.
1014 LocalInstantiationScope *Saved = nullptr;
1016 Saved = CurrentInstantiationScope->cloneScopes(OuterMostScope);
1017 LateAttrs->push_back(LateInstantiatedAttribute(TmplAttr, Saved, New));
1018 } else {
1019 // Allow 'this' within late-parsed attributes.
1020 auto *ND = cast<NamedDecl>(New);
1021 auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext());
1022 CXXThisScopeRAII ThisScope(*this, ThisContext, Qualifiers(),
1023 ND->isCXXInstanceMember());
1024
1025 Attr *NewAttr = sema::instantiateTemplateAttribute(TmplAttr, Context,
1026 *this, TemplateArgs);
1027 if (NewAttr && isRelevantAttr(*this, New, TmplAttr))
1028 New->addAttr(NewAttr);
1029 }
1030 }
1031}
1032
1034 for (const auto *Attr : Pattern->attrs()) {
1035 if (auto *A = dyn_cast<StrictFPAttr>(Attr)) {
1036 if (!Inst->hasAttr<StrictFPAttr>())
1037 Inst->addAttr(A->clone(getASTContext()));
1038 continue;
1039 }
1040 }
1041}
1042
1044 assert(Context.getTargetInfo().getCXXABI().isMicrosoft() &&
1045 Ctor->isDefaultConstructor());
1046 unsigned NumParams = Ctor->getNumParams();
1047 if (NumParams == 0)
1048 return;
1049 DLLExportAttr *Attr = Ctor->getAttr<DLLExportAttr>();
1050 if (!Attr)
1051 return;
1052 for (unsigned I = 0; I != NumParams; ++I) {
1054 Ctor->getParamDecl(I));
1056 }
1057}
1058
1059/// Get the previous declaration of a declaration for the purposes of template
1060/// instantiation. If this finds a previous declaration, then the previous
1061/// declaration of the instantiation of D should be an instantiation of the
1062/// result of this function.
1063template<typename DeclT>
1064static DeclT *getPreviousDeclForInstantiation(DeclT *D) {
1065 DeclT *Result = D->getPreviousDecl();
1066
1067 // If the declaration is within a class, and the previous declaration was
1068 // merged from a different definition of that class, then we don't have a
1069 // previous declaration for the purpose of template instantiation.
1070 if (Result && isa<CXXRecordDecl>(D->getDeclContext()) &&
1071 D->getLexicalDeclContext() != Result->getLexicalDeclContext())
1072 return nullptr;
1073
1074 return Result;
1075}
1076
1077Decl *
1078TemplateDeclInstantiator::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
1079 llvm_unreachable("Translation units cannot be instantiated");
1080}
1081
1082Decl *TemplateDeclInstantiator::VisitHLSLBufferDecl(HLSLBufferDecl *Decl) {
1083 llvm_unreachable("HLSL buffer declarations cannot be instantiated");
1084}
1085
1086Decl *TemplateDeclInstantiator::VisitHLSLRootSignatureDecl(
1088 llvm_unreachable("HLSL root signature declarations cannot be instantiated");
1089}
1090
1091Decl *
1092TemplateDeclInstantiator::VisitPragmaCommentDecl(PragmaCommentDecl *D) {
1093 llvm_unreachable("pragma comment cannot be instantiated");
1094}
1095
1096Decl *TemplateDeclInstantiator::VisitPragmaDetectMismatchDecl(
1098 llvm_unreachable("pragma comment cannot be instantiated");
1099}
1100
1101Decl *
1102TemplateDeclInstantiator::VisitExternCContextDecl(ExternCContextDecl *D) {
1103 llvm_unreachable("extern \"C\" context cannot be instantiated");
1104}
1105
1106Decl *TemplateDeclInstantiator::VisitMSGuidDecl(MSGuidDecl *D) {
1107 llvm_unreachable("GUID declaration cannot be instantiated");
1108}
1109
1110Decl *TemplateDeclInstantiator::VisitUnnamedGlobalConstantDecl(
1112 llvm_unreachable("UnnamedGlobalConstantDecl cannot be instantiated");
1113}
1114
1115Decl *TemplateDeclInstantiator::VisitTemplateParamObjectDecl(
1117 llvm_unreachable("template parameter objects cannot be instantiated");
1118}
1119
1120Decl *
1121TemplateDeclInstantiator::VisitLabelDecl(LabelDecl *D) {
1122 LabelDecl *Inst = LabelDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1123 D->getIdentifier());
1124 SemaRef.InstantiateAttrs(TemplateArgs, D, Inst, LateAttrs, StartingScope);
1125 Owner->addDecl(Inst);
1126 return Inst;
1127}
1128
1129Decl *
1130TemplateDeclInstantiator::VisitNamespaceDecl(NamespaceDecl *D) {
1131 llvm_unreachable("Namespaces cannot be instantiated");
1132}
1133
1134namespace {
1135class OpenACCDeclClauseInstantiator final
1136 : public OpenACCClauseVisitor<OpenACCDeclClauseInstantiator> {
1137 Sema &SemaRef;
1138 const MultiLevelTemplateArgumentList &MLTAL;
1139 ArrayRef<OpenACCClause *> ExistingClauses;
1140 SemaOpenACC::OpenACCParsedClause &ParsedClause;
1141 OpenACCClause *NewClause = nullptr;
1142
1143public:
1144 OpenACCDeclClauseInstantiator(Sema &S,
1145 const MultiLevelTemplateArgumentList &MLTAL,
1146 ArrayRef<OpenACCClause *> ExistingClauses,
1147 SemaOpenACC::OpenACCParsedClause &ParsedClause)
1148 : SemaRef(S), MLTAL(MLTAL), ExistingClauses(ExistingClauses),
1149 ParsedClause(ParsedClause) {}
1150
1151 OpenACCClause *CreatedClause() { return NewClause; }
1152#define VISIT_CLAUSE(CLAUSE_NAME) \
1153 void Visit##CLAUSE_NAME##Clause(const OpenACC##CLAUSE_NAME##Clause &Clause);
1154#include "clang/Basic/OpenACCClauses.def"
1155
1156 llvm::SmallVector<Expr *> VisitVarList(ArrayRef<Expr *> VarList) {
1157 llvm::SmallVector<Expr *> InstantiatedVarList;
1158 for (Expr *CurVar : VarList) {
1159 ExprResult Res = SemaRef.SubstExpr(CurVar, MLTAL);
1160
1161 if (!Res.isUsable())
1162 continue;
1163
1164 Res = SemaRef.OpenACC().ActOnVar(ParsedClause.getDirectiveKind(),
1165 ParsedClause.getClauseKind(), Res.get());
1166
1167 if (Res.isUsable())
1168 InstantiatedVarList.push_back(Res.get());
1169 }
1170 return InstantiatedVarList;
1171 }
1172};
1173
1174#define CLAUSE_NOT_ON_DECLS(CLAUSE_NAME) \
1175 void OpenACCDeclClauseInstantiator::Visit##CLAUSE_NAME##Clause( \
1176 const OpenACC##CLAUSE_NAME##Clause &) { \
1177 llvm_unreachable("Clause type invalid on declaration construct, or " \
1178 "instantiation not implemented"); \
1179 }
1180
1200CLAUSE_NOT_ON_DECLS(Private)
1207#undef CLAUSE_NOT_ON_DECLS
1208
1209void OpenACCDeclClauseInstantiator::VisitGangClause(
1210 const OpenACCGangClause &C) {
1211 llvm::SmallVector<OpenACCGangKind> TransformedGangKinds;
1212 llvm::SmallVector<Expr *> TransformedIntExprs;
1213 assert(C.getNumExprs() <= 1 &&
1214 "Only 1 expression allowed on gang clause in routine");
1215
1216 if (C.getNumExprs() > 0) {
1217 assert(C.getExpr(0).first == OpenACCGangKind::Dim &&
1218 "Only dim allowed on routine");
1219 ExprResult ER =
1220 SemaRef.SubstExpr(const_cast<Expr *>(C.getExpr(0).second), MLTAL);
1221 if (ER.isUsable()) {
1222 ER = SemaRef.OpenACC().CheckGangExpr(ExistingClauses,
1223 ParsedClause.getDirectiveKind(),
1224 C.getExpr(0).first, ER.get());
1225 if (ER.isUsable()) {
1226 TransformedGangKinds.push_back(OpenACCGangKind::Dim);
1227 TransformedIntExprs.push_back(ER.get());
1228 }
1229 }
1230 }
1231
1232 NewClause = SemaRef.OpenACC().CheckGangClause(
1233 ParsedClause.getDirectiveKind(), ExistingClauses,
1234 ParsedClause.getBeginLoc(), ParsedClause.getLParenLoc(),
1235 TransformedGangKinds, TransformedIntExprs, ParsedClause.getEndLoc());
1236}
1237
1238void OpenACCDeclClauseInstantiator::VisitSeqClause(const OpenACCSeqClause &C) {
1239 NewClause = OpenACCSeqClause::Create(SemaRef.getASTContext(),
1240 ParsedClause.getBeginLoc(),
1241 ParsedClause.getEndLoc());
1242}
1243void OpenACCDeclClauseInstantiator::VisitNoHostClause(
1244 const OpenACCNoHostClause &C) {
1245 NewClause = OpenACCNoHostClause::Create(SemaRef.getASTContext(),
1246 ParsedClause.getBeginLoc(),
1247 ParsedClause.getEndLoc());
1248}
1249
1250void OpenACCDeclClauseInstantiator::VisitDeviceTypeClause(
1251 const OpenACCDeviceTypeClause &C) {
1252 // Nothing to transform here, just create a new version of 'C'.
1254 SemaRef.getASTContext(), C.getClauseKind(), ParsedClause.getBeginLoc(),
1255 ParsedClause.getLParenLoc(), C.getArchitectures(),
1256 ParsedClause.getEndLoc());
1257}
1258
1259void OpenACCDeclClauseInstantiator::VisitWorkerClause(
1260 const OpenACCWorkerClause &C) {
1261 assert(!C.hasIntExpr() && "Int Expr not allowed on routine 'worker' clause");
1262 NewClause = OpenACCWorkerClause::Create(SemaRef.getASTContext(),
1263 ParsedClause.getBeginLoc(), {},
1264 nullptr, ParsedClause.getEndLoc());
1265}
1266
1267void OpenACCDeclClauseInstantiator::VisitVectorClause(
1268 const OpenACCVectorClause &C) {
1269 assert(!C.hasIntExpr() && "Int Expr not allowed on routine 'vector' clause");
1270 NewClause = OpenACCVectorClause::Create(SemaRef.getASTContext(),
1271 ParsedClause.getBeginLoc(), {},
1272 nullptr, ParsedClause.getEndLoc());
1273}
1274
1275void OpenACCDeclClauseInstantiator::VisitCopyClause(
1276 const OpenACCCopyClause &C) {
1277 ParsedClause.setVarListDetails(VisitVarList(C.getVarList()),
1278 C.getModifierList());
1279 if (SemaRef.OpenACC().CheckDeclareClause(ParsedClause, C.getModifierList()))
1280 return;
1281 NewClause = OpenACCCopyClause::Create(
1282 SemaRef.getASTContext(), ParsedClause.getClauseKind(),
1283 ParsedClause.getBeginLoc(), ParsedClause.getLParenLoc(),
1284 ParsedClause.getModifierList(), ParsedClause.getVarList(),
1285 ParsedClause.getEndLoc());
1286}
1287
1288void OpenACCDeclClauseInstantiator::VisitLinkClause(
1289 const OpenACCLinkClause &C) {
1290 ParsedClause.setVarListDetails(
1291 SemaRef.OpenACC().CheckLinkClauseVarList(VisitVarList(C.getVarList())),
1293
1294 if (SemaRef.OpenACC().CheckDeclareClause(ParsedClause,
1296 return;
1297
1298 NewClause = OpenACCLinkClause::Create(
1299 SemaRef.getASTContext(), ParsedClause.getBeginLoc(),
1300 ParsedClause.getLParenLoc(), ParsedClause.getVarList(),
1301 ParsedClause.getEndLoc());
1302}
1303
1304void OpenACCDeclClauseInstantiator::VisitDeviceResidentClause(
1306 ParsedClause.setVarListDetails(VisitVarList(C.getVarList()),
1308 if (SemaRef.OpenACC().CheckDeclareClause(ParsedClause,
1310 return;
1312 SemaRef.getASTContext(), ParsedClause.getBeginLoc(),
1313 ParsedClause.getLParenLoc(), ParsedClause.getVarList(),
1314 ParsedClause.getEndLoc());
1315}
1316
1317void OpenACCDeclClauseInstantiator::VisitCopyInClause(
1318 const OpenACCCopyInClause &C) {
1319 ParsedClause.setVarListDetails(VisitVarList(C.getVarList()),
1320 C.getModifierList());
1321
1322 if (SemaRef.OpenACC().CheckDeclareClause(ParsedClause, C.getModifierList()))
1323 return;
1324 NewClause = OpenACCCopyInClause::Create(
1325 SemaRef.getASTContext(), ParsedClause.getClauseKind(),
1326 ParsedClause.getBeginLoc(), ParsedClause.getLParenLoc(),
1327 ParsedClause.getModifierList(), ParsedClause.getVarList(),
1328 ParsedClause.getEndLoc());
1329}
1330void OpenACCDeclClauseInstantiator::VisitCopyOutClause(
1331 const OpenACCCopyOutClause &C) {
1332 ParsedClause.setVarListDetails(VisitVarList(C.getVarList()),
1333 C.getModifierList());
1334
1335 if (SemaRef.OpenACC().CheckDeclareClause(ParsedClause, C.getModifierList()))
1336 return;
1337 NewClause = OpenACCCopyOutClause::Create(
1338 SemaRef.getASTContext(), ParsedClause.getClauseKind(),
1339 ParsedClause.getBeginLoc(), ParsedClause.getLParenLoc(),
1340 ParsedClause.getModifierList(), ParsedClause.getVarList(),
1341 ParsedClause.getEndLoc());
1342}
1343void OpenACCDeclClauseInstantiator::VisitCreateClause(
1344 const OpenACCCreateClause &C) {
1345 ParsedClause.setVarListDetails(VisitVarList(C.getVarList()),
1346 C.getModifierList());
1347
1348 if (SemaRef.OpenACC().CheckDeclareClause(ParsedClause, C.getModifierList()))
1349 return;
1350 NewClause = OpenACCCreateClause::Create(
1351 SemaRef.getASTContext(), ParsedClause.getClauseKind(),
1352 ParsedClause.getBeginLoc(), ParsedClause.getLParenLoc(),
1353 ParsedClause.getModifierList(), ParsedClause.getVarList(),
1354 ParsedClause.getEndLoc());
1355}
1356void OpenACCDeclClauseInstantiator::VisitPresentClause(
1357 const OpenACCPresentClause &C) {
1358 ParsedClause.setVarListDetails(VisitVarList(C.getVarList()),
1360 if (SemaRef.OpenACC().CheckDeclareClause(ParsedClause,
1362 return;
1363 NewClause = OpenACCPresentClause::Create(
1364 SemaRef.getASTContext(), ParsedClause.getBeginLoc(),
1365 ParsedClause.getLParenLoc(), ParsedClause.getVarList(),
1366 ParsedClause.getEndLoc());
1367}
1368void OpenACCDeclClauseInstantiator::VisitDevicePtrClause(
1369 const OpenACCDevicePtrClause &C) {
1370 llvm::SmallVector<Expr *> VarList = VisitVarList(C.getVarList());
1371 // Ensure each var is a pointer type.
1372 llvm::erase_if(VarList, [&](Expr *E) {
1373 return SemaRef.OpenACC().CheckVarIsPointerType(OpenACCClauseKind::DevicePtr,
1374 E);
1375 });
1376 ParsedClause.setVarListDetails(VarList, OpenACCModifierKind::Invalid);
1377 if (SemaRef.OpenACC().CheckDeclareClause(ParsedClause,
1379 return;
1381 SemaRef.getASTContext(), ParsedClause.getBeginLoc(),
1382 ParsedClause.getLParenLoc(), ParsedClause.getVarList(),
1383 ParsedClause.getEndLoc());
1384}
1385
1386void OpenACCDeclClauseInstantiator::VisitBindClause(
1387 const OpenACCBindClause &C) {
1388 // Nothing to instantiate, we support only string literal or identifier.
1389 if (C.isStringArgument())
1390 NewClause = OpenACCBindClause::Create(
1391 SemaRef.getASTContext(), ParsedClause.getBeginLoc(),
1392 ParsedClause.getLParenLoc(), C.getStringArgument(),
1393 ParsedClause.getEndLoc());
1394 else
1395 NewClause = OpenACCBindClause::Create(
1396 SemaRef.getASTContext(), ParsedClause.getBeginLoc(),
1397 ParsedClause.getLParenLoc(), C.getIdentifierArgument(),
1398 ParsedClause.getEndLoc());
1399}
1400
1401llvm::SmallVector<OpenACCClause *> InstantiateOpenACCClauseList(
1402 Sema &S, const MultiLevelTemplateArgumentList &MLTAL,
1404 llvm::SmallVector<OpenACCClause *> TransformedClauses;
1405
1406 for (const auto *Clause : ClauseList) {
1407 SemaOpenACC::OpenACCParsedClause ParsedClause(DK, Clause->getClauseKind(),
1408 Clause->getBeginLoc());
1409 ParsedClause.setEndLoc(Clause->getEndLoc());
1410 if (const auto *WithParms = dyn_cast<OpenACCClauseWithParams>(Clause))
1411 ParsedClause.setLParenLoc(WithParms->getLParenLoc());
1412
1413 OpenACCDeclClauseInstantiator Instantiator{S, MLTAL, TransformedClauses,
1414 ParsedClause};
1415 Instantiator.Visit(Clause);
1416 if (Instantiator.CreatedClause())
1417 TransformedClauses.push_back(Instantiator.CreatedClause());
1418 }
1419 return TransformedClauses;
1420}
1421
1422} // namespace
1423
1425 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
1426 const OpenACCRoutineDeclAttr *OldAttr, const Decl *OldDecl, Decl *NewDecl) {
1427 OpenACCRoutineDeclAttr *A =
1428 OpenACCRoutineDeclAttr::Create(S.getASTContext(), OldAttr->getLocation());
1429
1430 if (!OldAttr->Clauses.empty()) {
1431 llvm::SmallVector<OpenACCClause *> TransformedClauses =
1432 InstantiateOpenACCClauseList(
1433 S, TemplateArgs, OpenACCDirectiveKind::Routine, OldAttr->Clauses);
1434 A->Clauses.assign(TransformedClauses.begin(), TransformedClauses.end());
1435 }
1436
1437 // We don't end up having to do any magic-static or bind checking here, since
1438 // the first phase should have caught this, since we always apply to the
1439 // functiondecl.
1440 NewDecl->addAttr(A);
1441}
1442
1443Decl *TemplateDeclInstantiator::VisitOpenACCDeclareDecl(OpenACCDeclareDecl *D) {
1444 SemaRef.OpenACC().ActOnConstruct(D->getDirectiveKind(), D->getBeginLoc());
1445 llvm::SmallVector<OpenACCClause *> TransformedClauses =
1446 InstantiateOpenACCClauseList(SemaRef, TemplateArgs, D->getDirectiveKind(),
1447 D->clauses());
1448
1449 if (SemaRef.OpenACC().ActOnStartDeclDirective(
1450 D->getDirectiveKind(), D->getBeginLoc(), TransformedClauses))
1451 return nullptr;
1452
1453 DeclGroupRef Res = SemaRef.OpenACC().ActOnEndDeclDirective(
1454 D->getDirectiveKind(), D->getBeginLoc(), D->getDirectiveLoc(), {}, {},
1455 D->getEndLoc(), TransformedClauses);
1456
1457 if (Res.isNull())
1458 return nullptr;
1459
1460 return Res.getSingleDecl();
1461}
1462
1463Decl *TemplateDeclInstantiator::VisitOpenACCRoutineDecl(OpenACCRoutineDecl *D) {
1464 SemaRef.OpenACC().ActOnConstruct(D->getDirectiveKind(), D->getBeginLoc());
1465 llvm::SmallVector<OpenACCClause *> TransformedClauses =
1466 InstantiateOpenACCClauseList(SemaRef, TemplateArgs, D->getDirectiveKind(),
1467 D->clauses());
1468
1469 ExprResult FuncRef;
1470 if (D->getFunctionReference()) {
1471 FuncRef = SemaRef.SubstCXXIdExpr(D->getFunctionReference(), TemplateArgs);
1472 if (FuncRef.isUsable())
1473 FuncRef = SemaRef.OpenACC().ActOnRoutineName(FuncRef.get());
1474 // We don't return early here, we leave the construct in the AST, even if
1475 // the function decl is empty.
1476 }
1477
1478 if (SemaRef.OpenACC().ActOnStartDeclDirective(
1479 D->getDirectiveKind(), D->getBeginLoc(), TransformedClauses))
1480 return nullptr;
1481
1482 DeclGroupRef Res = SemaRef.OpenACC().ActOnEndRoutineDeclDirective(
1483 D->getBeginLoc(), D->getDirectiveLoc(), D->getLParenLoc(), FuncRef.get(),
1484 D->getRParenLoc(), TransformedClauses, D->getEndLoc(), nullptr);
1485
1486 if (Res.isNull())
1487 return nullptr;
1488
1489 return Res.getSingleDecl();
1490}
1491
1492Decl *
1493TemplateDeclInstantiator::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
1494 NamespaceAliasDecl *Inst
1495 = NamespaceAliasDecl::Create(SemaRef.Context, Owner,
1496 D->getNamespaceLoc(),
1497 D->getAliasLoc(),
1498 D->getIdentifier(),
1499 D->getQualifierLoc(),
1500 D->getTargetNameLoc(),
1501 D->getNamespace());
1502 Owner->addDecl(Inst);
1503 return Inst;
1504}
1505
1507 bool IsTypeAlias) {
1508 bool Invalid = false;
1510 if (TSI->getType()->isInstantiationDependentType() ||
1511 TSI->getType()->isVariablyModifiedType()) {
1512 TSI = SemaRef.SubstType(TSI, TemplateArgs, D->getLocation(),
1513 D->getDeclName());
1514 if (!TSI) {
1515 Invalid = true;
1516 TSI = SemaRef.Context.getTrivialTypeSourceInfo(SemaRef.Context.IntTy);
1517 }
1518 } else {
1519 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), TSI->getType());
1520 }
1521
1522 // HACK: 2012-10-23 g++ has a bug where it gets the value kind of ?: wrong.
1523 // libstdc++ relies upon this bug in its implementation of common_type. If we
1524 // happen to be processing that implementation, fake up the g++ ?:
1525 // semantics. See LWG issue 2141 for more information on the bug. The bugs
1526 // are fixed in g++ and libstdc++ 4.9.0 (2014-04-22).
1527 if (SemaRef.getPreprocessor().NeedsStdLibCxxWorkaroundBefore(2014'04'22)) {
1528 const DecltypeType *DT = TSI->getType()->getAs<DecltypeType>();
1529 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D->getDeclContext());
1530 if (DT && RD && isa<ConditionalOperator>(DT->getUnderlyingExpr()) &&
1531 DT->isReferenceType() &&
1532 RD->getEnclosingNamespaceContext() == SemaRef.getStdNamespace() &&
1533 RD->getIdentifier() && RD->getIdentifier()->isStr("common_type") &&
1534 D->getIdentifier() && D->getIdentifier()->isStr("type") &&
1535 SemaRef.getSourceManager().isInSystemHeader(D->getBeginLoc()))
1536 // Fold it to the (non-reference) type which g++ would have produced.
1537 TSI = SemaRef.Context.getTrivialTypeSourceInfo(
1538 TSI->getType().getNonReferenceType());
1539 }
1540
1541 // Create the new typedef
1543 if (IsTypeAlias)
1544 Typedef = TypeAliasDecl::Create(SemaRef.Context, Owner, D->getBeginLoc(),
1545 D->getLocation(), D->getIdentifier(), TSI);
1546 else
1547 Typedef = TypedefDecl::Create(SemaRef.Context, Owner, D->getBeginLoc(),
1548 D->getLocation(), D->getIdentifier(), TSI);
1549 if (Invalid)
1550 Typedef->setInvalidDecl();
1551
1552 // If the old typedef was the name for linkage purposes of an anonymous
1553 // tag decl, re-establish that relationship for the new typedef.
1554 if (const TagType *oldTagType = D->getUnderlyingType()->getAs<TagType>()) {
1555 TagDecl *oldTag = oldTagType->getDecl();
1556 if (oldTag->getTypedefNameForAnonDecl() == D && !Invalid) {
1557 TagDecl *newTag = TSI->getType()->castAs<TagType>()->getDecl();
1558 assert(!newTag->hasNameForLinkage());
1560 }
1561 }
1562
1564 NamedDecl *InstPrev = SemaRef.FindInstantiatedDecl(D->getLocation(), Prev,
1565 TemplateArgs);
1566 if (!InstPrev)
1567 return nullptr;
1568
1569 TypedefNameDecl *InstPrevTypedef = cast<TypedefNameDecl>(InstPrev);
1570
1571 // If the typedef types are not identical, reject them.
1572 SemaRef.isIncompatibleTypedef(InstPrevTypedef, Typedef);
1573
1574 Typedef->setPreviousDecl(InstPrevTypedef);
1575 }
1576
1577 SemaRef.InstantiateAttrs(TemplateArgs, D, Typedef);
1578
1579 if (D->getUnderlyingType()->getAs<DependentNameType>())
1580 SemaRef.inferGslPointerAttribute(Typedef);
1581
1582 Typedef->setAccess(D->getAccess());
1583 Typedef->setReferenced(D->isReferenced());
1584
1585 return Typedef;
1586}
1587
1588Decl *TemplateDeclInstantiator::VisitTypedefDecl(TypedefDecl *D) {
1589 Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/false);
1590 if (Typedef)
1591 Owner->addDecl(Typedef);
1592 return Typedef;
1593}
1594
1595Decl *TemplateDeclInstantiator::VisitTypeAliasDecl(TypeAliasDecl *D) {
1596 Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/true);
1597 if (Typedef)
1598 Owner->addDecl(Typedef);
1599 return Typedef;
1600}
1601
1604 // Create a local instantiation scope for this type alias template, which
1605 // will contain the instantiations of the template parameters.
1607
1609 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1610 if (!InstParams)
1611 return nullptr;
1612
1613 // FIXME: This is a hack for instantiating lambdas in the pattern of the
1614 // alias. We are not really instantiating the alias at its template level,
1615 // that only happens in CheckTemplateId, this is only for outer templates
1616 // which contain it. In getTemplateInstantiationArgs, the template arguments
1617 // used here would be used for collating the template arguments needed to
1618 // instantiate the lambda. Pass an empty argument list, so this workaround
1619 // doesn't get confused if there is an outer alias being instantiated.
1620 Sema::InstantiatingTemplate InstTemplate(SemaRef, D->getBeginLoc(), D,
1622 if (InstTemplate.isInvalid())
1623 return nullptr;
1624
1625 TypeAliasDecl *Pattern = D->getTemplatedDecl();
1626 TypeAliasTemplateDecl *PrevAliasTemplate = nullptr;
1628 DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
1629 if (!Found.empty()) {
1630 PrevAliasTemplate = dyn_cast<TypeAliasTemplateDecl>(Found.front());
1631 }
1632 }
1633
1634 TypeAliasDecl *AliasInst = cast_or_null<TypeAliasDecl>(
1635 InstantiateTypedefNameDecl(Pattern, /*IsTypeAlias=*/true));
1636 if (!AliasInst)
1637 return nullptr;
1638
1640 = TypeAliasTemplateDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1641 D->getDeclName(), InstParams, AliasInst);
1642 AliasInst->setDescribedAliasTemplate(Inst);
1643 if (PrevAliasTemplate)
1644 Inst->setPreviousDecl(PrevAliasTemplate);
1645
1646 Inst->setAccess(D->getAccess());
1647
1648 if (!PrevAliasTemplate)
1650
1651 return Inst;
1652}
1653
1654Decl *
1655TemplateDeclInstantiator::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) {
1657 if (Inst)
1658 Owner->addDecl(Inst);
1659
1660 return Inst;
1661}
1662
1663Decl *TemplateDeclInstantiator::VisitBindingDecl(BindingDecl *D) {
1664 auto *NewBD = BindingDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1665 D->getIdentifier(), D->getType());
1666 NewBD->setReferenced(D->isReferenced());
1668
1669 return NewBD;
1670}
1671
1672Decl *TemplateDeclInstantiator::VisitDecompositionDecl(DecompositionDecl *D) {
1673 // Transform the bindings first.
1674 // The transformed DD will have all of the concrete BindingDecls.
1675 SmallVector<BindingDecl*, 16> NewBindings;
1676 BindingDecl *OldBindingPack = nullptr;
1677 for (auto *OldBD : D->bindings()) {
1678 Expr *BindingExpr = OldBD->getBinding();
1679 if (isa_and_present<FunctionParmPackExpr>(BindingExpr)) {
1680 // We have a resolved pack.
1681 assert(!OldBindingPack && "no more than one pack is allowed");
1682 OldBindingPack = OldBD;
1683 }
1684 NewBindings.push_back(cast<BindingDecl>(VisitBindingDecl(OldBD)));
1685 }
1686 ArrayRef<BindingDecl*> NewBindingArray = NewBindings;
1687
1688 auto *NewDD = cast_if_present<DecompositionDecl>(
1689 VisitVarDecl(D, /*InstantiatingVarTemplate=*/false, &NewBindingArray));
1690
1691 if (!NewDD || NewDD->isInvalidDecl()) {
1692 for (auto *NewBD : NewBindings)
1693 NewBD->setInvalidDecl();
1694 } else if (OldBindingPack) {
1695 // Mark the bindings in the pack as instantiated.
1696 auto Bindings = NewDD->bindings();
1697 BindingDecl *NewBindingPack = *llvm::find_if(
1698 Bindings, [](BindingDecl *D) -> bool { return D->isParameterPack(); });
1699 assert(NewBindingPack != nullptr && "new bindings should also have a pack");
1700 llvm::ArrayRef<BindingDecl *> OldDecls =
1701 OldBindingPack->getBindingPackDecls();
1702 llvm::ArrayRef<BindingDecl *> NewDecls =
1703 NewBindingPack->getBindingPackDecls();
1704 assert(OldDecls.size() == NewDecls.size());
1705 for (unsigned I = 0; I < OldDecls.size(); I++)
1706 SemaRef.CurrentInstantiationScope->InstantiatedLocal(OldDecls[I],
1707 NewDecls[I]);
1708 }
1709
1710 return NewDD;
1711}
1712
1714 return VisitVarDecl(D, /*InstantiatingVarTemplate=*/false);
1715}
1716
1718 bool InstantiatingVarTemplate,
1720
1721 // Do substitution on the type of the declaration
1722 TypeSourceInfo *TSI = SemaRef.SubstType(
1723 D->getTypeSourceInfo(), TemplateArgs, D->getTypeSpecStartLoc(),
1724 D->getDeclName(), /*AllowDeducedTST*/ true);
1725 if (!TSI)
1726 return nullptr;
1727
1728 if (TSI->getType()->isFunctionType()) {
1729 SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function)
1730 << D->isStaticDataMember() << TSI->getType();
1731 return nullptr;
1732 }
1733
1734 DeclContext *DC = Owner;
1735 if (D->isLocalExternDecl())
1737
1738 // Build the instantiated declaration.
1739 VarDecl *Var;
1740 if (Bindings)
1741 Var = DecompositionDecl::Create(SemaRef.Context, DC, D->getInnerLocStart(),
1742 D->getLocation(), TSI->getType(), TSI,
1743 D->getStorageClass(), *Bindings);
1744 else
1745 Var = VarDecl::Create(SemaRef.Context, DC, D->getInnerLocStart(),
1746 D->getLocation(), D->getIdentifier(), TSI->getType(),
1747 TSI, D->getStorageClass());
1748
1749 // In ARC, infer 'retaining' for variables of retainable type.
1750 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
1751 SemaRef.ObjC().inferObjCARCLifetime(Var))
1752 Var->setInvalidDecl();
1753
1754 if (SemaRef.getLangOpts().OpenCL)
1755 SemaRef.deduceOpenCLAddressSpace(Var);
1756
1757 // Substitute the nested name specifier, if any.
1758 if (SubstQualifier(D, Var))
1759 return nullptr;
1760
1761 SemaRef.BuildVariableInstantiation(Var, D, TemplateArgs, LateAttrs, Owner,
1762 StartingScope, InstantiatingVarTemplate);
1763 if (D->isNRVOVariable() && !Var->isInvalidDecl()) {
1764 QualType RT;
1765 if (auto *F = dyn_cast<FunctionDecl>(DC))
1766 RT = F->getReturnType();
1767 else if (isa<BlockDecl>(DC))
1769 ->getReturnType();
1770 else
1771 llvm_unreachable("Unknown context type");
1772
1773 // This is the last chance we have of checking copy elision eligibility
1774 // for functions in dependent contexts. The sema actions for building
1775 // the return statement during template instantiation will have no effect
1776 // regarding copy elision, since NRVO propagation runs on the scope exit
1777 // actions, and these are not run on instantiation.
1778 // This might run through some VarDecls which were returned from non-taken
1779 // 'if constexpr' branches, and these will end up being constructed on the
1780 // return slot even if they will never be returned, as a sort of accidental
1781 // 'optimization'. Notably, functions with 'auto' return types won't have it
1782 // deduced by this point. Coupled with the limitation described
1783 // previously, this makes it very hard to support copy elision for these.
1784 Sema::NamedReturnInfo Info = SemaRef.getNamedReturnInfo(Var);
1785 bool NRVO = SemaRef.getCopyElisionCandidate(Info, RT) != nullptr;
1786 Var->setNRVOVariable(NRVO);
1787 }
1788
1789 Var->setImplicit(D->isImplicit());
1790
1791 if (Var->isStaticLocal())
1792 SemaRef.CheckStaticLocalForDllExport(Var);
1793
1794 if (Var->getTLSKind())
1795 SemaRef.CheckThreadLocalForLargeAlignment(Var);
1796
1797 if (SemaRef.getLangOpts().OpenACC)
1798 SemaRef.OpenACC().ActOnVariableDeclarator(Var);
1799
1800 return Var;
1801}
1802
1803Decl *TemplateDeclInstantiator::VisitAccessSpecDecl(AccessSpecDecl *D) {
1804 AccessSpecDecl* AD
1805 = AccessSpecDecl::Create(SemaRef.Context, D->getAccess(), Owner,
1807 Owner->addHiddenDecl(AD);
1808 return AD;
1809}
1810
1811Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) {
1812 bool Invalid = false;
1813 TypeSourceInfo *TSI = D->getTypeSourceInfo();
1814 if (TSI->getType()->isInstantiationDependentType() ||
1815 TSI->getType()->isVariablyModifiedType()) {
1816 TSI = SemaRef.SubstType(TSI, TemplateArgs, D->getLocation(),
1817 D->getDeclName());
1818 if (!TSI) {
1819 TSI = D->getTypeSourceInfo();
1820 Invalid = true;
1821 } else if (TSI->getType()->isFunctionType()) {
1822 // C++ [temp.arg.type]p3:
1823 // If a declaration acquires a function type through a type
1824 // dependent on a template-parameter and this causes a
1825 // declaration that does not use the syntactic form of a
1826 // function declarator to have function type, the program is
1827 // ill-formed.
1828 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
1829 << TSI->getType();
1830 Invalid = true;
1831 }
1832 } else {
1833 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), TSI->getType());
1834 }
1835
1836 Expr *BitWidth = D->getBitWidth();
1837 if (Invalid)
1838 BitWidth = nullptr;
1839 else if (BitWidth) {
1840 // The bit-width expression is a constant expression.
1841 EnterExpressionEvaluationContext Unevaluated(
1843
1844 ExprResult InstantiatedBitWidth
1845 = SemaRef.SubstExpr(BitWidth, TemplateArgs);
1846 if (InstantiatedBitWidth.isInvalid()) {
1847 Invalid = true;
1848 BitWidth = nullptr;
1849 } else
1850 BitWidth = InstantiatedBitWidth.getAs<Expr>();
1851 }
1852
1853 FieldDecl *Field = SemaRef.CheckFieldDecl(
1854 D->getDeclName(), TSI->getType(), TSI, cast<RecordDecl>(Owner),
1855 D->getLocation(), D->isMutable(), BitWidth, D->getInClassInitStyle(),
1856 D->getInnerLocStart(), D->getAccess(), nullptr);
1857 if (!Field) {
1858 cast<Decl>(Owner)->setInvalidDecl();
1859 return nullptr;
1860 }
1861
1862 SemaRef.InstantiateAttrs(TemplateArgs, D, Field, LateAttrs, StartingScope);
1863
1864 if (Field->hasAttrs())
1865 SemaRef.CheckAlignasUnderalignment(Field);
1866
1867 if (Invalid)
1868 Field->setInvalidDecl();
1869
1870 if (!Field->getDeclName() || Field->isPlaceholderVar(SemaRef.getLangOpts())) {
1871 // Keep track of where this decl came from.
1872 SemaRef.Context.setInstantiatedFromUnnamedFieldDecl(Field, D);
1873 }
1874 if (CXXRecordDecl *Parent= dyn_cast<CXXRecordDecl>(Field->getDeclContext())) {
1875 if (Parent->isAnonymousStructOrUnion() &&
1876 Parent->getRedeclContext()->isFunctionOrMethod())
1877 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Field);
1878 }
1879
1880 Field->setImplicit(D->isImplicit());
1881 Field->setAccess(D->getAccess());
1882 Owner->addDecl(Field);
1883
1884 return Field;
1885}
1886
1887Decl *TemplateDeclInstantiator::VisitMSPropertyDecl(MSPropertyDecl *D) {
1888 bool Invalid = false;
1889 TypeSourceInfo *TSI = D->getTypeSourceInfo();
1890
1891 if (TSI->getType()->isVariablyModifiedType()) {
1892 SemaRef.Diag(D->getLocation(), diag::err_property_is_variably_modified)
1893 << D;
1894 Invalid = true;
1895 } else if (TSI->getType()->isInstantiationDependentType()) {
1896 TSI = SemaRef.SubstType(TSI, TemplateArgs, D->getLocation(),
1897 D->getDeclName());
1898 if (!TSI) {
1899 TSI = D->getTypeSourceInfo();
1900 Invalid = true;
1901 } else if (TSI->getType()->isFunctionType()) {
1902 // C++ [temp.arg.type]p3:
1903 // If a declaration acquires a function type through a type
1904 // dependent on a template-parameter and this causes a
1905 // declaration that does not use the syntactic form of a
1906 // function declarator to have function type, the program is
1907 // ill-formed.
1908 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
1909 << TSI->getType();
1910 Invalid = true;
1911 }
1912 } else {
1913 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), TSI->getType());
1914 }
1915
1916 MSPropertyDecl *Property = MSPropertyDecl::Create(
1917 SemaRef.Context, Owner, D->getLocation(), D->getDeclName(),
1918 TSI->getType(), TSI, D->getBeginLoc(), D->getGetterId(),
1919 D->getSetterId());
1920
1921 SemaRef.InstantiateAttrs(TemplateArgs, D, Property, LateAttrs,
1922 StartingScope);
1923
1924 if (Invalid)
1925 Property->setInvalidDecl();
1926
1927 Property->setAccess(D->getAccess());
1928 Owner->addDecl(Property);
1929
1930 return Property;
1931}
1932
1933Decl *TemplateDeclInstantiator::VisitIndirectFieldDecl(IndirectFieldDecl *D) {
1934 NamedDecl **NamedChain =
1935 new (SemaRef.Context)NamedDecl*[D->getChainingSize()];
1936
1937 int i = 0;
1938 for (auto *PI : D->chain()) {
1939 NamedDecl *Next = SemaRef.FindInstantiatedDecl(D->getLocation(), PI,
1940 TemplateArgs);
1941 if (!Next)
1942 return nullptr;
1943
1944 NamedChain[i++] = Next;
1945 }
1946
1947 QualType T = cast<FieldDecl>(NamedChain[i-1])->getType();
1948 IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
1949 SemaRef.Context, Owner, D->getLocation(), D->getIdentifier(), T,
1950 {NamedChain, D->getChainingSize()});
1951
1952 for (const auto *Attr : D->attrs())
1953 IndirectField->addAttr(Attr->clone(SemaRef.Context));
1954
1955 IndirectField->setImplicit(D->isImplicit());
1956 IndirectField->setAccess(D->getAccess());
1957 Owner->addDecl(IndirectField);
1958 return IndirectField;
1959}
1960
1961Decl *TemplateDeclInstantiator::VisitFriendDecl(FriendDecl *D) {
1962 // Handle friend type expressions by simply substituting template
1963 // parameters into the pattern type and checking the result.
1964 if (TypeSourceInfo *Ty = D->getFriendType()) {
1965 TypeSourceInfo *InstTy;
1966 // If this is an unsupported friend, don't bother substituting template
1967 // arguments into it. The actual type referred to won't be used by any
1968 // parts of Clang, and may not be valid for instantiating. Just use the
1969 // same info for the instantiated friend.
1970 if (D->isUnsupportedFriend()) {
1971 InstTy = Ty;
1972 } else {
1973 if (D->isPackExpansion()) {
1974 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
1975 SemaRef.collectUnexpandedParameterPacks(Ty->getTypeLoc(), Unexpanded);
1976 assert(!Unexpanded.empty() && "Pack expansion without packs");
1977
1978 bool ShouldExpand = true;
1979 bool RetainExpansion = false;
1980 UnsignedOrNone NumExpansions = std::nullopt;
1981 if (SemaRef.CheckParameterPacksForExpansion(
1982 D->getEllipsisLoc(), D->getSourceRange(), Unexpanded,
1983 TemplateArgs, /*FailOnPackProducingTemplates=*/true,
1984 ShouldExpand, RetainExpansion, NumExpansions))
1985 return nullptr;
1986
1987 assert(!RetainExpansion &&
1988 "should never retain an expansion for a variadic friend decl");
1989
1990 if (ShouldExpand) {
1991 SmallVector<FriendDecl *> Decls;
1992 for (unsigned I = 0; I != *NumExpansions; I++) {
1993 Sema::ArgPackSubstIndexRAII SubstIndex(SemaRef, I);
1994 TypeSourceInfo *TSI = SemaRef.SubstType(
1995 Ty, TemplateArgs, D->getEllipsisLoc(), DeclarationName());
1996 if (!TSI)
1997 return nullptr;
1998
1999 auto FD =
2000 FriendDecl::Create(SemaRef.Context, Owner, D->getLocation(),
2001 TSI, D->getFriendLoc());
2002
2003 FD->setAccess(AS_public);
2004 Owner->addDecl(FD);
2005 Decls.push_back(FD);
2006 }
2007
2008 // Just drop this node; we have no use for it anymore.
2009 return nullptr;
2010 }
2011 }
2012
2013 InstTy = SemaRef.SubstType(Ty, TemplateArgs, D->getLocation(),
2014 DeclarationName());
2015 }
2016 if (!InstTy)
2017 return nullptr;
2018
2019 FriendDecl *FD = FriendDecl::Create(
2020 SemaRef.Context, Owner, D->getLocation(), InstTy, D->getFriendLoc());
2021 FD->setAccess(AS_public);
2023 Owner->addDecl(FD);
2024 return FD;
2025 }
2026
2027 NamedDecl *ND = D->getFriendDecl();
2028 assert(ND && "friend decl must be a decl or a type!");
2029
2030 // All of the Visit implementations for the various potential friend
2031 // declarations have to be carefully written to work for friend
2032 // objects, with the most important detail being that the target
2033 // decl should almost certainly not be placed in Owner.
2034 Decl *NewND = Visit(ND);
2035 if (!NewND) return nullptr;
2036
2037 FriendDecl *FD =
2038 FriendDecl::Create(SemaRef.Context, Owner, D->getLocation(),
2039 cast<NamedDecl>(NewND), D->getFriendLoc());
2040 FD->setAccess(AS_public);
2042 Owner->addDecl(FD);
2043 return FD;
2044}
2045
2046Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) {
2047 Expr *AssertExpr = D->getAssertExpr();
2048
2049 // The expression in a static assertion is a constant expression.
2050 EnterExpressionEvaluationContext Unevaluated(
2052
2053 ExprResult InstantiatedAssertExpr
2054 = SemaRef.SubstExpr(AssertExpr, TemplateArgs);
2055 if (InstantiatedAssertExpr.isInvalid())
2056 return nullptr;
2057
2058 ExprResult InstantiatedMessageExpr =
2059 SemaRef.SubstExpr(D->getMessage(), TemplateArgs);
2060 if (InstantiatedMessageExpr.isInvalid())
2061 return nullptr;
2062
2063 return SemaRef.BuildStaticAssertDeclaration(
2064 D->getLocation(), InstantiatedAssertExpr.get(),
2065 InstantiatedMessageExpr.get(), D->getRParenLoc(), D->isFailed());
2066}
2067
2068Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) {
2069 EnumDecl *PrevDecl = nullptr;
2070 if (EnumDecl *PatternPrev = getPreviousDeclForInstantiation(D)) {
2071 NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
2072 PatternPrev,
2073 TemplateArgs);
2074 if (!Prev) return nullptr;
2075 PrevDecl = cast<EnumDecl>(Prev);
2076 }
2077
2078 EnumDecl *Enum =
2079 EnumDecl::Create(SemaRef.Context, Owner, D->getBeginLoc(),
2080 D->getLocation(), D->getIdentifier(), PrevDecl,
2081 D->isScoped(), D->isScopedUsingClassTag(), D->isFixed());
2082 if (D->isFixed()) {
2083 if (TypeSourceInfo *TI = D->getIntegerTypeSourceInfo()) {
2084 // If we have type source information for the underlying type, it means it
2085 // has been explicitly set by the user. Perform substitution on it before
2086 // moving on.
2087 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
2088 TypeSourceInfo *NewTI = SemaRef.SubstType(TI, TemplateArgs, UnderlyingLoc,
2089 DeclarationName());
2090 if (!NewTI || SemaRef.CheckEnumUnderlyingType(NewTI))
2091 Enum->setIntegerType(SemaRef.Context.IntTy);
2092 else {
2093 // If the underlying type is atomic, we need to adjust the type before
2094 // continuing. See C23 6.7.3.3p5 and Sema::ActOnTag(). FIXME: same as
2095 // within ActOnTag(), it would be nice to have an easy way to get a
2096 // derived TypeSourceInfo which strips qualifiers including the weird
2097 // ones like _Atomic where it forms a different type.
2098 if (NewTI->getType()->isAtomicType())
2099 Enum->setIntegerType(NewTI->getType().getAtomicUnqualifiedType());
2100 else
2101 Enum->setIntegerTypeSourceInfo(NewTI);
2102 }
2103
2104 // C++23 [conv.prom]p4
2105 // if integral promotion can be applied to its underlying type, a prvalue
2106 // of an unscoped enumeration type whose underlying type is fixed can also
2107 // be converted to a prvalue of the promoted underlying type.
2108 //
2109 // FIXME: that logic is already implemented in ActOnEnumBody, factor out
2110 // into (Re)BuildEnumBody.
2111 QualType UnderlyingType = Enum->getIntegerType();
2112 Enum->setPromotionType(
2113 SemaRef.Context.isPromotableIntegerType(UnderlyingType)
2114 ? SemaRef.Context.getPromotedIntegerType(UnderlyingType)
2115 : UnderlyingType);
2116 } else {
2117 assert(!D->getIntegerType()->isDependentType()
2118 && "Dependent type without type source info");
2119 Enum->setIntegerType(D->getIntegerType());
2120 }
2121 }
2122
2123 SemaRef.InstantiateAttrs(TemplateArgs, D, Enum);
2124
2125 Enum->setInstantiationOfMemberEnum(D, TSK_ImplicitInstantiation);
2126 Enum->setAccess(D->getAccess());
2127 // Forward the mangling number from the template to the instantiated decl.
2128 SemaRef.Context.setManglingNumber(Enum, SemaRef.Context.getManglingNumber(D));
2129 // See if the old tag was defined along with a declarator.
2130 // If it did, mark the new tag as being associated with that declarator.
2131 if (DeclaratorDecl *DD = SemaRef.Context.getDeclaratorForUnnamedTagDecl(D))
2132 SemaRef.Context.addDeclaratorForUnnamedTagDecl(Enum, DD);
2133 // See if the old tag was defined along with a typedef.
2134 // If it did, mark the new tag as being associated with that typedef.
2135 if (TypedefNameDecl *TND = SemaRef.Context.getTypedefNameForUnnamedTagDecl(D))
2136 SemaRef.Context.addTypedefNameForUnnamedTagDecl(Enum, TND);
2137 if (SubstQualifier(D, Enum)) return nullptr;
2138 Owner->addDecl(Enum);
2139
2140 EnumDecl *Def = D->getDefinition();
2141 if (Def && Def != D) {
2142 // If this is an out-of-line definition of an enum member template, check
2143 // that the underlying types match in the instantiation of both
2144 // declarations.
2145 if (TypeSourceInfo *TI = Def->getIntegerTypeSourceInfo()) {
2146 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
2147 QualType DefnUnderlying =
2148 SemaRef.SubstType(TI->getType(), TemplateArgs,
2149 UnderlyingLoc, DeclarationName());
2150 SemaRef.CheckEnumRedeclaration(Def->getLocation(), Def->isScoped(),
2151 DefnUnderlying, /*IsFixed=*/true, Enum);
2152 }
2153 }
2154
2155 // C++11 [temp.inst]p1: The implicit instantiation of a class template
2156 // specialization causes the implicit instantiation of the declarations, but
2157 // not the definitions of scoped member enumerations.
2158 //
2159 // DR1484 clarifies that enumeration definitions inside a template
2160 // declaration aren't considered entities that can be separately instantiated
2161 // from the rest of the entity they are declared inside.
2162 if (isDeclWithinFunction(D) ? D == Def : Def && !Enum->isScoped()) {
2163 // Prevent redundant instantiation of the enumerator-definition if the
2164 // definition has already been instantiated due to a prior
2165 // opaque-enum-declaration.
2166 if (PrevDecl == nullptr) {
2167 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Enum);
2169 }
2170 }
2171
2172 return Enum;
2173}
2174
2176 EnumDecl *Enum, EnumDecl *Pattern) {
2177 Enum->startDefinition();
2178
2179 // Update the location to refer to the definition.
2180 Enum->setLocation(Pattern->getLocation());
2181
2182 SmallVector<Decl*, 4> Enumerators;
2183
2184 EnumConstantDecl *LastEnumConst = nullptr;
2185 for (auto *EC : Pattern->enumerators()) {
2186 // The specified value for the enumerator.
2187 ExprResult Value((Expr *)nullptr);
2188 if (Expr *UninstValue = EC->getInitExpr()) {
2189 // The enumerator's value expression is a constant expression.
2192
2193 Value = SemaRef.SubstExpr(UninstValue, TemplateArgs);
2194 }
2195
2196 // Drop the initial value and continue.
2197 bool isInvalid = false;
2198 if (Value.isInvalid()) {
2199 Value = nullptr;
2200 isInvalid = true;
2201 }
2202
2203 EnumConstantDecl *EnumConst
2204 = SemaRef.CheckEnumConstant(Enum, LastEnumConst,
2205 EC->getLocation(), EC->getIdentifier(),
2206 Value.get());
2207
2208 if (isInvalid) {
2209 if (EnumConst)
2210 EnumConst->setInvalidDecl();
2211 Enum->setInvalidDecl();
2212 }
2213
2214 if (EnumConst) {
2215 SemaRef.InstantiateAttrs(TemplateArgs, EC, EnumConst);
2216
2217 EnumConst->setAccess(Enum->getAccess());
2218 Enum->addDecl(EnumConst);
2219 Enumerators.push_back(EnumConst);
2220 LastEnumConst = EnumConst;
2221
2222 if (Pattern->getDeclContext()->isFunctionOrMethod() &&
2223 !Enum->isScoped()) {
2224 // If the enumeration is within a function or method, record the enum
2225 // constant as a local.
2226 SemaRef.CurrentInstantiationScope->InstantiatedLocal(EC, EnumConst);
2227 }
2228 }
2229 }
2230
2231 SemaRef.ActOnEnumBody(Enum->getLocation(), Enum->getBraceRange(), Enum,
2232 Enumerators, nullptr, ParsedAttributesView());
2233}
2234
2235Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) {
2236 llvm_unreachable("EnumConstantDecls can only occur within EnumDecls.");
2237}
2238
2239Decl *
2240TemplateDeclInstantiator::VisitBuiltinTemplateDecl(BuiltinTemplateDecl *D) {
2241 llvm_unreachable("BuiltinTemplateDecls cannot be instantiated.");
2242}
2243
2244Decl *TemplateDeclInstantiator::VisitClassTemplateDecl(ClassTemplateDecl *D) {
2245 bool isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
2246
2247 // Create a local instantiation scope for this class template, which
2248 // will contain the instantiations of the template parameters.
2249 LocalInstantiationScope Scope(SemaRef);
2250 TemplateParameterList *TempParams = D->getTemplateParameters();
2251 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
2252 if (!InstParams)
2253 return nullptr;
2254
2255 CXXRecordDecl *Pattern = D->getTemplatedDecl();
2256
2257 // Instantiate the qualifier. We have to do this first in case
2258 // we're a friend declaration, because if we are then we need to put
2259 // the new declaration in the appropriate context.
2260 NestedNameSpecifierLoc QualifierLoc = Pattern->getQualifierLoc();
2261 if (QualifierLoc) {
2262 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
2263 TemplateArgs);
2264 if (!QualifierLoc)
2265 return nullptr;
2266 }
2267
2268 CXXRecordDecl *PrevDecl = nullptr;
2269 ClassTemplateDecl *PrevClassTemplate = nullptr;
2270
2271 if (!isFriend && getPreviousDeclForInstantiation(Pattern)) {
2272 DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
2273 if (!Found.empty()) {
2274 PrevClassTemplate = dyn_cast<ClassTemplateDecl>(Found.front());
2275 if (PrevClassTemplate)
2276 PrevDecl = PrevClassTemplate->getTemplatedDecl();
2277 }
2278 }
2279
2280 // If this isn't a friend, then it's a member template, in which
2281 // case we just want to build the instantiation in the
2282 // specialization. If it is a friend, we want to build it in
2283 // the appropriate context.
2284 DeclContext *DC = Owner;
2285 if (isFriend) {
2286 if (QualifierLoc) {
2287 CXXScopeSpec SS;
2288 SS.Adopt(QualifierLoc);
2289 DC = SemaRef.computeDeclContext(SS);
2290 if (!DC) return nullptr;
2291 } else {
2292 DC = SemaRef.FindInstantiatedContext(Pattern->getLocation(),
2293 Pattern->getDeclContext(),
2294 TemplateArgs);
2295 }
2296
2297 // Look for a previous declaration of the template in the owning
2298 // context.
2299 LookupResult R(SemaRef, Pattern->getDeclName(), Pattern->getLocation(),
2301 SemaRef.forRedeclarationInCurContext());
2302 SemaRef.LookupQualifiedName(R, DC);
2303
2304 if (R.isSingleResult()) {
2305 PrevClassTemplate = R.getAsSingle<ClassTemplateDecl>();
2306 if (PrevClassTemplate)
2307 PrevDecl = PrevClassTemplate->getTemplatedDecl();
2308 }
2309
2310 if (!PrevClassTemplate && QualifierLoc) {
2311 SemaRef.Diag(Pattern->getLocation(), diag::err_not_tag_in_scope)
2312 << D->getTemplatedDecl()->getTagKind() << Pattern->getDeclName() << DC
2313 << QualifierLoc.getSourceRange();
2314 return nullptr;
2315 }
2316 }
2317
2318 CXXRecordDecl *RecordInst = CXXRecordDecl::Create(
2319 SemaRef.Context, Pattern->getTagKind(), DC, Pattern->getBeginLoc(),
2320 Pattern->getLocation(), Pattern->getIdentifier(), PrevDecl);
2321 if (QualifierLoc)
2322 RecordInst->setQualifierInfo(QualifierLoc);
2323
2324 SemaRef.InstantiateAttrsForDecl(TemplateArgs, Pattern, RecordInst, LateAttrs,
2325 StartingScope);
2326
2327 ClassTemplateDecl *Inst
2328 = ClassTemplateDecl::Create(SemaRef.Context, DC, D->getLocation(),
2329 D->getIdentifier(), InstParams, RecordInst);
2330 RecordInst->setDescribedClassTemplate(Inst);
2331
2332 if (isFriend) {
2333 assert(!Owner->isDependentContext());
2334 Inst->setLexicalDeclContext(Owner);
2335 RecordInst->setLexicalDeclContext(Owner);
2336 Inst->setObjectOfFriendDecl();
2337
2338 if (PrevClassTemplate) {
2339 Inst->setCommonPtr(PrevClassTemplate->getCommonPtr());
2340 const ClassTemplateDecl *MostRecentPrevCT =
2341 PrevClassTemplate->getMostRecentDecl();
2342 TemplateParameterList *PrevParams =
2343 MostRecentPrevCT->getTemplateParameters();
2344
2345 // Make sure the parameter lists match.
2346 if (!SemaRef.TemplateParameterListsAreEqual(
2347 RecordInst, InstParams, MostRecentPrevCT->getTemplatedDecl(),
2348 PrevParams, true, Sema::TPL_TemplateMatch))
2349 return nullptr;
2350
2351 // Do some additional validation, then merge default arguments
2352 // from the existing declarations.
2353 if (SemaRef.CheckTemplateParameterList(InstParams, PrevParams,
2355 return nullptr;
2356
2357 Inst->setAccess(PrevClassTemplate->getAccess());
2358 } else {
2359 Inst->setAccess(D->getAccess());
2360 }
2361
2362 Inst->setObjectOfFriendDecl();
2363 // TODO: do we want to track the instantiation progeny of this
2364 // friend target decl?
2365 } else {
2366 Inst->setAccess(D->getAccess());
2367 if (!PrevClassTemplate)
2369 }
2370
2371 Inst->setPreviousDecl(PrevClassTemplate);
2372
2373 // Finish handling of friends.
2374 if (isFriend) {
2375 DC->makeDeclVisibleInContext(Inst);
2376 return Inst;
2377 }
2378
2379 if (D->isOutOfLine()) {
2382 }
2383
2384 Owner->addDecl(Inst);
2385
2386 if (!PrevClassTemplate) {
2387 // Queue up any out-of-line partial specializations of this member
2388 // class template; the client will force their instantiation once
2389 // the enclosing class has been instantiated.
2390 SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
2391 D->getPartialSpecializations(PartialSpecs);
2392 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
2393 if (PartialSpecs[I]->getFirstDecl()->isOutOfLine())
2394 OutOfLinePartialSpecs.push_back(std::make_pair(Inst, PartialSpecs[I]));
2395 }
2396
2397 return Inst;
2398}
2399
2400Decl *
2401TemplateDeclInstantiator::VisitClassTemplatePartialSpecializationDecl(
2403 ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
2404
2405 // Lookup the already-instantiated declaration in the instantiation
2406 // of the class template and return that.
2408 = Owner->lookup(ClassTemplate->getDeclName());
2409 if (Found.empty())
2410 return nullptr;
2411
2412 ClassTemplateDecl *InstClassTemplate
2413 = dyn_cast<ClassTemplateDecl>(Found.front());
2414 if (!InstClassTemplate)
2415 return nullptr;
2416
2417 if (ClassTemplatePartialSpecializationDecl *Result
2418 = InstClassTemplate->findPartialSpecInstantiatedFromMember(D))
2419 return Result;
2420
2421 return InstantiateClassTemplatePartialSpecialization(InstClassTemplate, D);
2422}
2423
2424Decl *TemplateDeclInstantiator::VisitVarTemplateDecl(VarTemplateDecl *D) {
2425 assert(D->getTemplatedDecl()->isStaticDataMember() &&
2426 "Only static data member templates are allowed.");
2427
2428 // Create a local instantiation scope for this variable template, which
2429 // will contain the instantiations of the template parameters.
2430 LocalInstantiationScope Scope(SemaRef);
2431 TemplateParameterList *TempParams = D->getTemplateParameters();
2432 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
2433 if (!InstParams)
2434 return nullptr;
2435
2436 VarDecl *Pattern = D->getTemplatedDecl();
2437 VarTemplateDecl *PrevVarTemplate = nullptr;
2438
2439 if (getPreviousDeclForInstantiation(Pattern)) {
2440 DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
2441 if (!Found.empty())
2442 PrevVarTemplate = dyn_cast<VarTemplateDecl>(Found.front());
2443 }
2444
2445 VarDecl *VarInst =
2446 cast_or_null<VarDecl>(VisitVarDecl(Pattern,
2447 /*InstantiatingVarTemplate=*/true));
2448 if (!VarInst) return nullptr;
2449
2450 DeclContext *DC = Owner;
2451
2452 VarTemplateDecl *Inst = VarTemplateDecl::Create(
2453 SemaRef.Context, DC, D->getLocation(), D->getIdentifier(), InstParams,
2454 VarInst);
2455 VarInst->setDescribedVarTemplate(Inst);
2456 Inst->setPreviousDecl(PrevVarTemplate);
2457
2458 Inst->setAccess(D->getAccess());
2459 if (!PrevVarTemplate)
2461
2462 if (D->isOutOfLine()) {
2465 }
2466
2467 Owner->addDecl(Inst);
2468
2469 if (!PrevVarTemplate) {
2470 // Queue up any out-of-line partial specializations of this member
2471 // variable template; the client will force their instantiation once
2472 // the enclosing class has been instantiated.
2473 SmallVector<VarTemplatePartialSpecializationDecl *, 1> PartialSpecs;
2474 D->getPartialSpecializations(PartialSpecs);
2475 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
2476 if (PartialSpecs[I]->getFirstDecl()->isOutOfLine())
2477 OutOfLineVarPartialSpecs.push_back(
2478 std::make_pair(Inst, PartialSpecs[I]));
2479 }
2480
2481 return Inst;
2482}
2483
2484Decl *TemplateDeclInstantiator::VisitVarTemplatePartialSpecializationDecl(
2486 assert(D->isStaticDataMember() &&
2487 "Only static data member templates are allowed.");
2488
2489 VarTemplateDecl *VarTemplate = D->getSpecializedTemplate();
2490
2491 // Lookup the already-instantiated declaration and return that.
2492 DeclContext::lookup_result Found = Owner->lookup(VarTemplate->getDeclName());
2493 assert(!Found.empty() && "Instantiation found nothing?");
2494
2495 VarTemplateDecl *InstVarTemplate = dyn_cast<VarTemplateDecl>(Found.front());
2496 assert(InstVarTemplate && "Instantiation did not find a variable template?");
2497
2498 if (VarTemplatePartialSpecializationDecl *Result =
2499 InstVarTemplate->findPartialSpecInstantiatedFromMember(D))
2500 return Result;
2501
2502 return InstantiateVarTemplatePartialSpecialization(InstVarTemplate, D);
2503}
2504
2505Decl *
2506TemplateDeclInstantiator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
2507 // Create a local instantiation scope for this function template, which
2508 // will contain the instantiations of the template parameters and then get
2509 // merged with the local instantiation scope for the function template
2510 // itself.
2511 LocalInstantiationScope Scope(SemaRef);
2512 Sema::ConstraintEvalRAII<TemplateDeclInstantiator> RAII(*this);
2513
2514 TemplateParameterList *TempParams = D->getTemplateParameters();
2515 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
2516 if (!InstParams)
2517 return nullptr;
2518
2519 FunctionDecl *Instantiated = nullptr;
2520 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(D->getTemplatedDecl()))
2521 Instantiated = cast_or_null<FunctionDecl>(VisitCXXMethodDecl(DMethod,
2522 InstParams));
2523 else
2524 Instantiated = cast_or_null<FunctionDecl>(VisitFunctionDecl(
2525 D->getTemplatedDecl(),
2526 InstParams));
2527
2528 if (!Instantiated)
2529 return nullptr;
2530
2531 // Link the instantiated function template declaration to the function
2532 // template from which it was instantiated.
2533 FunctionTemplateDecl *InstTemplate
2534 = Instantiated->getDescribedFunctionTemplate();
2535 InstTemplate->setAccess(D->getAccess());
2536 assert(InstTemplate &&
2537 "VisitFunctionDecl/CXXMethodDecl didn't create a template!");
2538
2539 bool isFriend = (InstTemplate->getFriendObjectKind() != Decl::FOK_None);
2540
2541 // Link the instantiation back to the pattern *unless* this is a
2542 // non-definition friend declaration.
2543 if (!InstTemplate->getInstantiatedFromMemberTemplate() &&
2544 !(isFriend && !D->getTemplatedDecl()->isThisDeclarationADefinition()))
2545 InstTemplate->setInstantiatedFromMemberTemplate(D);
2546
2547 // Make declarations visible in the appropriate context.
2548 if (!isFriend) {
2549 Owner->addDecl(InstTemplate);
2550 } else if (InstTemplate->getDeclContext()->isRecord() &&
2552 SemaRef.CheckFriendAccess(InstTemplate);
2553 }
2554
2555 return InstTemplate;
2556}
2557
2558Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) {
2559 CXXRecordDecl *PrevDecl = nullptr;
2560 if (CXXRecordDecl *PatternPrev = getPreviousDeclForInstantiation(D)) {
2561 NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
2562 PatternPrev,
2563 TemplateArgs);
2564 if (!Prev) return nullptr;
2565 PrevDecl = cast<CXXRecordDecl>(Prev);
2566 }
2567
2568 CXXRecordDecl *Record = nullptr;
2569 bool IsInjectedClassName = D->isInjectedClassName();
2570 if (D->isLambda())
2572 SemaRef.Context, Owner, D->getLambdaTypeInfo(), D->getLocation(),
2575 else
2576 Record = CXXRecordDecl::Create(SemaRef.Context, D->getTagKind(), Owner,
2577 D->getBeginLoc(), D->getLocation(),
2578 D->getIdentifier(), PrevDecl);
2579
2580 Record->setImplicit(D->isImplicit());
2581
2582 // Substitute the nested name specifier, if any.
2583 if (SubstQualifier(D, Record))
2584 return nullptr;
2585
2586 SemaRef.InstantiateAttrsForDecl(TemplateArgs, D, Record, LateAttrs,
2587 StartingScope);
2588
2589 // FIXME: Check against AS_none is an ugly hack to work around the issue that
2590 // the tag decls introduced by friend class declarations don't have an access
2591 // specifier. Remove once this area of the code gets sorted out.
2592 if (D->getAccess() != AS_none)
2593 Record->setAccess(D->getAccess());
2594 if (!IsInjectedClassName)
2595 Record->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
2596
2597 // If the original function was part of a friend declaration,
2598 // inherit its namespace state.
2599 if (D->getFriendObjectKind())
2600 Record->setObjectOfFriendDecl();
2601
2602 // Make sure that anonymous structs and unions are recorded.
2603 if (D->isAnonymousStructOrUnion())
2604 Record->setAnonymousStructOrUnion(true);
2605
2606 if (D->isLocalClass())
2607 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Record);
2608
2609 // Forward the mangling number from the template to the instantiated decl.
2610 SemaRef.Context.setManglingNumber(Record,
2611 SemaRef.Context.getManglingNumber(D));
2612
2613 // See if the old tag was defined along with a declarator.
2614 // If it did, mark the new tag as being associated with that declarator.
2615 if (DeclaratorDecl *DD = SemaRef.Context.getDeclaratorForUnnamedTagDecl(D))
2616 SemaRef.Context.addDeclaratorForUnnamedTagDecl(Record, DD);
2617
2618 // See if the old tag was defined along with a typedef.
2619 // If it did, mark the new tag as being associated with that typedef.
2620 if (TypedefNameDecl *TND = SemaRef.Context.getTypedefNameForUnnamedTagDecl(D))
2621 SemaRef.Context.addTypedefNameForUnnamedTagDecl(Record, TND);
2622
2623 Owner->addDecl(Record);
2624
2625 // DR1484 clarifies that the members of a local class are instantiated as part
2626 // of the instantiation of their enclosing entity.
2627 if (D->isCompleteDefinition() && D->isLocalClass()) {
2628 Sema::LocalEagerInstantiationScope LocalInstantiations(SemaRef,
2629 /*AtEndOfTU=*/false);
2630
2631 SemaRef.InstantiateClass(D->getLocation(), Record, D, TemplateArgs,
2633 /*Complain=*/true);
2634
2635 // For nested local classes, we will instantiate the members when we
2636 // reach the end of the outermost (non-nested) local class.
2637 if (!D->isCXXClassMember())
2638 SemaRef.InstantiateClassMembers(D->getLocation(), Record, TemplateArgs,
2640
2641 // This class may have local implicit instantiations that need to be
2642 // performed within this scope.
2643 LocalInstantiations.perform();
2644 }
2645
2646 SemaRef.DiagnoseUnusedNestedTypedefs(Record);
2647
2648 if (IsInjectedClassName)
2649 assert(Record->isInjectedClassName() && "Broken injected-class-name");
2650
2651 return Record;
2652}
2653
2654/// Adjust the given function type for an instantiation of the
2655/// given declaration, to cope with modifications to the function's type that
2656/// aren't reflected in the type-source information.
2657///
2658/// \param D The declaration we're instantiating.
2659/// \param TInfo The already-instantiated type.
2661 FunctionDecl *D,
2662 TypeSourceInfo *TInfo) {
2663 const FunctionProtoType *OrigFunc
2664 = D->getType()->castAs<FunctionProtoType>();
2665 const FunctionProtoType *NewFunc
2666 = TInfo->getType()->castAs<FunctionProtoType>();
2667 if (OrigFunc->getExtInfo() == NewFunc->getExtInfo())
2668 return TInfo->getType();
2669
2670 FunctionProtoType::ExtProtoInfo NewEPI = NewFunc->getExtProtoInfo();
2671 NewEPI.ExtInfo = OrigFunc->getExtInfo();
2672 return Context.getFunctionType(NewFunc->getReturnType(),
2673 NewFunc->getParamTypes(), NewEPI);
2674}
2675
2676/// Normal class members are of more specific types and therefore
2677/// don't make it here. This function serves three purposes:
2678/// 1) instantiating function templates
2679/// 2) substituting friend and local function declarations
2680/// 3) substituting deduction guide declarations for nested class templates
2682 FunctionDecl *D, TemplateParameterList *TemplateParams,
2683 RewriteKind FunctionRewriteKind) {
2684 // Check whether there is already a function template specialization for
2685 // this declaration.
2687 bool isFriend;
2688 if (FunctionTemplate)
2689 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
2690 else
2691 isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
2692
2693 // Friend function defined withing class template may stop being function
2694 // definition during AST merges from different modules, in this case decl
2695 // with function body should be used for instantiation.
2696 if (ExternalASTSource *Source = SemaRef.Context.getExternalSource()) {
2697 if (isFriend && Source->wasThisDeclarationADefinition(D)) {
2698 const FunctionDecl *Defn = nullptr;
2699 if (D->hasBody(Defn)) {
2700 D = const_cast<FunctionDecl *>(Defn);
2702 }
2703 }
2704 }
2705
2706 if (FunctionTemplate && !TemplateParams) {
2707 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
2708
2709 void *InsertPos = nullptr;
2710 FunctionDecl *SpecFunc
2711 = FunctionTemplate->findSpecialization(Innermost, InsertPos);
2712
2713 // If we already have a function template specialization, return it.
2714 if (SpecFunc)
2715 return SpecFunc;
2716 }
2717
2718 bool MergeWithParentScope = (TemplateParams != nullptr) ||
2719 Owner->isFunctionOrMethod() ||
2720 !(isa<Decl>(Owner) &&
2721 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
2722 LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
2723
2724 ExplicitSpecifier InstantiatedExplicitSpecifier;
2725 if (auto *DGuide = dyn_cast<CXXDeductionGuideDecl>(D)) {
2726 InstantiatedExplicitSpecifier = SemaRef.instantiateExplicitSpecifier(
2727 TemplateArgs, DGuide->getExplicitSpecifier());
2728 if (InstantiatedExplicitSpecifier.isInvalid())
2729 return nullptr;
2730 }
2731
2733 TypeSourceInfo *TInfo = SubstFunctionType(D, Params);
2734 if (!TInfo)
2735 return nullptr;
2736 QualType T = adjustFunctionTypeForInstantiation(SemaRef.Context, D, TInfo);
2737
2738 if (TemplateParams && TemplateParams->size()) {
2739 auto *LastParam =
2740 dyn_cast<TemplateTypeParmDecl>(TemplateParams->asArray().back());
2741 if (LastParam && LastParam->isImplicit() &&
2742 LastParam->hasTypeConstraint()) {
2743 // In abbreviated templates, the type-constraints of invented template
2744 // type parameters are instantiated with the function type, invalidating
2745 // the TemplateParameterList which relied on the template type parameter
2746 // not having a type constraint. Recreate the TemplateParameterList with
2747 // the updated parameter list.
2748 TemplateParams = TemplateParameterList::Create(
2749 SemaRef.Context, TemplateParams->getTemplateLoc(),
2750 TemplateParams->getLAngleLoc(), TemplateParams->asArray(),
2751 TemplateParams->getRAngleLoc(), TemplateParams->getRequiresClause());
2752 }
2753 }
2754
2755 NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
2756 if (QualifierLoc) {
2757 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
2758 TemplateArgs);
2759 if (!QualifierLoc)
2760 return nullptr;
2761 }
2762
2763 AssociatedConstraint TrailingRequiresClause = D->getTrailingRequiresClause();
2764
2765 // If we're instantiating a local function declaration, put the result
2766 // in the enclosing namespace; otherwise we need to find the instantiated
2767 // context.
2768 DeclContext *DC;
2769 if (D->isLocalExternDecl()) {
2770 DC = Owner;
2771 SemaRef.adjustContextForLocalExternDecl(DC);
2772 } else if (isFriend && QualifierLoc) {
2773 CXXScopeSpec SS;
2774 SS.Adopt(QualifierLoc);
2775 DC = SemaRef.computeDeclContext(SS);
2776 if (!DC) return nullptr;
2777 } else {
2778 DC = SemaRef.FindInstantiatedContext(D->getLocation(), D->getDeclContext(),
2779 TemplateArgs);
2780 }
2781
2782 DeclarationNameInfo NameInfo
2783 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
2784
2785 if (FunctionRewriteKind != RewriteKind::None)
2786 adjustForRewrite(FunctionRewriteKind, D, T, TInfo, NameInfo);
2787
2789 if (auto *DGuide = dyn_cast<CXXDeductionGuideDecl>(D)) {
2791 SemaRef.Context, DC, D->getInnerLocStart(),
2792 InstantiatedExplicitSpecifier, NameInfo, T, TInfo,
2793 D->getSourceRange().getEnd(), DGuide->getCorrespondingConstructor(),
2794 DGuide->getDeductionCandidateKind(), TrailingRequiresClause,
2795 DGuide->getSourceDeductionGuide(),
2796 DGuide->getSourceDeductionGuideKind());
2797 Function->setAccess(D->getAccess());
2798 } else {
2800 SemaRef.Context, DC, D->getInnerLocStart(), NameInfo, T, TInfo,
2803 TrailingRequiresClause);
2804 Function->setFriendConstraintRefersToEnclosingTemplate(
2806 Function->setRangeEnd(D->getSourceRange().getEnd());
2807 }
2808
2809 if (D->isInlined())
2810 Function->setImplicitlyInline();
2811
2812 if (QualifierLoc)
2813 Function->setQualifierInfo(QualifierLoc);
2814
2815 if (D->isLocalExternDecl())
2816 Function->setLocalExternDecl();
2817
2818 DeclContext *LexicalDC = Owner;
2819 if (!isFriend && D->isOutOfLine() && !D->isLocalExternDecl()) {
2820 assert(D->getDeclContext()->isFileContext());
2821 LexicalDC = D->getDeclContext();
2822 }
2823 else if (D->isLocalExternDecl()) {
2824 LexicalDC = SemaRef.CurContext;
2825 }
2826
2827 Function->setIsDestroyingOperatorDelete(D->isDestroyingOperatorDelete());
2828 Function->setIsTypeAwareOperatorNewOrDelete(
2830 Function->setLexicalDeclContext(LexicalDC);
2831
2832 // Attach the parameters
2833 for (unsigned P = 0; P < Params.size(); ++P)
2834 if (Params[P])
2835 Params[P]->setOwningFunction(Function);
2836 Function->setParams(Params);
2837
2838 if (TrailingRequiresClause)
2839 Function->setTrailingRequiresClause(TrailingRequiresClause);
2840
2841 if (TemplateParams) {
2842 // Our resulting instantiation is actually a function template, since we
2843 // are substituting only the outer template parameters. For example, given
2844 //
2845 // template<typename T>
2846 // struct X {
2847 // template<typename U> friend void f(T, U);
2848 // };
2849 //
2850 // X<int> x;
2851 //
2852 // We are instantiating the friend function template "f" within X<int>,
2853 // which means substituting int for T, but leaving "f" as a friend function
2854 // template.
2855 // Build the function template itself.
2856 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, DC,
2857 Function->getLocation(),
2858 Function->getDeclName(),
2859 TemplateParams, Function);
2860 Function->setDescribedFunctionTemplate(FunctionTemplate);
2861
2862 FunctionTemplate->setLexicalDeclContext(LexicalDC);
2863
2864 if (isFriend && D->isThisDeclarationADefinition()) {
2865 FunctionTemplate->setInstantiatedFromMemberTemplate(
2867 }
2868 } else if (FunctionTemplate &&
2869 SemaRef.CodeSynthesisContexts.back().Kind !=
2871 // Record this function template specialization.
2872 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
2873 Function->setFunctionTemplateSpecialization(FunctionTemplate,
2874 TemplateArgumentList::CreateCopy(SemaRef.Context,
2875 Innermost),
2876 /*InsertPos=*/nullptr);
2877 } else if (FunctionRewriteKind == RewriteKind::None) {
2878 if (isFriend && D->isThisDeclarationADefinition()) {
2879 // Do not connect the friend to the template unless it's actually a
2880 // definition. We don't want non-template functions to be marked as being
2881 // template instantiations.
2882 Function->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
2883 } else if (!isFriend) {
2884 // If this is not a function template, and this is not a friend (that is,
2885 // this is a locally declared function), save the instantiation
2886 // relationship for the purposes of constraint instantiation.
2887 Function->setInstantiatedFromDecl(D);
2888 }
2889 }
2890
2891 if (isFriend) {
2892 Function->setObjectOfFriendDecl();
2893 if (FunctionTemplateDecl *FT = Function->getDescribedFunctionTemplate())
2894 FT->setObjectOfFriendDecl();
2895 }
2896
2898 Function->setInvalidDecl();
2899
2900 bool IsExplicitSpecialization = false;
2901
2903 SemaRef, Function->getDeclName(), SourceLocation(),
2907 : SemaRef.forRedeclarationInCurContext());
2908
2911 assert(isFriend && "dependent specialization info on "
2912 "non-member non-friend function?");
2913
2914 // Instantiate the explicit template arguments.
2915 TemplateArgumentListInfo ExplicitArgs;
2916 if (const auto *ArgsWritten = DFTSI->TemplateArgumentsAsWritten) {
2917 ExplicitArgs.setLAngleLoc(ArgsWritten->getLAngleLoc());
2918 ExplicitArgs.setRAngleLoc(ArgsWritten->getRAngleLoc());
2919 if (SemaRef.SubstTemplateArguments(ArgsWritten->arguments(), TemplateArgs,
2920 ExplicitArgs))
2921 return nullptr;
2922 }
2923
2924 // Map the candidates for the primary template to their instantiations.
2925 for (FunctionTemplateDecl *FTD : DFTSI->getCandidates()) {
2926 if (NamedDecl *ND =
2927 SemaRef.FindInstantiatedDecl(D->getLocation(), FTD, TemplateArgs))
2928 Previous.addDecl(ND);
2929 else
2930 return nullptr;
2931 }
2932
2933 if (SemaRef.CheckFunctionTemplateSpecialization(
2934 Function,
2935 DFTSI->TemplateArgumentsAsWritten ? &ExplicitArgs : nullptr,
2936 Previous))
2937 Function->setInvalidDecl();
2938
2939 IsExplicitSpecialization = true;
2940 } else if (const ASTTemplateArgumentListInfo *ArgsWritten =
2942 // The name of this function was written as a template-id.
2943 SemaRef.LookupQualifiedName(Previous, DC);
2944
2945 // Instantiate the explicit template arguments.
2946 TemplateArgumentListInfo ExplicitArgs(ArgsWritten->getLAngleLoc(),
2947 ArgsWritten->getRAngleLoc());
2948 if (SemaRef.SubstTemplateArguments(ArgsWritten->arguments(), TemplateArgs,
2949 ExplicitArgs))
2950 return nullptr;
2951
2952 if (SemaRef.CheckFunctionTemplateSpecialization(Function,
2953 &ExplicitArgs,
2954 Previous))
2955 Function->setInvalidDecl();
2956
2957 IsExplicitSpecialization = true;
2958 } else if (TemplateParams || !FunctionTemplate) {
2959 // Look only into the namespace where the friend would be declared to
2960 // find a previous declaration. This is the innermost enclosing namespace,
2961 // as described in ActOnFriendFunctionDecl.
2962 SemaRef.LookupQualifiedName(Previous, DC->getRedeclContext());
2963
2964 // In C++, the previous declaration we find might be a tag type
2965 // (class or enum). In this case, the new declaration will hide the
2966 // tag type. Note that this does not apply if we're declaring a
2967 // typedef (C++ [dcl.typedef]p4).
2968 if (Previous.isSingleTagDecl())
2969 Previous.clear();
2970
2971 // Filter out previous declarations that don't match the scope. The only
2972 // effect this has is to remove declarations found in inline namespaces
2973 // for friend declarations with unqualified names.
2974 if (isFriend && !QualifierLoc) {
2975 SemaRef.FilterLookupForScope(Previous, DC, /*Scope=*/ nullptr,
2976 /*ConsiderLinkage=*/ true,
2977 QualifierLoc.hasQualifier());
2978 }
2979 }
2980
2981 // Per [temp.inst], default arguments in function declarations at local scope
2982 // are instantiated along with the enclosing declaration. For example:
2983 //
2984 // template<typename T>
2985 // void ft() {
2986 // void f(int = []{ return T::value; }());
2987 // }
2988 // template void ft<int>(); // error: type 'int' cannot be used prior
2989 // to '::' because it has no members
2990 //
2991 // The error is issued during instantiation of ft<int>() because substitution
2992 // into the default argument fails; the default argument is instantiated even
2993 // though it is never used.
2994 if (Function->isLocalExternDecl()) {
2995 for (ParmVarDecl *PVD : Function->parameters()) {
2996 if (!PVD->hasDefaultArg())
2997 continue;
2998 if (SemaRef.SubstDefaultArgument(D->getInnerLocStart(), PVD, TemplateArgs)) {
2999 // If substitution fails, the default argument is set to a
3000 // RecoveryExpr that wraps the uninstantiated default argument so
3001 // that downstream diagnostics are omitted.
3002 Expr *UninstExpr = PVD->getUninstantiatedDefaultArg();
3003 ExprResult ErrorResult = SemaRef.CreateRecoveryExpr(
3004 UninstExpr->getBeginLoc(), UninstExpr->getEndLoc(),
3005 { UninstExpr }, UninstExpr->getType());
3006 if (ErrorResult.isUsable())
3007 PVD->setDefaultArg(ErrorResult.get());
3008 }
3009 }
3010 }
3011
3012 SemaRef.CheckFunctionDeclaration(/*Scope*/ nullptr, Function, Previous,
3013 IsExplicitSpecialization,
3014 Function->isThisDeclarationADefinition());
3015
3016 // Check the template parameter list against the previous declaration. The
3017 // goal here is to pick up default arguments added since the friend was
3018 // declared; we know the template parameter lists match, since otherwise
3019 // we would not have picked this template as the previous declaration.
3020 if (isFriend && TemplateParams && FunctionTemplate->getPreviousDecl()) {
3021 SemaRef.CheckTemplateParameterList(
3022 TemplateParams,
3023 FunctionTemplate->getPreviousDecl()->getTemplateParameters(),
3024 Function->isThisDeclarationADefinition()
3027 }
3028
3029 // If we're introducing a friend definition after the first use, trigger
3030 // instantiation.
3031 // FIXME: If this is a friend function template definition, we should check
3032 // to see if any specializations have been used.
3033 if (isFriend && D->isThisDeclarationADefinition() && Function->isUsed(false)) {
3034 if (MemberSpecializationInfo *MSInfo =
3035 Function->getMemberSpecializationInfo()) {
3036 if (MSInfo->getPointOfInstantiation().isInvalid()) {
3037 SourceLocation Loc = D->getLocation(); // FIXME
3038 MSInfo->setPointOfInstantiation(Loc);
3039 SemaRef.PendingLocalImplicitInstantiations.emplace_back(Function, Loc);
3040 }
3041 }
3042 }
3043
3044 if (D->isExplicitlyDefaulted()) {
3046 return nullptr;
3047 }
3048 if (D->isDeleted())
3049 SemaRef.SetDeclDeleted(Function, D->getLocation(), D->getDeletedMessage());
3050
3051 NamedDecl *PrincipalDecl =
3052 (TemplateParams ? cast<NamedDecl>(FunctionTemplate) : Function);
3053
3054 // If this declaration lives in a different context from its lexical context,
3055 // add it to the corresponding lookup table.
3056 if (isFriend ||
3057 (Function->isLocalExternDecl() && !Function->getPreviousDecl()))
3058 DC->makeDeclVisibleInContext(PrincipalDecl);
3059
3060 if (Function->isOverloadedOperator() && !DC->isRecord() &&
3062 PrincipalDecl->setNonMemberOperator();
3063
3064 return Function;
3065}
3066
3068 CXXMethodDecl *D, TemplateParameterList *TemplateParams,
3069 RewriteKind FunctionRewriteKind) {
3071 if (FunctionTemplate && !TemplateParams) {
3072 // We are creating a function template specialization from a function
3073 // template. Check whether there is already a function template
3074 // specialization for this particular set of template arguments.
3075 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
3076
3077 void *InsertPos = nullptr;
3078 FunctionDecl *SpecFunc
3079 = FunctionTemplate->findSpecialization(Innermost, InsertPos);
3080
3081 // If we already have a function template specialization, return it.
3082 if (SpecFunc)
3083 return SpecFunc;
3084 }
3085
3086 bool isFriend;
3087 if (FunctionTemplate)
3088 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
3089 else
3090 isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
3091
3092 bool MergeWithParentScope = (TemplateParams != nullptr) ||
3093 !(isa<Decl>(Owner) &&
3094 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
3095 LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
3096
3098 SemaRef, D, TemplateArgs, Scope);
3099
3100 // Instantiate enclosing template arguments for friends.
3102 unsigned NumTempParamLists = 0;
3103 if (isFriend && (NumTempParamLists = D->getNumTemplateParameterLists())) {
3104 TempParamLists.resize(NumTempParamLists);
3105 for (unsigned I = 0; I != NumTempParamLists; ++I) {
3107 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
3108 if (!InstParams)
3109 return nullptr;
3110 TempParamLists[I] = InstParams;
3111 }
3112 }
3113
3114 auto InstantiatedExplicitSpecifier = ExplicitSpecifier::getFromDecl(D);
3115 // deduction guides need this
3116 const bool CouldInstantiate =
3117 InstantiatedExplicitSpecifier.getExpr() == nullptr ||
3118 !InstantiatedExplicitSpecifier.getExpr()->isValueDependent();
3119
3120 // Delay the instantiation of the explicit-specifier until after the
3121 // constraints are checked during template argument deduction.
3122 if (CouldInstantiate ||
3123 SemaRef.CodeSynthesisContexts.back().Kind !=
3125 InstantiatedExplicitSpecifier = SemaRef.instantiateExplicitSpecifier(
3126 TemplateArgs, InstantiatedExplicitSpecifier);
3127
3128 if (InstantiatedExplicitSpecifier.isInvalid())
3129 return nullptr;
3130 } else {
3131 InstantiatedExplicitSpecifier.setKind(ExplicitSpecKind::Unresolved);
3132 }
3133
3134 // Implicit destructors/constructors created for local classes in
3135 // DeclareImplicit* (see SemaDeclCXX.cpp) might not have an associated TSI.
3136 // Unfortunately there isn't enough context in those functions to
3137 // conditionally populate the TSI without breaking non-template related use
3138 // cases. Populate TSIs prior to calling SubstFunctionType to make sure we get
3139 // a proper transformation.
3140 if (isLambdaMethod(D) && !D->getTypeSourceInfo() &&
3142 TypeSourceInfo *TSI =
3143 SemaRef.Context.getTrivialTypeSourceInfo(D->getType());
3144 D->setTypeSourceInfo(TSI);
3145 }
3146
3148 TypeSourceInfo *TInfo = SubstFunctionType(D, Params);
3149 if (!TInfo)
3150 return nullptr;
3151 QualType T = adjustFunctionTypeForInstantiation(SemaRef.Context, D, TInfo);
3152
3153 if (TemplateParams && TemplateParams->size()) {
3154 auto *LastParam =
3155 dyn_cast<TemplateTypeParmDecl>(TemplateParams->asArray().back());
3156 if (LastParam && LastParam->isImplicit() &&
3157 LastParam->hasTypeConstraint()) {
3158 // In abbreviated templates, the type-constraints of invented template
3159 // type parameters are instantiated with the function type, invalidating
3160 // the TemplateParameterList which relied on the template type parameter
3161 // not having a type constraint. Recreate the TemplateParameterList with
3162 // the updated parameter list.
3163 TemplateParams = TemplateParameterList::Create(
3164 SemaRef.Context, TemplateParams->getTemplateLoc(),
3165 TemplateParams->getLAngleLoc(), TemplateParams->asArray(),
3166 TemplateParams->getRAngleLoc(), TemplateParams->getRequiresClause());
3167 }
3168 }
3169
3170 NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
3171 if (QualifierLoc) {
3172 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
3173 TemplateArgs);
3174 if (!QualifierLoc)
3175 return nullptr;
3176 }
3177
3178 DeclContext *DC = Owner;
3179 if (isFriend) {
3180 if (QualifierLoc) {
3181 CXXScopeSpec SS;
3182 SS.Adopt(QualifierLoc);
3183 DC = SemaRef.computeDeclContext(SS);
3184
3185 if (DC && SemaRef.RequireCompleteDeclContext(SS, DC))
3186 return nullptr;
3187 } else {
3188 DC = SemaRef.FindInstantiatedContext(D->getLocation(),
3189 D->getDeclContext(),
3190 TemplateArgs);
3191 }
3192 if (!DC) return nullptr;
3193 }
3194
3196 AssociatedConstraint TrailingRequiresClause = D->getTrailingRequiresClause();
3197
3198 DeclarationNameInfo NameInfo
3199 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
3200
3201 if (FunctionRewriteKind != RewriteKind::None)
3202 adjustForRewrite(FunctionRewriteKind, D, T, TInfo, NameInfo);
3203
3204 // Build the instantiated method declaration.
3205 CXXMethodDecl *Method = nullptr;
3206
3207 SourceLocation StartLoc = D->getInnerLocStart();
3208 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
3210 SemaRef.Context, Record, StartLoc, NameInfo, T, TInfo,
3211 InstantiatedExplicitSpecifier, Constructor->UsesFPIntrin(),
3212 Constructor->isInlineSpecified(), false,
3213 Constructor->getConstexprKind(), InheritedConstructor(),
3214 TrailingRequiresClause);
3215 Method->setRangeEnd(Constructor->getEndLoc());
3216 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
3218 SemaRef.Context, Record, StartLoc, NameInfo, T, TInfo,
3219 Destructor->UsesFPIntrin(), Destructor->isInlineSpecified(), false,
3220 Destructor->getConstexprKind(), TrailingRequiresClause);
3221 Method->setIneligibleOrNotSelected(true);
3222 Method->setRangeEnd(Destructor->getEndLoc());
3223 Method->setDeclName(SemaRef.Context.DeclarationNames.getCXXDestructorName(
3224
3225 SemaRef.Context.getCanonicalTagType(Record)));
3226 } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) {
3228 SemaRef.Context, Record, StartLoc, NameInfo, T, TInfo,
3229 Conversion->UsesFPIntrin(), Conversion->isInlineSpecified(),
3230 InstantiatedExplicitSpecifier, Conversion->getConstexprKind(),
3231 Conversion->getEndLoc(), TrailingRequiresClause);
3232 } else {
3233 StorageClass SC = D->isStatic() ? SC_Static : SC_None;
3235 SemaRef.Context, Record, StartLoc, NameInfo, T, TInfo, SC,
3237 D->getEndLoc(), TrailingRequiresClause);
3238 }
3239
3240 if (D->isInlined())
3241 Method->setImplicitlyInline();
3242
3243 if (QualifierLoc)
3244 Method->setQualifierInfo(QualifierLoc);
3245
3246 if (TemplateParams) {
3247 // Our resulting instantiation is actually a function template, since we
3248 // are substituting only the outer template parameters. For example, given
3249 //
3250 // template<typename T>
3251 // struct X {
3252 // template<typename U> void f(T, U);
3253 // };
3254 //
3255 // X<int> x;
3256 //
3257 // We are instantiating the member template "f" within X<int>, which means
3258 // substituting int for T, but leaving "f" as a member function template.
3259 // Build the function template itself.
3261 Method->getLocation(),
3262 Method->getDeclName(),
3263 TemplateParams, Method);
3264 if (isFriend) {
3265 FunctionTemplate->setLexicalDeclContext(Owner);
3266 FunctionTemplate->setObjectOfFriendDecl();
3267 } else if (D->isOutOfLine())
3268 FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
3269 Method->setDescribedFunctionTemplate(FunctionTemplate);
3270 } else if (FunctionTemplate) {
3271 // Record this function template specialization.
3272 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
3273 Method->setFunctionTemplateSpecialization(FunctionTemplate,
3274 TemplateArgumentList::CreateCopy(SemaRef.Context,
3275 Innermost),
3276 /*InsertPos=*/nullptr);
3277 } else if (!isFriend && FunctionRewriteKind == RewriteKind::None) {
3278 // Record that this is an instantiation of a member function.
3279 Method->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
3280 }
3281
3282 // If we are instantiating a member function defined
3283 // out-of-line, the instantiation will have the same lexical
3284 // context (which will be a namespace scope) as the template.
3285 if (isFriend) {
3286 if (NumTempParamLists)
3287 Method->setTemplateParameterListsInfo(
3288 SemaRef.Context,
3289 llvm::ArrayRef(TempParamLists.data(), NumTempParamLists));
3290
3291 Method->setLexicalDeclContext(Owner);
3292 Method->setObjectOfFriendDecl();
3293 } else if (D->isOutOfLine())
3294 Method->setLexicalDeclContext(D->getLexicalDeclContext());
3295
3296 // Attach the parameters
3297 for (unsigned P = 0; P < Params.size(); ++P)
3298 Params[P]->setOwningFunction(Method);
3299 Method->setParams(Params);
3300
3302 Method->setInvalidDecl();
3303
3306
3307 bool IsExplicitSpecialization = false;
3308
3309 // If the name of this function was written as a template-id, instantiate
3310 // the explicit template arguments.
3313 // Instantiate the explicit template arguments.
3314 TemplateArgumentListInfo ExplicitArgs;
3315 if (const auto *ArgsWritten = DFTSI->TemplateArgumentsAsWritten) {
3316 ExplicitArgs.setLAngleLoc(ArgsWritten->getLAngleLoc());
3317 ExplicitArgs.setRAngleLoc(ArgsWritten->getRAngleLoc());
3318 if (SemaRef.SubstTemplateArguments(ArgsWritten->arguments(), TemplateArgs,
3319 ExplicitArgs))
3320 return nullptr;
3321 }
3322
3323 // Map the candidates for the primary template to their instantiations.
3324 for (FunctionTemplateDecl *FTD : DFTSI->getCandidates()) {
3325 if (NamedDecl *ND =
3326 SemaRef.FindInstantiatedDecl(D->getLocation(), FTD, TemplateArgs))
3327 Previous.addDecl(ND);
3328 else
3329 return nullptr;
3330 }
3331
3332 if (SemaRef.CheckFunctionTemplateSpecialization(
3333 Method, DFTSI->TemplateArgumentsAsWritten ? &ExplicitArgs : nullptr,
3334 Previous))
3335 Method->setInvalidDecl();
3336
3337 IsExplicitSpecialization = true;
3338 } else if (const ASTTemplateArgumentListInfo *ArgsWritten =
3340 SemaRef.LookupQualifiedName(Previous, DC);
3341
3342 TemplateArgumentListInfo ExplicitArgs(ArgsWritten->getLAngleLoc(),
3343 ArgsWritten->getRAngleLoc());
3344
3345 if (SemaRef.SubstTemplateArguments(ArgsWritten->arguments(), TemplateArgs,
3346 ExplicitArgs))
3347 return nullptr;
3348
3349 if (SemaRef.CheckFunctionTemplateSpecialization(Method,
3350 &ExplicitArgs,
3351 Previous))
3352 Method->setInvalidDecl();
3353
3354 IsExplicitSpecialization = true;
3355 } else if (!FunctionTemplate || TemplateParams || isFriend) {
3356 SemaRef.LookupQualifiedName(Previous, Record);
3357
3358 // In C++, the previous declaration we find might be a tag type
3359 // (class or enum). In this case, the new declaration will hide the
3360 // tag type. Note that this does not apply if we're declaring a
3361 // typedef (C++ [dcl.typedef]p4).
3362 if (Previous.isSingleTagDecl())
3363 Previous.clear();
3364 }
3365
3366 // Per [temp.inst], default arguments in member functions of local classes
3367 // are instantiated along with the member function declaration. For example:
3368 //
3369 // template<typename T>
3370 // void ft() {
3371 // struct lc {
3372 // int operator()(int p = []{ return T::value; }());
3373 // };
3374 // }
3375 // template void ft<int>(); // error: type 'int' cannot be used prior
3376 // to '::'because it has no members
3377 //
3378 // The error is issued during instantiation of ft<int>()::lc::operator()
3379 // because substitution into the default argument fails; the default argument
3380 // is instantiated even though it is never used.
3382 for (unsigned P = 0; P < Params.size(); ++P) {
3383 if (!Params[P]->hasDefaultArg())
3384 continue;
3385 if (SemaRef.SubstDefaultArgument(StartLoc, Params[P], TemplateArgs)) {
3386 // If substitution fails, the default argument is set to a
3387 // RecoveryExpr that wraps the uninstantiated default argument so
3388 // that downstream diagnostics are omitted.
3389 Expr *UninstExpr = Params[P]->getUninstantiatedDefaultArg();
3390 ExprResult ErrorResult = SemaRef.CreateRecoveryExpr(
3391 UninstExpr->getBeginLoc(), UninstExpr->getEndLoc(),
3392 { UninstExpr }, UninstExpr->getType());
3393 if (ErrorResult.isUsable())
3394 Params[P]->setDefaultArg(ErrorResult.get());
3395 }
3396 }
3397 }
3398
3399 SemaRef.CheckFunctionDeclaration(nullptr, Method, Previous,
3400 IsExplicitSpecialization,
3401 Method->isThisDeclarationADefinition());
3402
3403 if (D->isPureVirtual())
3404 SemaRef.CheckPureMethod(Method, SourceRange());
3405
3406 // Propagate access. For a non-friend declaration, the access is
3407 // whatever we're propagating from. For a friend, it should be the
3408 // previous declaration we just found.
3409 if (isFriend && Method->getPreviousDecl())
3410 Method->setAccess(Method->getPreviousDecl()->getAccess());
3411 else
3412 Method->setAccess(D->getAccess());
3413 if (FunctionTemplate)
3414 FunctionTemplate->setAccess(Method->getAccess());
3415
3416 SemaRef.CheckOverrideControl(Method);
3417
3418 // If a function is defined as defaulted or deleted, mark it as such now.
3419 if (D->isExplicitlyDefaulted()) {
3421 return nullptr;
3422 }
3423 if (D->isDeletedAsWritten())
3424 SemaRef.SetDeclDeleted(Method, Method->getLocation(),
3425 D->getDeletedMessage());
3426
3427 // If this is an explicit specialization, mark the implicitly-instantiated
3428 // template specialization as being an explicit specialization too.
3429 // FIXME: Is this necessary?
3430 if (IsExplicitSpecialization && !isFriend)
3431 SemaRef.CompleteMemberSpecialization(Method, Previous);
3432
3433 // If the method is a special member function, we need to mark it as
3434 // ineligible so that Owner->addDecl() won't mark the class as non trivial.
3435 // At the end of the class instantiation, we calculate eligibility again and
3436 // then we adjust trivility if needed.
3437 // We need this check to happen only after the method parameters are set,
3438 // because being e.g. a copy constructor depends on the instantiated
3439 // arguments.
3440 if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Method)) {
3441 if (Constructor->isDefaultConstructor() ||
3442 Constructor->isCopyOrMoveConstructor())
3443 Method->setIneligibleOrNotSelected(true);
3444 } else if (Method->isCopyAssignmentOperator() ||
3445 Method->isMoveAssignmentOperator()) {
3446 Method->setIneligibleOrNotSelected(true);
3447 }
3448
3449 // If there's a function template, let our caller handle it.
3450 if (FunctionTemplate) {
3451 // do nothing
3452
3453 // Don't hide a (potentially) valid declaration with an invalid one.
3454 } else if (Method->isInvalidDecl() && !Previous.empty()) {
3455 // do nothing
3456
3457 // Otherwise, check access to friends and make them visible.
3458 } else if (isFriend) {
3459 // We only need to re-check access for methods which we didn't
3460 // manage to match during parsing.
3461 if (!D->getPreviousDecl())
3462 SemaRef.CheckFriendAccess(Method);
3463
3464 Record->makeDeclVisibleInContext(Method);
3465
3466 // Otherwise, add the declaration. We don't need to do this for
3467 // class-scope specializations because we'll have matched them with
3468 // the appropriate template.
3469 } else {
3470 Owner->addDecl(Method);
3471 }
3472
3473 // PR17480: Honor the used attribute to instantiate member function
3474 // definitions
3475 if (Method->hasAttr<UsedAttr>()) {
3476 if (const auto *A = dyn_cast<CXXRecordDecl>(Owner)) {
3477 SourceLocation Loc;
3478 if (const MemberSpecializationInfo *MSInfo =
3479 A->getMemberSpecializationInfo())
3480 Loc = MSInfo->getPointOfInstantiation();
3481 else if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(A))
3482 Loc = Spec->getPointOfInstantiation();
3483 SemaRef.MarkFunctionReferenced(Loc, Method);
3484 }
3485 }
3486
3487 return Method;
3488}
3489
3490Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
3491 return VisitCXXMethodDecl(D);
3492}
3493
3494Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
3495 return VisitCXXMethodDecl(D);
3496}
3497
3498Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
3499 return VisitCXXMethodDecl(D);
3500}
3501
3502Decl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
3503 return SemaRef.SubstParmVarDecl(D, TemplateArgs, /*indexAdjustment*/ 0,
3504 std::nullopt,
3505 /*ExpectParameterPack=*/false);
3506}
3507
3508Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl(
3510 assert(D->getTypeForDecl()->isTemplateTypeParmType());
3511
3512 UnsignedOrNone NumExpanded = std::nullopt;
3513
3514 if (const TypeConstraint *TC = D->getTypeConstraint()) {
3515 if (D->isPackExpansion() && !D->getNumExpansionParameters()) {
3516 assert(TC->getTemplateArgsAsWritten() &&
3517 "type parameter can only be an expansion when explicit arguments "
3518 "are specified");
3519 // The template type parameter pack's type is a pack expansion of types.
3520 // Determine whether we need to expand this parameter pack into separate
3521 // types.
3522 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
3523 for (auto &ArgLoc : TC->getTemplateArgsAsWritten()->arguments())
3524 SemaRef.collectUnexpandedParameterPacks(ArgLoc, Unexpanded);
3525
3526 // Determine whether the set of unexpanded parameter packs can and should
3527 // be expanded.
3528 bool Expand = true;
3529 bool RetainExpansion = false;
3530 if (SemaRef.CheckParameterPacksForExpansion(
3531 cast<CXXFoldExpr>(TC->getImmediatelyDeclaredConstraint())
3532 ->getEllipsisLoc(),
3533 SourceRange(TC->getConceptNameLoc(),
3534 TC->hasExplicitTemplateArgs()
3535 ? TC->getTemplateArgsAsWritten()->getRAngleLoc()
3536 : TC->getConceptNameInfo().getEndLoc()),
3537 Unexpanded, TemplateArgs, /*FailOnPackProducingTemplates=*/true,
3538 Expand, RetainExpansion, NumExpanded))
3539 return nullptr;
3540 }
3541 }
3542
3543 TemplateTypeParmDecl *Inst = TemplateTypeParmDecl::Create(
3544 SemaRef.Context, Owner, D->getBeginLoc(), D->getLocation(),
3545 D->getDepth() - TemplateArgs.getNumSubstitutedLevels(), D->getIndex(),
3547 D->hasTypeConstraint(), NumExpanded);
3548
3549 Inst->setAccess(AS_public);
3550 Inst->setImplicit(D->isImplicit());
3551 if (auto *TC = D->getTypeConstraint()) {
3552 if (!D->isImplicit()) {
3553 // Invented template parameter type constraints will be instantiated
3554 // with the corresponding auto-typed parameter as it might reference
3555 // other parameters.
3556 if (SemaRef.SubstTypeConstraint(Inst, TC, TemplateArgs,
3557 EvaluateConstraints))
3558 return nullptr;
3559 }
3560 }
3562 TemplateArgumentLoc Output;
3563 if (!SemaRef.SubstTemplateArgument(D->getDefaultArgument(), TemplateArgs,
3564 Output))
3565 Inst->setDefaultArgument(SemaRef.getASTContext(), Output);
3566 }
3567
3568 // Introduce this template parameter's instantiation into the instantiation
3569 // scope.
3570 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst);
3571
3572 return Inst;
3573}
3574
3575Decl *TemplateDeclInstantiator::VisitNonTypeTemplateParmDecl(
3577 // Substitute into the type of the non-type template parameter.
3578 TypeLoc TL = D->getTypeSourceInfo()->getTypeLoc();
3579 SmallVector<TypeSourceInfo *, 4> ExpandedParameterPackTypesAsWritten;
3580 SmallVector<QualType, 4> ExpandedParameterPackTypes;
3581 bool IsExpandedParameterPack = false;
3582 TypeSourceInfo *TSI;
3583 QualType T;
3584 bool Invalid = false;
3585
3586 if (D->isExpandedParameterPack()) {
3587 // The non-type template parameter pack is an already-expanded pack
3588 // expansion of types. Substitute into each of the expanded types.
3589 ExpandedParameterPackTypes.reserve(D->getNumExpansionTypes());
3590 ExpandedParameterPackTypesAsWritten.reserve(D->getNumExpansionTypes());
3591 for (unsigned I = 0, N = D->getNumExpansionTypes(); I != N; ++I) {
3592 TypeSourceInfo *NewTSI =
3593 SemaRef.SubstType(D->getExpansionTypeSourceInfo(I), TemplateArgs,
3594 D->getLocation(), D->getDeclName());
3595 if (!NewTSI)
3596 return nullptr;
3597
3598 QualType NewT =
3599 SemaRef.CheckNonTypeTemplateParameterType(NewTSI, D->getLocation());
3600 if (NewT.isNull())
3601 return nullptr;
3602
3603 ExpandedParameterPackTypesAsWritten.push_back(NewTSI);
3604 ExpandedParameterPackTypes.push_back(NewT);
3605 }
3606
3607 IsExpandedParameterPack = true;
3608 TSI = D->getTypeSourceInfo();
3609 T = TSI->getType();
3610 } else if (D->isPackExpansion()) {
3611 // The non-type template parameter pack's type is a pack expansion of types.
3612 // Determine whether we need to expand this parameter pack into separate
3613 // types.
3614 PackExpansionTypeLoc Expansion = TL.castAs<PackExpansionTypeLoc>();
3615 TypeLoc Pattern = Expansion.getPatternLoc();
3616 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
3617 SemaRef.collectUnexpandedParameterPacks(Pattern, Unexpanded);
3618
3619 // Determine whether the set of unexpanded parameter packs can and should
3620 // be expanded.
3621 bool Expand = true;
3622 bool RetainExpansion = false;
3623 UnsignedOrNone OrigNumExpansions =
3624 Expansion.getTypePtr()->getNumExpansions();
3625 UnsignedOrNone NumExpansions = OrigNumExpansions;
3626 if (SemaRef.CheckParameterPacksForExpansion(
3627 Expansion.getEllipsisLoc(), Pattern.getSourceRange(), Unexpanded,
3628 TemplateArgs, /*FailOnPackProducingTemplates=*/true, Expand,
3629 RetainExpansion, NumExpansions))
3630 return nullptr;
3631
3632 if (Expand) {
3633 for (unsigned I = 0; I != *NumExpansions; ++I) {
3634 Sema::ArgPackSubstIndexRAII SubstIndex(SemaRef, I);
3635 TypeSourceInfo *NewTSI = SemaRef.SubstType(
3636 Pattern, TemplateArgs, D->getLocation(), D->getDeclName());
3637 if (!NewTSI)
3638 return nullptr;
3639
3640 QualType NewT =
3641 SemaRef.CheckNonTypeTemplateParameterType(NewTSI, D->getLocation());
3642 if (NewT.isNull())
3643 return nullptr;
3644
3645 ExpandedParameterPackTypesAsWritten.push_back(NewTSI);
3646 ExpandedParameterPackTypes.push_back(NewT);
3647 }
3648
3649 // Note that we have an expanded parameter pack. The "type" of this
3650 // expanded parameter pack is the original expansion type, but callers
3651 // will end up using the expanded parameter pack types for type-checking.
3652 IsExpandedParameterPack = true;
3653 TSI = D->getTypeSourceInfo();
3654 T = TSI->getType();
3655 } else {
3656 // We cannot fully expand the pack expansion now, so substitute into the
3657 // pattern and create a new pack expansion type.
3658 Sema::ArgPackSubstIndexRAII SubstIndex(SemaRef, std::nullopt);
3659 TypeSourceInfo *NewPattern = SemaRef.SubstType(Pattern, TemplateArgs,
3660 D->getLocation(),
3661 D->getDeclName());
3662 if (!NewPattern)
3663 return nullptr;
3664
3665 SemaRef.CheckNonTypeTemplateParameterType(NewPattern, D->getLocation());
3666 TSI = SemaRef.CheckPackExpansion(NewPattern, Expansion.getEllipsisLoc(),
3667 NumExpansions);
3668 if (!TSI)
3669 return nullptr;
3670
3671 T = TSI->getType();
3672 }
3673 } else {
3674 // Simple case: substitution into a parameter that is not a parameter pack.
3675 TSI = SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs,
3676 D->getLocation(), D->getDeclName());
3677 if (!TSI)
3678 return nullptr;
3679
3680 // Check that this type is acceptable for a non-type template parameter.
3681 T = SemaRef.CheckNonTypeTemplateParameterType(TSI, D->getLocation());
3682 if (T.isNull()) {
3683 T = SemaRef.Context.IntTy;
3684 Invalid = true;
3685 }
3686 }
3687
3688 NonTypeTemplateParmDecl *Param;
3689 if (IsExpandedParameterPack)
3691 SemaRef.Context, Owner, D->getInnerLocStart(), D->getLocation(),
3692 D->getDepth() - TemplateArgs.getNumSubstitutedLevels(),
3693 D->getPosition(), D->getIdentifier(), T, TSI,
3694 ExpandedParameterPackTypes, ExpandedParameterPackTypesAsWritten);
3695 else
3697 SemaRef.Context, Owner, D->getInnerLocStart(), D->getLocation(),
3698 D->getDepth() - TemplateArgs.getNumSubstitutedLevels(),
3699 D->getPosition(), D->getIdentifier(), T, D->isParameterPack(), TSI);
3700
3701 if (AutoTypeLoc AutoLoc = TSI->getTypeLoc().getContainedAutoTypeLoc())
3702 if (AutoLoc.isConstrained()) {
3703 SourceLocation EllipsisLoc;
3704 if (IsExpandedParameterPack)
3705 EllipsisLoc =
3706 TSI->getTypeLoc().getAs<PackExpansionTypeLoc>().getEllipsisLoc();
3707 else if (auto *Constraint = dyn_cast_if_present<CXXFoldExpr>(
3709 EllipsisLoc = Constraint->getEllipsisLoc();
3710 // Note: We attach the uninstantiated constriant here, so that it can be
3711 // instantiated relative to the top level, like all our other
3712 // constraints.
3713 if (SemaRef.AttachTypeConstraint(AutoLoc, /*NewConstrainedParm=*/Param,
3714 /*OrigConstrainedParm=*/D, EllipsisLoc))
3715 Invalid = true;
3716 }
3717
3718 Param->setAccess(AS_public);
3719 Param->setImplicit(D->isImplicit());
3720 if (Invalid)
3721 Param->setInvalidDecl();
3722
3724 EnterExpressionEvaluationContext ConstantEvaluated(
3726 TemplateArgumentLoc Result;
3727 if (!SemaRef.SubstTemplateArgument(D->getDefaultArgument(), TemplateArgs,
3728 Result))
3729 Param->setDefaultArgument(SemaRef.Context, Result);
3730 }
3731
3732 // Introduce this template parameter's instantiation into the instantiation
3733 // scope.
3734 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
3735 return Param;
3736}
3737
3739 Sema &S,
3740 TemplateParameterList *Params,
3742 for (const auto &P : *Params) {
3743 if (P->isTemplateParameterPack())
3744 continue;
3745 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P))
3746 S.collectUnexpandedParameterPacks(NTTP->getTypeSourceInfo()->getTypeLoc(),
3747 Unexpanded);
3748 if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(P))
3749 collectUnexpandedParameterPacks(S, TTP->getTemplateParameters(),
3750 Unexpanded);
3751 }
3752}
3753
3754Decl *
3755TemplateDeclInstantiator::VisitTemplateTemplateParmDecl(
3757 // Instantiate the template parameter list of the template template parameter.
3758 TemplateParameterList *TempParams = D->getTemplateParameters();
3759 TemplateParameterList *InstParams;
3760 SmallVector<TemplateParameterList*, 8> ExpandedParams;
3761
3762 bool IsExpandedParameterPack = false;
3763
3764 if (D->isExpandedParameterPack()) {
3765 // The template template parameter pack is an already-expanded pack
3766 // expansion of template parameters. Substitute into each of the expanded
3767 // parameters.
3768 ExpandedParams.reserve(D->getNumExpansionTemplateParameters());
3769 for (unsigned I = 0, N = D->getNumExpansionTemplateParameters();
3770 I != N; ++I) {
3771 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
3772 TemplateParameterList *Expansion =
3774 if (!Expansion)
3775 return nullptr;
3776 ExpandedParams.push_back(Expansion);
3777 }
3778
3779 IsExpandedParameterPack = true;
3780 InstParams = TempParams;
3781 } else if (D->isPackExpansion()) {
3782 // The template template parameter pack expands to a pack of template
3783 // template parameters. Determine whether we need to expand this parameter
3784 // pack into separate parameters.
3785 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
3787 Unexpanded);
3788
3789 // Determine whether the set of unexpanded parameter packs can and should
3790 // be expanded.
3791 bool Expand = true;
3792 bool RetainExpansion = false;
3793 UnsignedOrNone NumExpansions = std::nullopt;
3794 if (SemaRef.CheckParameterPacksForExpansion(
3795 D->getLocation(), TempParams->getSourceRange(), Unexpanded,
3796 TemplateArgs, /*FailOnPackProducingTemplates=*/true, Expand,
3797 RetainExpansion, NumExpansions))
3798 return nullptr;
3799
3800 if (Expand) {
3801 for (unsigned I = 0; I != *NumExpansions; ++I) {
3802 Sema::ArgPackSubstIndexRAII SubstIndex(SemaRef, I);
3803 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
3804 TemplateParameterList *Expansion = SubstTemplateParams(TempParams);
3805 if (!Expansion)
3806 return nullptr;
3807 ExpandedParams.push_back(Expansion);
3808 }
3809
3810 // Note that we have an expanded parameter pack. The "type" of this
3811 // expanded parameter pack is the original expansion type, but callers
3812 // will end up using the expanded parameter pack types for type-checking.
3813 IsExpandedParameterPack = true;
3814 }
3815
3816 Sema::ArgPackSubstIndexRAII SubstIndex(SemaRef, std::nullopt);
3817
3818 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
3819 InstParams = SubstTemplateParams(TempParams);
3820 if (!InstParams)
3821 return nullptr;
3822 } else {
3823 // Perform the actual substitution of template parameters within a new,
3824 // local instantiation scope.
3825 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
3826 InstParams = SubstTemplateParams(TempParams);
3827 if (!InstParams)
3828 return nullptr;
3829 }
3830
3831 // Build the template template parameter.
3832 TemplateTemplateParmDecl *Param;
3833 if (IsExpandedParameterPack)
3835 SemaRef.Context, Owner, D->getLocation(),
3836 D->getDepth() - TemplateArgs.getNumSubstitutedLevels(),
3838 D->wasDeclaredWithTypename(), InstParams, ExpandedParams);
3839 else
3841 SemaRef.Context, Owner, D->getLocation(),
3842 D->getDepth() - TemplateArgs.getNumSubstitutedLevels(),
3843 D->getPosition(), D->isParameterPack(), D->getIdentifier(),
3844 D->templateParameterKind(), D->wasDeclaredWithTypename(), InstParams);
3846 const TemplateArgumentLoc &A = D->getDefaultArgument();
3847 NestedNameSpecifierLoc QualifierLoc = A.getTemplateQualifierLoc();
3848 // FIXME: Pass in the template keyword location.
3849 TemplateName TName = SemaRef.SubstTemplateName(
3850 A.getTemplateKWLoc(), QualifierLoc, A.getArgument().getAsTemplate(),
3851 A.getTemplateNameLoc(), TemplateArgs);
3852 if (!TName.isNull())
3853 Param->setDefaultArgument(
3854 SemaRef.Context,
3855 TemplateArgumentLoc(SemaRef.Context, TemplateArgument(TName),
3856 A.getTemplateKWLoc(), QualifierLoc,
3857 A.getTemplateNameLoc()));
3858 }
3859 Param->setAccess(AS_public);
3860 Param->setImplicit(D->isImplicit());
3861
3862 // Introduce this template parameter's instantiation into the instantiation
3863 // scope.
3864 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
3865
3866 return Param;
3867}
3868
3869Decl *TemplateDeclInstantiator::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
3870 // Using directives are never dependent (and never contain any types or
3871 // expressions), so they require no explicit instantiation work.
3872
3873 UsingDirectiveDecl *Inst
3874 = UsingDirectiveDecl::Create(SemaRef.Context, Owner, D->getLocation(),
3876 D->getQualifierLoc(),
3877 D->getIdentLocation(),
3879 D->getCommonAncestor());
3880
3881 // Add the using directive to its declaration context
3882 // only if this is not a function or method.
3883 if (!Owner->isFunctionOrMethod())
3884 Owner->addDecl(Inst);
3885
3886 return Inst;
3887}
3888
3890 BaseUsingDecl *Inst,
3891 LookupResult *Lookup) {
3892
3893 bool isFunctionScope = Owner->isFunctionOrMethod();
3894
3895 for (auto *Shadow : D->shadows()) {
3896 // FIXME: UsingShadowDecl doesn't preserve its immediate target, so
3897 // reconstruct it in the case where it matters. Hm, can we extract it from
3898 // the DeclSpec when parsing and save it in the UsingDecl itself?
3899 NamedDecl *OldTarget = Shadow->getTargetDecl();
3900 if (auto *CUSD = dyn_cast<ConstructorUsingShadowDecl>(Shadow))
3901 if (auto *BaseShadow = CUSD->getNominatedBaseClassShadowDecl())
3902 OldTarget = BaseShadow;
3903
3904 NamedDecl *InstTarget = nullptr;
3905 if (auto *EmptyD =
3906 dyn_cast<UnresolvedUsingIfExistsDecl>(Shadow->getTargetDecl())) {
3908 SemaRef.Context, Owner, EmptyD->getLocation(), EmptyD->getDeclName());
3909 } else {
3910 InstTarget = cast_or_null<NamedDecl>(SemaRef.FindInstantiatedDecl(
3911 Shadow->getLocation(), OldTarget, TemplateArgs));
3912 }
3913 if (!InstTarget)
3914 return nullptr;
3915
3916 UsingShadowDecl *PrevDecl = nullptr;
3917 if (Lookup &&
3918 SemaRef.CheckUsingShadowDecl(Inst, InstTarget, *Lookup, PrevDecl))
3919 continue;
3920
3921 if (UsingShadowDecl *OldPrev = getPreviousDeclForInstantiation(Shadow))
3922 PrevDecl = cast_or_null<UsingShadowDecl>(SemaRef.FindInstantiatedDecl(
3923 Shadow->getLocation(), OldPrev, TemplateArgs));
3924
3925 UsingShadowDecl *InstShadow = SemaRef.BuildUsingShadowDecl(
3926 /*Scope*/ nullptr, Inst, InstTarget, PrevDecl);
3927 SemaRef.Context.setInstantiatedFromUsingShadowDecl(InstShadow, Shadow);
3928
3929 if (isFunctionScope)
3930 SemaRef.CurrentInstantiationScope->InstantiatedLocal(Shadow, InstShadow);
3931 }
3932
3933 return Inst;
3934}
3935
3936Decl *TemplateDeclInstantiator::VisitUsingDecl(UsingDecl *D) {
3937
3938 // The nested name specifier may be dependent, for example
3939 // template <typename T> struct t {
3940 // struct s1 { T f1(); };
3941 // struct s2 : s1 { using s1::f1; };
3942 // };
3943 // template struct t<int>;
3944 // Here, in using s1::f1, s1 refers to t<T>::s1;
3945 // we need to substitute for t<int>::s1.
3946 NestedNameSpecifierLoc QualifierLoc
3948 TemplateArgs);
3949 if (!QualifierLoc)
3950 return nullptr;
3951
3952 // For an inheriting constructor declaration, the name of the using
3953 // declaration is the name of a constructor in this class, not in the
3954 // base class.
3955 DeclarationNameInfo NameInfo = D->getNameInfo();
3957 if (auto *RD = dyn_cast<CXXRecordDecl>(SemaRef.CurContext))
3959 SemaRef.Context.getCanonicalTagType(RD)));
3960
3961 // We only need to do redeclaration lookups if we're in a class scope (in
3962 // fact, it's not really even possible in non-class scopes).
3963 bool CheckRedeclaration = Owner->isRecord();
3964 LookupResult Prev(SemaRef, NameInfo, Sema::LookupUsingDeclName,
3966
3967 UsingDecl *NewUD = UsingDecl::Create(SemaRef.Context, Owner,
3968 D->getUsingLoc(),
3969 QualifierLoc,
3970 NameInfo,
3971 D->hasTypename());
3972
3973 CXXScopeSpec SS;
3974 SS.Adopt(QualifierLoc);
3975 if (CheckRedeclaration) {
3976 Prev.setHideTags(false);
3977 SemaRef.LookupQualifiedName(Prev, Owner);
3978
3979 // Check for invalid redeclarations.
3981 D->hasTypename(), SS,
3982 D->getLocation(), Prev))
3983 NewUD->setInvalidDecl();
3984 }
3985
3986 if (!NewUD->isInvalidDecl() &&
3987 SemaRef.CheckUsingDeclQualifier(D->getUsingLoc(), D->hasTypename(), SS,
3988 NameInfo, D->getLocation(), nullptr, D))
3989 NewUD->setInvalidDecl();
3990
3991 SemaRef.Context.setInstantiatedFromUsingDecl(NewUD, D);
3992 NewUD->setAccess(D->getAccess());
3993 Owner->addDecl(NewUD);
3994
3995 // Don't process the shadow decls for an invalid decl.
3996 if (NewUD->isInvalidDecl())
3997 return NewUD;
3998
3999 // If the using scope was dependent, or we had dependent bases, we need to
4000 // recheck the inheritance
4003
4004 return VisitBaseUsingDecls(D, NewUD, CheckRedeclaration ? &Prev : nullptr);
4005}
4006
4007Decl *TemplateDeclInstantiator::VisitUsingEnumDecl(UsingEnumDecl *D) {
4008 // Cannot be a dependent type, but still could be an instantiation
4009 EnumDecl *EnumD = cast_or_null<EnumDecl>(SemaRef.FindInstantiatedDecl(
4010 D->getLocation(), D->getEnumDecl(), TemplateArgs));
4011
4012 if (SemaRef.RequireCompleteEnumDecl(EnumD, EnumD->getLocation()))
4013 return nullptr;
4014
4015 TypeSourceInfo *TSI = SemaRef.SubstType(D->getEnumType(), TemplateArgs,
4016 D->getLocation(), D->getDeclName());
4017
4018 if (!TSI)
4019 return nullptr;
4020
4021 UsingEnumDecl *NewUD =
4022 UsingEnumDecl::Create(SemaRef.Context, Owner, D->getUsingLoc(),
4023 D->getEnumLoc(), D->getLocation(), TSI);
4024
4025 SemaRef.Context.setInstantiatedFromUsingEnumDecl(NewUD, D);
4026 NewUD->setAccess(D->getAccess());
4027 Owner->addDecl(NewUD);
4028
4029 // Don't process the shadow decls for an invalid decl.
4030 if (NewUD->isInvalidDecl())
4031 return NewUD;
4032
4033 // We don't have to recheck for duplication of the UsingEnumDecl itself, as it
4034 // cannot be dependent, and will therefore have been checked during template
4035 // definition.
4036
4037 return VisitBaseUsingDecls(D, NewUD, nullptr);
4038}
4039
4040Decl *TemplateDeclInstantiator::VisitUsingShadowDecl(UsingShadowDecl *D) {
4041 // Ignore these; we handle them in bulk when processing the UsingDecl.
4042 return nullptr;
4043}
4044
4045Decl *TemplateDeclInstantiator::VisitConstructorUsingShadowDecl(
4047 // Ignore these; we handle them in bulk when processing the UsingDecl.
4048 return nullptr;
4049}
4050
4051template <typename T>
4052Decl *TemplateDeclInstantiator::instantiateUnresolvedUsingDecl(
4053 T *D, bool InstantiatingPackElement) {
4054 // If this is a pack expansion, expand it now.
4055 if (D->isPackExpansion() && !InstantiatingPackElement) {
4056 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
4057 SemaRef.collectUnexpandedParameterPacks(D->getQualifierLoc(), Unexpanded);
4058 SemaRef.collectUnexpandedParameterPacks(D->getNameInfo(), Unexpanded);
4059
4060 // Determine whether the set of unexpanded parameter packs can and should
4061 // be expanded.
4062 bool Expand = true;
4063 bool RetainExpansion = false;
4064 UnsignedOrNone NumExpansions = std::nullopt;
4065 if (SemaRef.CheckParameterPacksForExpansion(
4066 D->getEllipsisLoc(), D->getSourceRange(), Unexpanded, TemplateArgs,
4067 /*FailOnPackProducingTemplates=*/true, Expand, RetainExpansion,
4068 NumExpansions))
4069 return nullptr;
4070
4071 // This declaration cannot appear within a function template signature,
4072 // so we can't have a partial argument list for a parameter pack.
4073 assert(!RetainExpansion &&
4074 "should never need to retain an expansion for UsingPackDecl");
4075
4076 if (!Expand) {
4077 // We cannot fully expand the pack expansion now, so substitute into the
4078 // pattern and create a new pack expansion.
4079 Sema::ArgPackSubstIndexRAII SubstIndex(SemaRef, std::nullopt);
4080 return instantiateUnresolvedUsingDecl(D, true);
4081 }
4082
4083 // Within a function, we don't have any normal way to check for conflicts
4084 // between shadow declarations from different using declarations in the
4085 // same pack expansion, but this is always ill-formed because all expansions
4086 // must produce (conflicting) enumerators.
4087 //
4088 // Sadly we can't just reject this in the template definition because it
4089 // could be valid if the pack is empty or has exactly one expansion.
4090 if (D->getDeclContext()->isFunctionOrMethod() && *NumExpansions > 1) {
4091 SemaRef.Diag(D->getEllipsisLoc(),
4092 diag::err_using_decl_redeclaration_expansion);
4093 return nullptr;
4094 }
4095
4096 // Instantiate the slices of this pack and build a UsingPackDecl.
4097 SmallVector<NamedDecl*, 8> Expansions;
4098 for (unsigned I = 0; I != *NumExpansions; ++I) {
4099 Sema::ArgPackSubstIndexRAII SubstIndex(SemaRef, I);
4100 Decl *Slice = instantiateUnresolvedUsingDecl(D, true);
4101 if (!Slice)
4102 return nullptr;
4103 // Note that we can still get unresolved using declarations here, if we
4104 // had arguments for all packs but the pattern also contained other
4105 // template arguments (this only happens during partial substitution, eg
4106 // into the body of a generic lambda in a function template).
4107 Expansions.push_back(cast<NamedDecl>(Slice));
4108 }
4109
4110 auto *NewD = SemaRef.BuildUsingPackDecl(D, Expansions);
4111 if (isDeclWithinFunction(D))
4112 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewD);
4113 return NewD;
4114 }
4115
4116 UnresolvedUsingTypenameDecl *TD = dyn_cast<UnresolvedUsingTypenameDecl>(D);
4117 SourceLocation TypenameLoc = TD ? TD->getTypenameLoc() : SourceLocation();
4118
4119 NestedNameSpecifierLoc QualifierLoc
4120 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
4121 TemplateArgs);
4122 if (!QualifierLoc)
4123 return nullptr;
4124
4125 CXXScopeSpec SS;
4126 SS.Adopt(QualifierLoc);
4127
4128 DeclarationNameInfo NameInfo
4129 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
4130
4131 // Produce a pack expansion only if we're not instantiating a particular
4132 // slice of a pack expansion.
4133 bool InstantiatingSlice =
4134 D->getEllipsisLoc().isValid() && SemaRef.ArgPackSubstIndex;
4135 SourceLocation EllipsisLoc =
4136 InstantiatingSlice ? SourceLocation() : D->getEllipsisLoc();
4137
4138 bool IsUsingIfExists = D->template hasAttr<UsingIfExistsAttr>();
4139 NamedDecl *UD = SemaRef.BuildUsingDeclaration(
4140 /*Scope*/ nullptr, D->getAccess(), D->getUsingLoc(),
4141 /*HasTypename*/ TD, TypenameLoc, SS, NameInfo, EllipsisLoc,
4142 ParsedAttributesView(),
4143 /*IsInstantiation*/ true, IsUsingIfExists);
4144 if (UD) {
4145 SemaRef.InstantiateAttrs(TemplateArgs, D, UD);
4146 SemaRef.Context.setInstantiatedFromUsingDecl(UD, D);
4147 }
4148
4149 return UD;
4150}
4151
4152Decl *TemplateDeclInstantiator::VisitUnresolvedUsingTypenameDecl(
4154 return instantiateUnresolvedUsingDecl(D);
4155}
4156
4157Decl *TemplateDeclInstantiator::VisitUnresolvedUsingValueDecl(
4159 return instantiateUnresolvedUsingDecl(D);
4160}
4161
4162Decl *TemplateDeclInstantiator::VisitUnresolvedUsingIfExistsDecl(
4164 llvm_unreachable("referring to unresolved decl out of UsingShadowDecl");
4165}
4166
4167Decl *TemplateDeclInstantiator::VisitUsingPackDecl(UsingPackDecl *D) {
4168 SmallVector<NamedDecl*, 8> Expansions;
4169 for (auto *UD : D->expansions()) {
4170 if (NamedDecl *NewUD =
4171 SemaRef.FindInstantiatedDecl(D->getLocation(), UD, TemplateArgs))
4172 Expansions.push_back(NewUD);
4173 else
4174 return nullptr;
4175 }
4176
4177 auto *NewD = SemaRef.BuildUsingPackDecl(D, Expansions);
4178 if (isDeclWithinFunction(D))
4179 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewD);
4180 return NewD;
4181}
4182
4183Decl *TemplateDeclInstantiator::VisitOMPThreadPrivateDecl(
4185 SmallVector<Expr *, 5> Vars;
4186 for (auto *I : D->varlist()) {
4187 Expr *Var = SemaRef.SubstExpr(I, TemplateArgs).get();
4188 assert(isa<DeclRefExpr>(Var) && "threadprivate arg is not a DeclRefExpr");
4189 Vars.push_back(Var);
4190 }
4191
4192 OMPThreadPrivateDecl *TD =
4193 SemaRef.OpenMP().CheckOMPThreadPrivateDecl(D->getLocation(), Vars);
4194
4195 TD->setAccess(AS_public);
4196 Owner->addDecl(TD);
4197
4198 return TD;
4199}
4200
4201Decl *
4202TemplateDeclInstantiator::VisitOMPGroupPrivateDecl(OMPGroupPrivateDecl *D) {
4203 SmallVector<Expr *, 5> Vars;
4204 for (auto *I : D->varlist()) {
4205 Expr *Var = SemaRef.SubstExpr(I, TemplateArgs).get();
4206 assert(isa<DeclRefExpr>(Var) && "groupprivate arg is not a DeclRefExpr");
4207 Vars.push_back(Var);
4208 }
4209
4210 OMPGroupPrivateDecl *TD =
4211 SemaRef.OpenMP().CheckOMPGroupPrivateDecl(D->getLocation(), Vars);
4212
4213 TD->setAccess(AS_public);
4214 Owner->addDecl(TD);
4215
4216 return TD;
4217}
4218
4219Decl *TemplateDeclInstantiator::VisitOMPAllocateDecl(OMPAllocateDecl *D) {
4220 SmallVector<Expr *, 5> Vars;
4221 for (auto *I : D->varlist()) {
4222 Expr *Var = SemaRef.SubstExpr(I, TemplateArgs).get();
4223 assert(isa<DeclRefExpr>(Var) && "allocate arg is not a DeclRefExpr");
4224 Vars.push_back(Var);
4225 }
4226 SmallVector<OMPClause *, 4> Clauses;
4227 // Copy map clauses from the original mapper.
4228 for (OMPClause *C : D->clauselists()) {
4229 OMPClause *IC = nullptr;
4230 if (auto *AC = dyn_cast<OMPAllocatorClause>(C)) {
4231 ExprResult NewE = SemaRef.SubstExpr(AC->getAllocator(), TemplateArgs);
4232 if (!NewE.isUsable())
4233 continue;
4234 IC = SemaRef.OpenMP().ActOnOpenMPAllocatorClause(
4235 NewE.get(), AC->getBeginLoc(), AC->getLParenLoc(), AC->getEndLoc());
4236 } else if (auto *AC = dyn_cast<OMPAlignClause>(C)) {
4237 ExprResult NewE = SemaRef.SubstExpr(AC->getAlignment(), TemplateArgs);
4238 if (!NewE.isUsable())
4239 continue;
4240 IC = SemaRef.OpenMP().ActOnOpenMPAlignClause(
4241 NewE.get(), AC->getBeginLoc(), AC->getLParenLoc(), AC->getEndLoc());
4242 // If align clause value ends up being invalid, this can end up null.
4243 if (!IC)
4244 continue;
4245 }
4246 Clauses.push_back(IC);
4247 }
4248
4249 Sema::DeclGroupPtrTy Res = SemaRef.OpenMP().ActOnOpenMPAllocateDirective(
4250 D->getLocation(), Vars, Clauses, Owner);
4251 if (Res.get().isNull())
4252 return nullptr;
4253 return Res.get().getSingleDecl();
4254}
4255
4256Decl *TemplateDeclInstantiator::VisitOMPRequiresDecl(OMPRequiresDecl *D) {
4257 llvm_unreachable(
4258 "Requires directive cannot be instantiated within a dependent context");
4259}
4260
4261Decl *TemplateDeclInstantiator::VisitOMPDeclareReductionDecl(
4263 // Instantiate type and check if it is allowed.
4264 const bool RequiresInstantiation =
4265 D->getType()->isDependentType() ||
4268 QualType SubstReductionType;
4269 if (RequiresInstantiation) {
4270 SubstReductionType = SemaRef.OpenMP().ActOnOpenMPDeclareReductionType(
4271 D->getLocation(),
4272 ParsedType::make(SemaRef.SubstType(
4273 D->getType(), TemplateArgs, D->getLocation(), DeclarationName())));
4274 } else {
4275 SubstReductionType = D->getType();
4276 }
4277 if (SubstReductionType.isNull())
4278 return nullptr;
4279 Expr *Combiner = D->getCombiner();
4280 Expr *Init = D->getInitializer();
4281 bool IsCorrect = true;
4282 // Create instantiated copy.
4283 std::pair<QualType, SourceLocation> ReductionTypes[] = {
4284 std::make_pair(SubstReductionType, D->getLocation())};
4285 auto *PrevDeclInScope = D->getPrevDeclInScope();
4286 if (PrevDeclInScope && !PrevDeclInScope->isInvalidDecl()) {
4287 PrevDeclInScope = cast<OMPDeclareReductionDecl>(
4288 cast<Decl *>(*SemaRef.CurrentInstantiationScope->findInstantiationOf(
4289 PrevDeclInScope)));
4290 }
4291 auto DRD = SemaRef.OpenMP().ActOnOpenMPDeclareReductionDirectiveStart(
4292 /*S=*/nullptr, Owner, D->getDeclName(), ReductionTypes, D->getAccess(),
4293 PrevDeclInScope);
4294 auto *NewDRD = cast<OMPDeclareReductionDecl>(DRD.get().getSingleDecl());
4295 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewDRD);
4296 Expr *SubstCombiner = nullptr;
4297 Expr *SubstInitializer = nullptr;
4298 // Combiners instantiation sequence.
4299 if (Combiner) {
4300 SemaRef.OpenMP().ActOnOpenMPDeclareReductionCombinerStart(
4301 /*S=*/nullptr, NewDRD);
4302 SemaRef.CurrentInstantiationScope->InstantiatedLocal(
4303 cast<DeclRefExpr>(D->getCombinerIn())->getDecl(),
4304 cast<DeclRefExpr>(NewDRD->getCombinerIn())->getDecl());
4305 SemaRef.CurrentInstantiationScope->InstantiatedLocal(
4306 cast<DeclRefExpr>(D->getCombinerOut())->getDecl(),
4307 cast<DeclRefExpr>(NewDRD->getCombinerOut())->getDecl());
4308 auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(Owner);
4309 Sema::CXXThisScopeRAII ThisScope(SemaRef, ThisContext, Qualifiers(),
4310 ThisContext);
4311 SubstCombiner = SemaRef.SubstExpr(Combiner, TemplateArgs).get();
4312 SemaRef.OpenMP().ActOnOpenMPDeclareReductionCombinerEnd(NewDRD,
4313 SubstCombiner);
4314 }
4315 // Initializers instantiation sequence.
4316 if (Init) {
4317 VarDecl *OmpPrivParm =
4318 SemaRef.OpenMP().ActOnOpenMPDeclareReductionInitializerStart(
4319 /*S=*/nullptr, NewDRD);
4320 SemaRef.CurrentInstantiationScope->InstantiatedLocal(
4321 cast<DeclRefExpr>(D->getInitOrig())->getDecl(),
4322 cast<DeclRefExpr>(NewDRD->getInitOrig())->getDecl());
4323 SemaRef.CurrentInstantiationScope->InstantiatedLocal(
4324 cast<DeclRefExpr>(D->getInitPriv())->getDecl(),
4325 cast<DeclRefExpr>(NewDRD->getInitPriv())->getDecl());
4327 SubstInitializer = SemaRef.SubstExpr(Init, TemplateArgs).get();
4328 } else {
4329 auto *OldPrivParm =
4331 IsCorrect = IsCorrect && OldPrivParm->hasInit();
4332 if (IsCorrect)
4333 SemaRef.InstantiateVariableInitializer(OmpPrivParm, OldPrivParm,
4334 TemplateArgs);
4335 }
4336 SemaRef.OpenMP().ActOnOpenMPDeclareReductionInitializerEnd(
4337 NewDRD, SubstInitializer, OmpPrivParm);
4338 }
4339 IsCorrect = IsCorrect && SubstCombiner &&
4340 (!Init ||
4342 SubstInitializer) ||
4344 !SubstInitializer));
4345
4346 (void)SemaRef.OpenMP().ActOnOpenMPDeclareReductionDirectiveEnd(
4347 /*S=*/nullptr, DRD, IsCorrect && !D->isInvalidDecl());
4348
4349 return NewDRD;
4350}
4351
4352Decl *
4353TemplateDeclInstantiator::VisitOMPDeclareMapperDecl(OMPDeclareMapperDecl *D) {
4354 // Instantiate type and check if it is allowed.
4355 const bool RequiresInstantiation =
4356 D->getType()->isDependentType() ||
4359 QualType SubstMapperTy;
4360 DeclarationName VN = D->getVarName();
4361 if (RequiresInstantiation) {
4362 SubstMapperTy = SemaRef.OpenMP().ActOnOpenMPDeclareMapperType(
4363 D->getLocation(),
4364 ParsedType::make(SemaRef.SubstType(D->getType(), TemplateArgs,
4365 D->getLocation(), VN)));
4366 } else {
4367 SubstMapperTy = D->getType();
4368 }
4369 if (SubstMapperTy.isNull())
4370 return nullptr;
4371 // Create an instantiated copy of mapper.
4372 auto *PrevDeclInScope = D->getPrevDeclInScope();
4373 if (PrevDeclInScope && !PrevDeclInScope->isInvalidDecl()) {
4374 PrevDeclInScope = cast<OMPDeclareMapperDecl>(
4375 cast<Decl *>(*SemaRef.CurrentInstantiationScope->findInstantiationOf(
4376 PrevDeclInScope)));
4377 }
4378 bool IsCorrect = true;
4379 SmallVector<OMPClause *, 6> Clauses;
4380 // Instantiate the mapper variable.
4381 DeclarationNameInfo DirName;
4382 SemaRef.OpenMP().StartOpenMPDSABlock(llvm::omp::OMPD_declare_mapper, DirName,
4383 /*S=*/nullptr,
4384 (*D->clauselist_begin())->getBeginLoc());
4385 ExprResult MapperVarRef =
4386 SemaRef.OpenMP().ActOnOpenMPDeclareMapperDirectiveVarDecl(
4387 /*S=*/nullptr, SubstMapperTy, D->getLocation(), VN);
4388 SemaRef.CurrentInstantiationScope->InstantiatedLocal(
4389 cast<DeclRefExpr>(D->getMapperVarRef())->getDecl(),
4390 cast<DeclRefExpr>(MapperVarRef.get())->getDecl());
4391 auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(Owner);
4392 Sema::CXXThisScopeRAII ThisScope(SemaRef, ThisContext, Qualifiers(),
4393 ThisContext);
4394 // Instantiate map clauses.
4395 for (OMPClause *C : D->clauselists()) {
4396 auto *OldC = cast<OMPMapClause>(C);
4397 SmallVector<Expr *, 4> NewVars;
4398 for (Expr *OE : OldC->varlist()) {
4399 Expr *NE = SemaRef.SubstExpr(OE, TemplateArgs).get();
4400 if (!NE) {
4401 IsCorrect = false;
4402 break;
4403 }
4404 NewVars.push_back(NE);
4405 }
4406 if (!IsCorrect)
4407 break;
4408 NestedNameSpecifierLoc NewQualifierLoc =
4409 SemaRef.SubstNestedNameSpecifierLoc(OldC->getMapperQualifierLoc(),
4410 TemplateArgs);
4411 CXXScopeSpec SS;
4412 SS.Adopt(NewQualifierLoc);
4413 DeclarationNameInfo NewNameInfo =
4414 SemaRef.SubstDeclarationNameInfo(OldC->getMapperIdInfo(), TemplateArgs);
4415 OMPVarListLocTy Locs(OldC->getBeginLoc(), OldC->getLParenLoc(),
4416 OldC->getEndLoc());
4417 OMPClause *NewC = SemaRef.OpenMP().ActOnOpenMPMapClause(
4418 OldC->getIteratorModifier(), OldC->getMapTypeModifiers(),
4419 OldC->getMapTypeModifiersLoc(), SS, NewNameInfo, OldC->getMapType(),
4420 OldC->isImplicitMapType(), OldC->getMapLoc(), OldC->getColonLoc(),
4421 NewVars, Locs);
4422 Clauses.push_back(NewC);
4423 }
4424 SemaRef.OpenMP().EndOpenMPDSABlock(nullptr);
4425 if (!IsCorrect)
4426 return nullptr;
4427 Sema::DeclGroupPtrTy DG = SemaRef.OpenMP().ActOnOpenMPDeclareMapperDirective(
4428 /*S=*/nullptr, Owner, D->getDeclName(), SubstMapperTy, D->getLocation(),
4429 VN, D->getAccess(), MapperVarRef.get(), Clauses, PrevDeclInScope);
4430 Decl *NewDMD = DG.get().getSingleDecl();
4431 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewDMD);
4432 return NewDMD;
4433}
4434
4435Decl *TemplateDeclInstantiator::VisitOMPCapturedExprDecl(
4436 OMPCapturedExprDecl * /*D*/) {
4437 llvm_unreachable("Should not be met in templates");
4438}
4439
4441 return VisitFunctionDecl(D, nullptr);
4442}
4443
4444Decl *
4445TemplateDeclInstantiator::VisitCXXDeductionGuideDecl(CXXDeductionGuideDecl *D) {
4446 Decl *Inst = VisitFunctionDecl(D, nullptr);
4447 if (Inst && !D->getDescribedFunctionTemplate())
4448 Owner->addDecl(Inst);
4449 return Inst;
4450}
4451
4453 return VisitCXXMethodDecl(D, nullptr);
4454}
4455
4456Decl *TemplateDeclInstantiator::VisitRecordDecl(RecordDecl *D) {
4457 llvm_unreachable("There are only CXXRecordDecls in C++");
4458}
4459
4460Decl *
4461TemplateDeclInstantiator::VisitClassTemplateSpecializationDecl(
4463 // As a MS extension, we permit class-scope explicit specialization
4464 // of member class templates.
4465 ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
4466 assert(ClassTemplate->getDeclContext()->isRecord() &&
4468 "can only instantiate an explicit specialization "
4469 "for a member class template");
4470
4471 // Lookup the already-instantiated declaration in the instantiation
4472 // of the class template.
4473 ClassTemplateDecl *InstClassTemplate =
4474 cast_or_null<ClassTemplateDecl>(SemaRef.FindInstantiatedDecl(
4475 D->getLocation(), ClassTemplate, TemplateArgs));
4476 if (!InstClassTemplate)
4477 return nullptr;
4478
4479 // Substitute into the template arguments of the class template explicit
4480 // specialization.
4481 TemplateArgumentListInfo InstTemplateArgs;
4482 if (const ASTTemplateArgumentListInfo *TemplateArgsInfo =
4484 InstTemplateArgs.setLAngleLoc(TemplateArgsInfo->getLAngleLoc());
4485 InstTemplateArgs.setRAngleLoc(TemplateArgsInfo->getRAngleLoc());
4486
4487 if (SemaRef.SubstTemplateArguments(TemplateArgsInfo->arguments(),
4488 TemplateArgs, InstTemplateArgs))
4489 return nullptr;
4490 }
4491
4492 // Check that the template argument list is well-formed for this
4493 // class template.
4494 Sema::CheckTemplateArgumentInfo CTAI;
4495 if (SemaRef.CheckTemplateArgumentList(
4496 InstClassTemplate, D->getLocation(), InstTemplateArgs,
4497 /*DefaultArgs=*/{}, /*PartialTemplateArgs=*/false, CTAI,
4498 /*UpdateArgsWithConversions=*/true))
4499 return nullptr;
4500
4501 // Figure out where to insert this class template explicit specialization
4502 // in the member template's set of class template explicit specializations.
4503 void *InsertPos = nullptr;
4504 ClassTemplateSpecializationDecl *PrevDecl =
4505 InstClassTemplate->findSpecialization(CTAI.CanonicalConverted, InsertPos);
4506
4507 // Check whether we've already seen a conflicting instantiation of this
4508 // declaration (for instance, if there was a prior implicit instantiation).
4509 bool Ignored;
4510 if (PrevDecl &&
4511 SemaRef.CheckSpecializationInstantiationRedecl(D->getLocation(),
4513 PrevDecl,
4514 PrevDecl->getSpecializationKind(),
4515 PrevDecl->getPointOfInstantiation(),
4516 Ignored))
4517 return nullptr;
4518
4519 // If PrevDecl was a definition and D is also a definition, diagnose.
4520 // This happens in cases like:
4521 //
4522 // template<typename T, typename U>
4523 // struct Outer {
4524 // template<typename X> struct Inner;
4525 // template<> struct Inner<T> {};
4526 // template<> struct Inner<U> {};
4527 // };
4528 //
4529 // Outer<int, int> outer; // error: the explicit specializations of Inner
4530 // // have the same signature.
4531 if (PrevDecl && PrevDecl->getDefinition() &&
4533 SemaRef.Diag(D->getLocation(), diag::err_redefinition) << PrevDecl;
4534 SemaRef.Diag(PrevDecl->getDefinition()->getLocation(),
4535 diag::note_previous_definition);
4536 return nullptr;
4537 }
4538
4539 // Create the class template partial specialization declaration.
4540 ClassTemplateSpecializationDecl *InstD =
4542 SemaRef.Context, D->getTagKind(), Owner, D->getBeginLoc(),
4543 D->getLocation(), InstClassTemplate, CTAI.CanonicalConverted,
4544 CTAI.StrictPackMatch, PrevDecl);
4545 InstD->setTemplateArgsAsWritten(InstTemplateArgs);
4546
4547 // Add this partial specialization to the set of class template partial
4548 // specializations.
4549 if (!PrevDecl)
4550 InstClassTemplate->AddSpecialization(InstD, InsertPos);
4551
4552 // Substitute the nested name specifier, if any.
4553 if (SubstQualifier(D, InstD))
4554 return nullptr;
4555
4556 InstD->setAccess(D->getAccess());
4561
4562 Owner->addDecl(InstD);
4563
4564 // Instantiate the members of the class-scope explicit specialization eagerly.
4565 // We don't have support for lazy instantiation of an explicit specialization
4566 // yet, and MSVC eagerly instantiates in this case.
4567 // FIXME: This is wrong in standard C++.
4569 SemaRef.InstantiateClass(D->getLocation(), InstD, D, TemplateArgs,
4571 /*Complain=*/true))
4572 return nullptr;
4573
4574 return InstD;
4575}
4576
4579
4580 TemplateArgumentListInfo VarTemplateArgsInfo;
4582 assert(VarTemplate &&
4583 "A template specialization without specialized template?");
4584
4585 VarTemplateDecl *InstVarTemplate =
4586 cast_or_null<VarTemplateDecl>(SemaRef.FindInstantiatedDecl(
4587 D->getLocation(), VarTemplate, TemplateArgs));
4588 if (!InstVarTemplate)
4589 return nullptr;
4590
4591 // Substitute the current template arguments.
4592 if (const ASTTemplateArgumentListInfo *TemplateArgsInfo =
4594 VarTemplateArgsInfo.setLAngleLoc(TemplateArgsInfo->getLAngleLoc());
4595 VarTemplateArgsInfo.setRAngleLoc(TemplateArgsInfo->getRAngleLoc());
4596
4597 if (SemaRef.SubstTemplateArguments(TemplateArgsInfo->arguments(),
4598 TemplateArgs, VarTemplateArgsInfo))
4599 return nullptr;
4600 }
4601
4602 // Check that the template argument list is well-formed for this template.
4604 if (SemaRef.CheckTemplateArgumentList(
4605 InstVarTemplate, D->getLocation(), VarTemplateArgsInfo,
4606 /*DefaultArgs=*/{}, /*PartialTemplateArgs=*/false, CTAI,
4607 /*UpdateArgsWithConversions=*/true))
4608 return nullptr;
4609
4610 // Check whether we've already seen a declaration of this specialization.
4611 void *InsertPos = nullptr;
4613 InstVarTemplate->findSpecialization(CTAI.CanonicalConverted, InsertPos);
4614
4615 // Check whether we've already seen a conflicting instantiation of this
4616 // declaration (for instance, if there was a prior implicit instantiation).
4617 bool Ignored;
4618 if (PrevDecl && SemaRef.CheckSpecializationInstantiationRedecl(
4619 D->getLocation(), D->getSpecializationKind(), PrevDecl,
4620 PrevDecl->getSpecializationKind(),
4621 PrevDecl->getPointOfInstantiation(), Ignored))
4622 return nullptr;
4623
4625 InstVarTemplate, D, CTAI.CanonicalConverted, PrevDecl)) {
4626 VTSD->setTemplateArgsAsWritten(VarTemplateArgsInfo);
4627 return VTSD;
4628 }
4629 return nullptr;
4630}
4631
4637
4638 // Do substitution on the type of the declaration
4639 TypeSourceInfo *TSI =
4640 SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs,
4641 D->getTypeSpecStartLoc(), D->getDeclName());
4642 if (!TSI)
4643 return nullptr;
4644
4645 if (TSI->getType()->isFunctionType()) {
4646 SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function)
4647 << D->isStaticDataMember() << TSI->getType();
4648 return nullptr;
4649 }
4650
4651 // Build the instantiated declaration
4653 SemaRef.Context, Owner, D->getInnerLocStart(), D->getLocation(),
4654 VarTemplate, TSI->getType(), TSI, D->getStorageClass(), Converted);
4655 if (!PrevDecl) {
4656 void *InsertPos = nullptr;
4657 VarTemplate->findSpecialization(Converted, InsertPos);
4658 VarTemplate->AddSpecialization(Var, InsertPos);
4659 }
4660
4661 if (SemaRef.getLangOpts().OpenCL)
4662 SemaRef.deduceOpenCLAddressSpace(Var);
4663
4664 // Substitute the nested name specifier, if any.
4665 if (SubstQualifier(D, Var))
4666 return nullptr;
4667
4668 SemaRef.BuildVariableInstantiation(Var, D, TemplateArgs, LateAttrs, Owner,
4669 StartingScope, false, PrevDecl);
4670
4671 return Var;
4672}
4673
4674Decl *TemplateDeclInstantiator::VisitObjCAtDefsFieldDecl(ObjCAtDefsFieldDecl *D) {
4675 llvm_unreachable("@defs is not supported in Objective-C++");
4676}
4677
4678Decl *TemplateDeclInstantiator::VisitFriendTemplateDecl(FriendTemplateDecl *D) {
4679 // FIXME: We need to be able to instantiate FriendTemplateDecls.
4680 unsigned DiagID = SemaRef.getDiagnostics().getCustomDiagID(
4682 "cannot instantiate %0 yet");
4683 SemaRef.Diag(D->getLocation(), DiagID)
4684 << D->getDeclKindName();
4685
4686 return nullptr;
4687}
4688
4689Decl *TemplateDeclInstantiator::VisitConceptDecl(ConceptDecl *D) {
4690 llvm_unreachable("Concept definitions cannot reside inside a template");
4691}
4692
4693Decl *TemplateDeclInstantiator::VisitImplicitConceptSpecializationDecl(
4695 llvm_unreachable("Concept specializations cannot reside inside a template");
4696}
4697
4698Decl *
4699TemplateDeclInstantiator::VisitRequiresExprBodyDecl(RequiresExprBodyDecl *D) {
4700 return RequiresExprBodyDecl::Create(SemaRef.Context, D->getDeclContext(),
4701 D->getBeginLoc());
4702}
4703
4705 llvm_unreachable("Unexpected decl");
4706}
4707
4709 const MultiLevelTemplateArgumentList &TemplateArgs) {
4710 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
4711 if (D->isInvalidDecl())
4712 return nullptr;
4713
4714 Decl *SubstD;
4716 SubstD = Instantiator.Visit(D);
4717 });
4718 return SubstD;
4719}
4720
4722 FunctionDecl *Orig, QualType &T,
4723 TypeSourceInfo *&TInfo,
4724 DeclarationNameInfo &NameInfo) {
4726
4727 // C++2a [class.compare.default]p3:
4728 // the return type is replaced with bool
4729 auto *FPT = T->castAs<FunctionProtoType>();
4730 T = SemaRef.Context.getFunctionType(
4731 SemaRef.Context.BoolTy, FPT->getParamTypes(), FPT->getExtProtoInfo());
4732
4733 // Update the return type in the source info too. The most straightforward
4734 // way is to create new TypeSourceInfo for the new type. Use the location of
4735 // the '= default' as the location of the new type.
4736 //
4737 // FIXME: Set the correct return type when we initially transform the type,
4738 // rather than delaying it to now.
4739 TypeSourceInfo *NewTInfo =
4740 SemaRef.Context.getTrivialTypeSourceInfo(T, Orig->getEndLoc());
4741 auto OldLoc = TInfo->getTypeLoc().getAsAdjusted<FunctionProtoTypeLoc>();
4742 assert(OldLoc && "type of function is not a function type?");
4743 auto NewLoc = NewTInfo->getTypeLoc().castAs<FunctionProtoTypeLoc>();
4744 for (unsigned I = 0, N = OldLoc.getNumParams(); I != N; ++I)
4745 NewLoc.setParam(I, OldLoc.getParam(I));
4746 TInfo = NewTInfo;
4747
4748 // and the declarator-id is replaced with operator==
4749 NameInfo.setName(
4750 SemaRef.Context.DeclarationNames.getCXXOperatorName(OO_EqualEqual));
4751}
4752
4754 FunctionDecl *Spaceship) {
4755 if (Spaceship->isInvalidDecl())
4756 return nullptr;
4757
4758 // C++2a [class.compare.default]p3:
4759 // an == operator function is declared implicitly [...] with the same
4760 // access and function-definition and in the same class scope as the
4761 // three-way comparison operator function
4762 MultiLevelTemplateArgumentList NoTemplateArgs;
4764 NoTemplateArgs.addOuterRetainedLevels(RD->getTemplateDepth());
4765 TemplateDeclInstantiator Instantiator(*this, RD, NoTemplateArgs);
4766 Decl *R;
4767 if (auto *MD = dyn_cast<CXXMethodDecl>(Spaceship)) {
4768 R = Instantiator.VisitCXXMethodDecl(
4769 MD, /*TemplateParams=*/nullptr,
4771 } else {
4772 assert(Spaceship->getFriendObjectKind() &&
4773 "defaulted spaceship is neither a member nor a friend");
4774
4775 R = Instantiator.VisitFunctionDecl(
4776 Spaceship, /*TemplateParams=*/nullptr,
4778 if (!R)
4779 return nullptr;
4780
4781 FriendDecl *FD =
4782 FriendDecl::Create(Context, RD, Spaceship->getLocation(),
4783 cast<NamedDecl>(R), Spaceship->getBeginLoc());
4784 FD->setAccess(AS_public);
4785 RD->addDecl(FD);
4786 }
4787 return cast_or_null<FunctionDecl>(R);
4788}
4789
4790/// Instantiates a nested template parameter list in the current
4791/// instantiation context.
4792///
4793/// \param L The parameter list to instantiate
4794///
4795/// \returns NULL if there was an error
4798 // Get errors for all the parameters before bailing out.
4799 bool Invalid = false;
4800
4801 unsigned N = L->size();
4802 typedef SmallVector<NamedDecl *, 8> ParamVector;
4803 ParamVector Params;
4804 Params.reserve(N);
4805 for (auto &P : *L) {
4806 NamedDecl *D = cast_or_null<NamedDecl>(Visit(P));
4807 Params.push_back(D);
4808 Invalid = Invalid || !D || D->isInvalidDecl();
4809 }
4810
4811 // Clean up if we had an error.
4812 if (Invalid)
4813 return nullptr;
4814
4815 Expr *InstRequiresClause = L->getRequiresClause();
4816
4818 = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(),
4819 L->getLAngleLoc(), Params,
4820 L->getRAngleLoc(), InstRequiresClause);
4821 return InstL;
4822}
4823
4826 const MultiLevelTemplateArgumentList &TemplateArgs,
4827 bool EvaluateConstraints) {
4828 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
4829 Instantiator.setEvaluateConstraints(EvaluateConstraints);
4830 return Instantiator.SubstTemplateParams(Params);
4831}
4832
4833/// Instantiate the declaration of a class template partial
4834/// specialization.
4835///
4836/// \param ClassTemplate the (instantiated) class template that is partially
4837// specialized by the instantiation of \p PartialSpec.
4838///
4839/// \param PartialSpec the (uninstantiated) class template partial
4840/// specialization that we are instantiating.
4841///
4842/// \returns The instantiated partial specialization, if successful; otherwise,
4843/// NULL to indicate an error.
4846 ClassTemplateDecl *ClassTemplate,
4848 // Create a local instantiation scope for this class template partial
4849 // specialization, which will contain the instantiations of the template
4850 // parameters.
4852
4853 // Substitute into the template parameters of the class template partial
4854 // specialization.
4855 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
4856 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
4857 if (!InstParams)
4858 return nullptr;
4859
4860 // Substitute into the template arguments of the class template partial
4861 // specialization.
4862 const ASTTemplateArgumentListInfo *TemplArgInfo
4863 = PartialSpec->getTemplateArgsAsWritten();
4864 TemplateArgumentListInfo InstTemplateArgs(TemplArgInfo->LAngleLoc,
4865 TemplArgInfo->RAngleLoc);
4866 if (SemaRef.SubstTemplateArguments(TemplArgInfo->arguments(), TemplateArgs,
4867 InstTemplateArgs))
4868 return nullptr;
4869
4870 // Check that the template argument list is well-formed for this
4871 // class template.
4873 if (SemaRef.CheckTemplateArgumentList(
4874 ClassTemplate, PartialSpec->getLocation(), InstTemplateArgs,
4875 /*DefaultArgs=*/{},
4876 /*PartialTemplateArgs=*/false, CTAI))
4877 return nullptr;
4878
4879 // Check these arguments are valid for a template partial specialization.
4880 if (SemaRef.CheckTemplatePartialSpecializationArgs(
4881 PartialSpec->getLocation(), ClassTemplate, InstTemplateArgs.size(),
4882 CTAI.CanonicalConverted))
4883 return nullptr;
4884
4885 // Figure out where to insert this class template partial specialization
4886 // in the member template's set of class template partial specializations.
4887 void *InsertPos = nullptr;
4890 InstParams, InsertPos);
4891
4892 // Create the class template partial specialization declaration.
4895 SemaRef.Context, PartialSpec->getTagKind(), Owner,
4896 PartialSpec->getBeginLoc(), PartialSpec->getLocation(), InstParams,
4897 ClassTemplate, CTAI.CanonicalConverted,
4898 /*CanonInjectedTST=*/CanQualType(),
4899 /*PrevDecl=*/nullptr);
4900
4901 InstPartialSpec->setTemplateArgsAsWritten(InstTemplateArgs);
4902
4903 // Substitute the nested name specifier, if any.
4904 if (SubstQualifier(PartialSpec, InstPartialSpec))
4905 return nullptr;
4906
4907 InstPartialSpec->setInstantiatedFromMember(PartialSpec);
4908
4909 if (PrevDecl) {
4910 // We've already seen a partial specialization with the same template
4911 // parameters and template arguments. This can happen, for example, when
4912 // substituting the outer template arguments ends up causing two
4913 // class template partial specializations of a member class template
4914 // to have identical forms, e.g.,
4915 //
4916 // template<typename T, typename U>
4917 // struct Outer {
4918 // template<typename X, typename Y> struct Inner;
4919 // template<typename Y> struct Inner<T, Y>;
4920 // template<typename Y> struct Inner<U, Y>;
4921 // };
4922 //
4923 // Outer<int, int> outer; // error: the partial specializations of Inner
4924 // // have the same signature.
4925 SemaRef.Diag(InstPartialSpec->getLocation(),
4926 diag::err_partial_spec_redeclared)
4927 << InstPartialSpec;
4928 SemaRef.Diag(PrevDecl->getLocation(), diag::note_prev_partial_spec_here)
4929 << SemaRef.Context.getCanonicalTagType(PrevDecl);
4930 return nullptr;
4931 }
4932
4933 // Check the completed partial specialization.
4934 SemaRef.CheckTemplatePartialSpecialization(InstPartialSpec);
4935
4936 // Add this partial specialization to the set of class template partial
4937 // specializations.
4938 ClassTemplate->AddPartialSpecialization(InstPartialSpec,
4939 /*InsertPos=*/nullptr);
4940 return InstPartialSpec;
4941}
4942
4943/// Instantiate the declaration of a variable template partial
4944/// specialization.
4945///
4946/// \param VarTemplate the (instantiated) variable template that is partially
4947/// specialized by the instantiation of \p PartialSpec.
4948///
4949/// \param PartialSpec the (uninstantiated) variable template partial
4950/// specialization that we are instantiating.
4951///
4952/// \returns The instantiated partial specialization, if successful; otherwise,
4953/// NULL to indicate an error.
4958 // Create a local instantiation scope for this variable template partial
4959 // specialization, which will contain the instantiations of the template
4960 // parameters.
4962
4963 // Substitute into the template parameters of the variable template partial
4964 // specialization.
4965 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
4966 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
4967 if (!InstParams)
4968 return nullptr;
4969
4970 // Substitute into the template arguments of the variable template partial
4971 // specialization.
4972 const ASTTemplateArgumentListInfo *TemplArgInfo
4973 = PartialSpec->getTemplateArgsAsWritten();
4974 TemplateArgumentListInfo InstTemplateArgs(TemplArgInfo->LAngleLoc,
4975 TemplArgInfo->RAngleLoc);
4976 if (SemaRef.SubstTemplateArguments(TemplArgInfo->arguments(), TemplateArgs,
4977 InstTemplateArgs))
4978 return nullptr;
4979
4980 // Check that the template argument list is well-formed for this
4981 // class template.
4983 if (SemaRef.CheckTemplateArgumentList(VarTemplate, PartialSpec->getLocation(),
4984 InstTemplateArgs, /*DefaultArgs=*/{},
4985 /*PartialTemplateArgs=*/false, CTAI))
4986 return nullptr;
4987
4988 // Check these arguments are valid for a template partial specialization.
4989 if (SemaRef.CheckTemplatePartialSpecializationArgs(
4990 PartialSpec->getLocation(), VarTemplate, InstTemplateArgs.size(),
4991 CTAI.CanonicalConverted))
4992 return nullptr;
4993
4994 // Figure out where to insert this variable template partial specialization
4995 // in the member template's set of variable template partial specializations.
4996 void *InsertPos = nullptr;
4998 VarTemplate->findPartialSpecialization(CTAI.CanonicalConverted,
4999 InstParams, InsertPos);
5000
5001 // Do substitution on the type of the declaration
5002 TypeSourceInfo *TSI = SemaRef.SubstType(
5003 PartialSpec->getTypeSourceInfo(), TemplateArgs,
5004 PartialSpec->getTypeSpecStartLoc(), PartialSpec->getDeclName());
5005 if (!TSI)
5006 return nullptr;
5007
5008 if (TSI->getType()->isFunctionType()) {
5009 SemaRef.Diag(PartialSpec->getLocation(),
5010 diag::err_variable_instantiates_to_function)
5011 << PartialSpec->isStaticDataMember() << TSI->getType();
5012 return nullptr;
5013 }
5014
5015 // Create the variable template partial specialization declaration.
5016 VarTemplatePartialSpecializationDecl *InstPartialSpec =
5018 SemaRef.Context, Owner, PartialSpec->getInnerLocStart(),
5019 PartialSpec->getLocation(), InstParams, VarTemplate, TSI->getType(),
5020 TSI, PartialSpec->getStorageClass(), CTAI.CanonicalConverted);
5021
5022 InstPartialSpec->setTemplateArgsAsWritten(InstTemplateArgs);
5023
5024 // Substitute the nested name specifier, if any.
5025 if (SubstQualifier(PartialSpec, InstPartialSpec))
5026 return nullptr;
5027
5028 InstPartialSpec->setInstantiatedFromMember(PartialSpec);
5029
5030 if (PrevDecl) {
5031 // We've already seen a partial specialization with the same template
5032 // parameters and template arguments. This can happen, for example, when
5033 // substituting the outer template arguments ends up causing two
5034 // variable template partial specializations of a member variable template
5035 // to have identical forms, e.g.,
5036 //
5037 // template<typename T, typename U>
5038 // struct Outer {
5039 // template<typename X, typename Y> pair<X,Y> p;
5040 // template<typename Y> pair<T, Y> p;
5041 // template<typename Y> pair<U, Y> p;
5042 // };
5043 //
5044 // Outer<int, int> outer; // error: the partial specializations of Inner
5045 // // have the same signature.
5046 SemaRef.Diag(PartialSpec->getLocation(),
5047 diag::err_var_partial_spec_redeclared)
5048 << InstPartialSpec;
5049 SemaRef.Diag(PrevDecl->getLocation(),
5050 diag::note_var_prev_partial_spec_here);
5051 return nullptr;
5052 }
5053 // Check the completed partial specialization.
5054 SemaRef.CheckTemplatePartialSpecialization(InstPartialSpec);
5055
5056 // Add this partial specialization to the set of variable template partial
5057 // specializations. The instantiation of the initializer is not necessary.
5058 VarTemplate->AddPartialSpecialization(InstPartialSpec, /*InsertPos=*/nullptr);
5059
5060 SemaRef.BuildVariableInstantiation(InstPartialSpec, PartialSpec, TemplateArgs,
5061 LateAttrs, Owner, StartingScope);
5062
5063 return InstPartialSpec;
5064}
5065
5069 TypeSourceInfo *OldTInfo = D->getTypeSourceInfo();
5070 assert(OldTInfo && "substituting function without type source info");
5071 assert(Params.empty() && "parameter vector is non-empty at start");
5072
5073 CXXRecordDecl *ThisContext = nullptr;
5074 Qualifiers ThisTypeQuals;
5075 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
5076 ThisContext = cast<CXXRecordDecl>(Owner);
5077 ThisTypeQuals = Method->getFunctionObjectParameterType().getQualifiers();
5078 }
5079
5080 TypeSourceInfo *NewTInfo = SemaRef.SubstFunctionDeclType(
5081 OldTInfo, TemplateArgs, D->getTypeSpecStartLoc(), D->getDeclName(),
5082 ThisContext, ThisTypeQuals, EvaluateConstraints);
5083 if (!NewTInfo)
5084 return nullptr;
5085
5086 TypeLoc OldTL = OldTInfo->getTypeLoc().IgnoreParens();
5087 if (FunctionProtoTypeLoc OldProtoLoc = OldTL.getAs<FunctionProtoTypeLoc>()) {
5088 if (NewTInfo != OldTInfo) {
5089 // Get parameters from the new type info.
5090 TypeLoc NewTL = NewTInfo->getTypeLoc().IgnoreParens();
5091 FunctionProtoTypeLoc NewProtoLoc = NewTL.castAs<FunctionProtoTypeLoc>();
5092 unsigned NewIdx = 0;
5093 for (unsigned OldIdx = 0, NumOldParams = OldProtoLoc.getNumParams();
5094 OldIdx != NumOldParams; ++OldIdx) {
5095 ParmVarDecl *OldParam = OldProtoLoc.getParam(OldIdx);
5096 if (!OldParam)
5097 return nullptr;
5098
5099 LocalInstantiationScope *Scope = SemaRef.CurrentInstantiationScope;
5100
5101 UnsignedOrNone NumArgumentsInExpansion = std::nullopt;
5102 if (OldParam->isParameterPack())
5103 NumArgumentsInExpansion =
5104 SemaRef.getNumArgumentsInExpansion(OldParam->getType(),
5105 TemplateArgs);
5106 if (!NumArgumentsInExpansion) {
5107 // Simple case: normal parameter, or a parameter pack that's
5108 // instantiated to a (still-dependent) parameter pack.
5109 ParmVarDecl *NewParam = NewProtoLoc.getParam(NewIdx++);
5110 Params.push_back(NewParam);
5111 Scope->InstantiatedLocal(OldParam, NewParam);
5112 } else {
5113 // Parameter pack expansion: make the instantiation an argument pack.
5114 Scope->MakeInstantiatedLocalArgPack(OldParam);
5115 for (unsigned I = 0; I != *NumArgumentsInExpansion; ++I) {
5116 ParmVarDecl *NewParam = NewProtoLoc.getParam(NewIdx++);
5117 Params.push_back(NewParam);
5118 Scope->InstantiatedLocalPackArg(OldParam, NewParam);
5119 }
5120 }
5121 }
5122 } else {
5123 // The function type itself was not dependent and therefore no
5124 // substitution occurred. However, we still need to instantiate
5125 // the function parameters themselves.
5126 const FunctionProtoType *OldProto =
5127 cast<FunctionProtoType>(OldProtoLoc.getType());
5128 for (unsigned i = 0, i_end = OldProtoLoc.getNumParams(); i != i_end;
5129 ++i) {
5130 ParmVarDecl *OldParam = OldProtoLoc.getParam(i);
5131 if (!OldParam) {
5132 Params.push_back(SemaRef.BuildParmVarDeclForTypedef(
5133 D, D->getLocation(), OldProto->getParamType(i)));
5134 continue;
5135 }
5136
5137 ParmVarDecl *Parm =
5138 cast_or_null<ParmVarDecl>(VisitParmVarDecl(OldParam));
5139 if (!Parm)
5140 return nullptr;
5141 Params.push_back(Parm);
5142 }
5143 }
5144 } else {
5145 // If the type of this function, after ignoring parentheses, is not
5146 // *directly* a function type, then we're instantiating a function that
5147 // was declared via a typedef or with attributes, e.g.,
5148 //
5149 // typedef int functype(int, int);
5150 // functype func;
5151 // int __cdecl meth(int, int);
5152 //
5153 // In this case, we'll just go instantiate the ParmVarDecls that we
5154 // synthesized in the method declaration.
5155 SmallVector<QualType, 4> ParamTypes;
5156 Sema::ExtParameterInfoBuilder ExtParamInfos;
5157 if (SemaRef.SubstParmTypes(D->getLocation(), D->parameters(), nullptr,
5158 TemplateArgs, ParamTypes, &Params,
5159 ExtParamInfos))
5160 return nullptr;
5161 }
5162
5163 return NewTInfo;
5164}
5165
5166void Sema::addInstantiatedLocalVarsToScope(FunctionDecl *Function,
5167 const FunctionDecl *PatternDecl,
5170
5171 for (auto *decl : PatternDecl->decls()) {
5173 continue;
5174
5175 VarDecl *VD = cast<VarDecl>(decl);
5176 IdentifierInfo *II = VD->getIdentifier();
5177
5178 auto it = llvm::find_if(Function->decls(), [&](Decl *inst) {
5179 VarDecl *InstVD = dyn_cast<VarDecl>(inst);
5180 return InstVD && InstVD->isLocalVarDecl() &&
5181 InstVD->getIdentifier() == II;
5182 });
5183
5184 if (it == Function->decls().end())
5185 continue;
5186
5187 Scope.InstantiatedLocal(VD, *it);
5188 LSI->addCapture(cast<VarDecl>(*it), /*isBlock=*/false, /*isByref=*/false,
5189 /*isNested=*/false, VD->getLocation(), SourceLocation(),
5190 VD->getType(), /*Invalid=*/false);
5191 }
5192}
5193
5194bool Sema::addInstantiatedParametersToScope(
5195 FunctionDecl *Function, const FunctionDecl *PatternDecl,
5197 const MultiLevelTemplateArgumentList &TemplateArgs) {
5198 unsigned FParamIdx = 0;
5199 for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I) {
5200 const ParmVarDecl *PatternParam = PatternDecl->getParamDecl(I);
5201 if (!PatternParam->isParameterPack()) {
5202 // Simple case: not a parameter pack.
5203 assert(FParamIdx < Function->getNumParams());
5204 ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
5205 FunctionParam->setDeclName(PatternParam->getDeclName());
5206 // If the parameter's type is not dependent, update it to match the type
5207 // in the pattern. They can differ in top-level cv-qualifiers, and we want
5208 // the pattern's type here. If the type is dependent, they can't differ,
5209 // per core issue 1668. Substitute into the type from the pattern, in case
5210 // it's instantiation-dependent.
5211 // FIXME: Updating the type to work around this is at best fragile.
5212 if (!PatternDecl->getType()->isDependentType()) {
5213 QualType T = SubstType(PatternParam->getType(), TemplateArgs,
5214 FunctionParam->getLocation(),
5215 FunctionParam->getDeclName());
5216 if (T.isNull())
5217 return true;
5218 FunctionParam->setType(T);
5219 }
5220
5221 Scope.InstantiatedLocal(PatternParam, FunctionParam);
5222 ++FParamIdx;
5223 continue;
5224 }
5225
5226 // Expand the parameter pack.
5227 Scope.MakeInstantiatedLocalArgPack(PatternParam);
5228 UnsignedOrNone NumArgumentsInExpansion =
5229 getNumArgumentsInExpansion(PatternParam->getType(), TemplateArgs);
5230 if (NumArgumentsInExpansion) {
5231 QualType PatternType =
5232 PatternParam->getType()->castAs<PackExpansionType>()->getPattern();
5233 for (unsigned Arg = 0; Arg < *NumArgumentsInExpansion; ++Arg) {
5234 ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
5235 FunctionParam->setDeclName(PatternParam->getDeclName());
5236 if (!PatternDecl->getType()->isDependentType()) {
5237 Sema::ArgPackSubstIndexRAII SubstIndex(*this, Arg);
5238 QualType T =
5239 SubstType(PatternType, TemplateArgs, FunctionParam->getLocation(),
5240 FunctionParam->getDeclName());
5241 if (T.isNull())
5242 return true;
5243 FunctionParam->setType(T);
5244 }
5245
5246 Scope.InstantiatedLocalPackArg(PatternParam, FunctionParam);
5247 ++FParamIdx;
5248 }
5249 }
5250 }
5251
5252 return false;
5253}
5254
5256 ParmVarDecl *Param) {
5257 assert(Param->hasUninstantiatedDefaultArg());
5258
5259 // FIXME: We don't track member specialization info for non-defining
5260 // friend declarations, so we will not be able to later find the function
5261 // pattern. As a workaround, don't instantiate the default argument in this
5262 // case. This is correct per the standard and only an issue for recovery
5263 // purposes. [dcl.fct.default]p4:
5264 // if a friend declaration D specifies a default argument expression,
5265 // that declaration shall be a definition.
5266 if (FD->getFriendObjectKind() != Decl::FOK_None &&
5268 return true;
5269
5270 // Instantiate the expression.
5271 //
5272 // FIXME: Pass in a correct Pattern argument, otherwise
5273 // getTemplateInstantiationArgs uses the lexical context of FD, e.g.
5274 //
5275 // template<typename T>
5276 // struct A {
5277 // static int FooImpl();
5278 //
5279 // template<typename Tp>
5280 // // bug: default argument A<T>::FooImpl() is evaluated with 2-level
5281 // // template argument list [[T], [Tp]], should be [[Tp]].
5282 // friend A<Tp> Foo(int a);
5283 // };
5284 //
5285 // template<typename T>
5286 // A<T> Foo(int a = A<T>::FooImpl());
5288 FD, FD->getLexicalDeclContext(),
5289 /*Final=*/false, /*Innermost=*/std::nullopt,
5290 /*RelativeToPrimary=*/true, /*Pattern=*/nullptr,
5291 /*ForConstraintInstantiation=*/false, /*SkipForSpecialization=*/false,
5292 /*ForDefaultArgumentSubstitution=*/true);
5293
5294 if (SubstDefaultArgument(CallLoc, Param, TemplateArgs, /*ForCallExpr*/ true))
5295 return true;
5296
5298 L->DefaultArgumentInstantiated(Param);
5299
5300 return false;
5301}
5302
5304 FunctionDecl *Decl) {
5305 const FunctionProtoType *Proto = Decl->getType()->castAs<FunctionProtoType>();
5307 return;
5308
5309 RecursiveInstGuard AlreadyInstantiating(
5311 if (AlreadyInstantiating) {
5312 // This exception specification indirectly depends on itself. Reject.
5313 // FIXME: Corresponding rule in the standard?
5314 Diag(PointOfInstantiation, diag::err_exception_spec_cycle) << Decl;
5316 return;
5317 }
5318
5319 NonSFINAEContext _(*this);
5320 InstantiatingTemplate Inst(*this, PointOfInstantiation, Decl,
5322 if (Inst.isInvalid()) {
5323 // We hit the instantiation depth limit. Clear the exception specification
5324 // so that our callers don't have to cope with EST_Uninstantiated.
5326 return;
5327 }
5328
5329 // Enter the scope of this instantiation. We don't use
5330 // PushDeclContext because we don't have a scope.
5331 Sema::ContextRAII savedContext(*this, Decl);
5333
5334 MultiLevelTemplateArgumentList TemplateArgs =
5336 /*Final=*/false, /*Innermost=*/std::nullopt,
5337 /*RelativeToPrimary*/ true);
5338
5339 // FIXME: We can't use getTemplateInstantiationPattern(false) in general
5340 // here, because for a non-defining friend declaration in a class template,
5341 // we don't store enough information to map back to the friend declaration in
5342 // the template.
5344 if (addInstantiatedParametersToScope(Decl, Template, Scope, TemplateArgs)) {
5346 return;
5347 }
5348
5349 // The noexcept specification could reference any lambda captures. Ensure
5350 // those are added to the LocalInstantiationScope.
5352 *this, Decl, TemplateArgs, Scope,
5353 /*ShouldAddDeclsFromParentScope=*/false);
5354
5355 SubstExceptionSpec(Decl, Template->getType()->castAs<FunctionProtoType>(),
5356 TemplateArgs);
5357}
5358
5359/// Initializes the common fields of an instantiation function
5360/// declaration (New) from the corresponding fields of its template (Tmpl).
5361///
5362/// \returns true if there was an error
5363bool
5365 FunctionDecl *Tmpl) {
5366 New->setImplicit(Tmpl->isImplicit());
5367
5368 // Forward the mangling number from the template to the instantiated decl.
5369 SemaRef.Context.setManglingNumber(New,
5370 SemaRef.Context.getManglingNumber(Tmpl));
5371
5372 // If we are performing substituting explicitly-specified template arguments
5373 // or deduced template arguments into a function template and we reach this
5374 // point, we are now past the point where SFINAE applies and have committed
5375 // to keeping the new function template specialization. We therefore
5376 // convert the active template instantiation for the function template
5377 // into a template instantiation for this specific function template
5378 // specialization, which is not a SFINAE context, so that we diagnose any
5379 // further errors in the declaration itself.
5380 //
5381 // FIXME: This is a hack.
5382 typedef Sema::CodeSynthesisContext ActiveInstType;
5383 ActiveInstType &ActiveInst = SemaRef.CodeSynthesisContexts.back();
5384 if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution ||
5385 ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) {
5386 if (isa<FunctionTemplateDecl>(ActiveInst.Entity)) {
5387 SemaRef.CurrentSFINAEContext = nullptr;
5388 atTemplateEnd(SemaRef.TemplateInstCallbacks, SemaRef, ActiveInst);
5389 ActiveInst.Kind = ActiveInstType::TemplateInstantiation;
5390 ActiveInst.Entity = New;
5391 atTemplateBegin(SemaRef.TemplateInstCallbacks, SemaRef, ActiveInst);
5392 }
5393 }
5394
5395 const FunctionProtoType *Proto = Tmpl->getType()->getAs<FunctionProtoType>();
5396 assert(Proto && "Function template without prototype?");
5397
5398 if (Proto->hasExceptionSpec() || Proto->getNoReturnAttr()) {
5400
5401 // DR1330: In C++11, defer instantiation of a non-trivial
5402 // exception specification.
5403 // DR1484: Local classes and their members are instantiated along with the
5404 // containing function.
5405 if (SemaRef.getLangOpts().CPlusPlus11 &&
5406 EPI.ExceptionSpec.Type != EST_None &&
5410 FunctionDecl *ExceptionSpecTemplate = Tmpl;
5412 ExceptionSpecTemplate = EPI.ExceptionSpec.SourceTemplate;
5415 NewEST = EST_Unevaluated;
5416
5417 // Mark the function has having an uninstantiated exception specification.
5418 const FunctionProtoType *NewProto
5419 = New->getType()->getAs<FunctionProtoType>();
5420 assert(NewProto && "Template instantiation without function prototype?");
5421 EPI = NewProto->getExtProtoInfo();
5422 EPI.ExceptionSpec.Type = NewEST;
5424 EPI.ExceptionSpec.SourceTemplate = ExceptionSpecTemplate;
5425 New->setType(SemaRef.Context.getFunctionType(
5426 NewProto->getReturnType(), NewProto->getParamTypes(), EPI));
5427 } else {
5428 Sema::ContextRAII SwitchContext(SemaRef, New);
5429 SemaRef.SubstExceptionSpec(New, Proto, TemplateArgs);
5430 }
5431 }
5432
5433 // Get the definition. Leaves the variable unchanged if undefined.
5434 const FunctionDecl *Definition = Tmpl;
5435 Tmpl->isDefined(Definition);
5436
5437 SemaRef.InstantiateAttrs(TemplateArgs, Definition, New,
5438 LateAttrs, StartingScope);
5439
5440 return false;
5441}
5442
5443/// Initializes common fields of an instantiated method
5444/// declaration (New) from the corresponding fields of its template
5445/// (Tmpl).
5446///
5447/// \returns true if there was an error
5448bool
5450 CXXMethodDecl *Tmpl) {
5451 if (InitFunctionInstantiation(New, Tmpl))
5452 return true;
5453
5454 if (isa<CXXDestructorDecl>(New) && SemaRef.getLangOpts().CPlusPlus11)
5455 SemaRef.AdjustDestructorExceptionSpec(cast<CXXDestructorDecl>(New));
5456
5457 New->setAccess(Tmpl->getAccess());
5458 if (Tmpl->isVirtualAsWritten())
5459 New->setVirtualAsWritten(true);
5460
5461 // FIXME: New needs a pointer to Tmpl
5462 return false;
5463}
5464
5466 FunctionDecl *Tmpl) {
5467 // Transfer across any unqualified lookups.
5468 if (auto *DFI = Tmpl->getDefaultedOrDeletedInfo()) {
5470 Lookups.reserve(DFI->getUnqualifiedLookups().size());
5471 bool AnyChanged = false;
5472 for (DeclAccessPair DA : DFI->getUnqualifiedLookups()) {
5473 NamedDecl *D = SemaRef.FindInstantiatedDecl(New->getLocation(),
5474 DA.getDecl(), TemplateArgs);
5475 if (!D)
5476 return true;
5477 AnyChanged |= (D != DA.getDecl());
5478 Lookups.push_back(DeclAccessPair::make(D, DA.getAccess()));
5479 }
5480
5481 // It's unlikely that substitution will change any declarations. Don't
5482 // store an unnecessary copy in that case.
5483 New->setDefaultedOrDeletedInfo(
5485 SemaRef.Context, Lookups)
5486 : DFI);
5487 }
5488
5489 SemaRef.SetDeclDefaulted(New, Tmpl->getLocation());
5490 return false;
5491}
5492
5496 FunctionDecl *FD = FTD->getTemplatedDecl();
5497
5498 InstantiatingTemplate Inst(*this, Loc, FTD, Args->asArray(), CSC);
5499 if (Inst.isInvalid())
5500 return nullptr;
5501
5502 ContextRAII SavedContext(*this, FD);
5503 MultiLevelTemplateArgumentList MArgs(FTD, Args->asArray(),
5504 /*Final=*/false);
5505
5506 return cast_or_null<FunctionDecl>(SubstDecl(FD, FD->getParent(), MArgs));
5507}
5508
5511 bool Recursive,
5512 bool DefinitionRequired,
5513 bool AtEndOfTU) {
5514 if (Function->isInvalidDecl() || isa<CXXDeductionGuideDecl>(Function))
5515 return;
5516
5517 // Never instantiate an explicit specialization except if it is a class scope
5518 // explicit specialization.
5520 Function->getTemplateSpecializationKindForInstantiation();
5521 if (TSK == TSK_ExplicitSpecialization)
5522 return;
5523
5524 // Never implicitly instantiate a builtin; we don't actually need a function
5525 // body.
5526 if (Function->getBuiltinID() && TSK == TSK_ImplicitInstantiation &&
5527 !DefinitionRequired)
5528 return;
5529
5530 // Don't instantiate a definition if we already have one.
5531 const FunctionDecl *ExistingDefn = nullptr;
5532 if (Function->isDefined(ExistingDefn,
5533 /*CheckForPendingFriendDefinition=*/true)) {
5534 if (ExistingDefn->isThisDeclarationADefinition())
5535 return;
5536
5537 // If we're asked to instantiate a function whose body comes from an
5538 // instantiated friend declaration, attach the instantiated body to the
5539 // corresponding declaration of the function.
5541 Function = const_cast<FunctionDecl*>(ExistingDefn);
5542 }
5543
5544#ifndef NDEBUG
5545 RecursiveInstGuard AlreadyInstantiating(*this, Function,
5547 assert(!AlreadyInstantiating && "should have been caught by caller");
5548#endif
5549
5550 // Find the function body that we'll be substituting.
5551 const FunctionDecl *PatternDecl = Function->getTemplateInstantiationPattern();
5552 assert(PatternDecl && "instantiating a non-template");
5553
5554 const FunctionDecl *PatternDef = PatternDecl->getDefinition();
5555 Stmt *Pattern = nullptr;
5556 if (PatternDef) {
5557 Pattern = PatternDef->getBody(PatternDef);
5558 PatternDecl = PatternDef;
5559 if (PatternDef->willHaveBody())
5560 PatternDef = nullptr;
5561 }
5562
5563 // True is the template definition is unreachable, otherwise false.
5564 bool Unreachable = false;
5565 // FIXME: We need to track the instantiation stack in order to know which
5566 // definitions should be visible within this instantiation.
5568 PointOfInstantiation, Function,
5569 Function->getInstantiatedFromMemberFunction(), PatternDecl,
5570 PatternDef, TSK,
5571 /*Complain*/ DefinitionRequired, &Unreachable)) {
5572 if (DefinitionRequired)
5573 Function->setInvalidDecl();
5574 else if (TSK == TSK_ExplicitInstantiationDefinition ||
5575 (Function->isConstexpr() && !Recursive)) {
5576 // Try again at the end of the translation unit (at which point a
5577 // definition will be required).
5578 assert(!Recursive);
5579 Function->setInstantiationIsPending(true);
5580 PendingInstantiations.emplace_back(Function, PointOfInstantiation);
5581
5582 if (llvm::isTimeTraceVerbose()) {
5583 llvm::timeTraceAddInstantEvent("DeferInstantiation", [&] {
5584 std::string Name;
5585 llvm::raw_string_ostream OS(Name);
5586 Function->getNameForDiagnostic(OS, getPrintingPolicy(),
5587 /*Qualified=*/true);
5588 return Name;
5589 });
5590 }
5591 } else if (TSK == TSK_ImplicitInstantiation) {
5592 if (AtEndOfTU && !getDiagnostics().hasErrorOccurred() &&
5593 !getSourceManager().isInSystemHeader(PatternDecl->getBeginLoc())) {
5594 Diag(PointOfInstantiation, diag::warn_func_template_missing)
5595 << Function;
5596 if (Unreachable) {
5597 // FIXME: would be nice to mention which module the function template
5598 // comes from.
5599 Diag(PatternDecl->getLocation(),
5600 diag::note_unreachable_template_decl);
5601 } else {
5602 Diag(PatternDecl->getLocation(), diag::note_forward_template_decl);
5604 Diag(PointOfInstantiation, diag::note_inst_declaration_hint)
5605 << Function;
5606 }
5607 }
5608 }
5609
5610 return;
5611 }
5612
5613 // Postpone late parsed template instantiations.
5614 if (PatternDecl->isLateTemplateParsed() &&
5616 Function->setInstantiationIsPending(true);
5617 LateParsedInstantiations.push_back(
5618 std::make_pair(Function, PointOfInstantiation));
5619 return;
5620 }
5621
5622 llvm::TimeTraceScope TimeScope("InstantiateFunction", [&]() {
5623 llvm::TimeTraceMetadata M;
5624 llvm::raw_string_ostream OS(M.Detail);
5625 Function->getNameForDiagnostic(OS, getPrintingPolicy(),
5626 /*Qualified=*/true);
5627 if (llvm::isTimeTraceVerbose()) {
5628 auto Loc = SourceMgr.getExpansionLoc(Function->getLocation());
5629 M.File = SourceMgr.getFilename(Loc);
5630 M.Line = SourceMgr.getExpansionLineNumber(Loc);
5631 }
5632 return M;
5633 });
5634
5635 // If we're performing recursive template instantiation, create our own
5636 // queue of pending implicit instantiations that we will instantiate later,
5637 // while we're still within our own instantiation context.
5638 // This has to happen before LateTemplateParser below is called, so that
5639 // it marks vtables used in late parsed templates as used.
5640 GlobalEagerInstantiationScope GlobalInstantiations(*this,
5641 /*Enabled=*/Recursive,
5642 /*AtEndOfTU=*/AtEndOfTU);
5643 LocalEagerInstantiationScope LocalInstantiations(*this,
5644 /*AtEndOfTU=*/AtEndOfTU);
5645
5646 // Call the LateTemplateParser callback if there is a need to late parse
5647 // a templated function definition.
5648 if (!Pattern && PatternDecl->isLateTemplateParsed() &&
5650 // FIXME: Optimize to allow individual templates to be deserialized.
5651 if (PatternDecl->isFromASTFile())
5652 ExternalSource->ReadLateParsedTemplates(LateParsedTemplateMap);
5653
5654 auto LPTIter = LateParsedTemplateMap.find(PatternDecl);
5655 assert(LPTIter != LateParsedTemplateMap.end() &&
5656 "missing LateParsedTemplate");
5657 LateTemplateParser(OpaqueParser, *LPTIter->second);
5658 Pattern = PatternDecl->getBody(PatternDecl);
5660 }
5661
5662 // Note, we should never try to instantiate a deleted function template.
5663 assert((Pattern || PatternDecl->isDefaulted() ||
5664 PatternDecl->hasSkippedBody()) &&
5665 "unexpected kind of function template definition");
5666
5667 // C++1y [temp.explicit]p10:
5668 // Except for inline functions, declarations with types deduced from their
5669 // initializer or return value, and class template specializations, other
5670 // explicit instantiation declarations have the effect of suppressing the
5671 // implicit instantiation of the entity to which they refer.
5673 !PatternDecl->isInlined() &&
5674 !PatternDecl->getReturnType()->getContainedAutoType())
5675 return;
5676
5677 if (PatternDecl->isInlined()) {
5678 // Function, and all later redeclarations of it (from imported modules,
5679 // for instance), are now implicitly inline.
5680 for (auto *D = Function->getMostRecentDecl(); /**/;
5681 D = D->getPreviousDecl()) {
5682 D->setImplicitlyInline();
5683 if (D == Function)
5684 break;
5685 }
5686 }
5687
5688 NonSFINAEContext _(*this);
5689 InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
5690 if (Inst.isInvalid())
5691 return;
5693 "instantiating function definition");
5694
5695 // The instantiation is visible here, even if it was first declared in an
5696 // unimported module.
5697 Function->setVisibleDespiteOwningModule();
5698
5699 // Copy the source locations from the pattern.
5700 Function->setLocation(PatternDecl->getLocation());
5701 Function->setInnerLocStart(PatternDecl->getInnerLocStart());
5702 Function->setRangeEnd(PatternDecl->getEndLoc());
5703 // Let the instantiation use the Pattern's DeclarationNameLoc, due to the
5704 // following awkwardness:
5705 //
5706 // 1. There are out-of-tree users of getNameInfo().getSourceRange(), who
5707 // expect the source range of the instantiated declaration to be set to
5708 // point to the definition.
5709 //
5710 // 2. That getNameInfo().getSourceRange() might return the TypeLocInfo's
5711 // location it tracked.
5712 //
5713 // 3. Function might come from an (implicit) declaration, while the pattern
5714 // comes from a definition. In these cases, we need the PatternDecl's source
5715 // location.
5716 //
5717 // To that end, we need to more or less tweak the DeclarationNameLoc. However,
5718 // we can't blindly copy the DeclarationNameLoc from the PatternDecl to the
5719 // function, since it contains associated TypeLocs that should have already
5720 // been transformed. So, we rebuild the TypeLoc for that purpose. Technically,
5721 // we should create a new function declaration and assign everything we need,
5722 // but InstantiateFunctionDefinition updates the declaration in place.
5723 auto NameLocPointsToPattern = [&] {
5724 DeclarationNameInfo PatternName = PatternDecl->getNameInfo();
5725 DeclarationNameLoc PatternNameLoc = PatternName.getInfo();
5726 switch (PatternName.getName().getNameKind()) {
5730 break;
5731 default:
5732 // Cases where DeclarationNameLoc doesn't matter, as it merely contains a
5733 // source range.
5734 return PatternNameLoc;
5735 }
5736
5737 TypeSourceInfo *TSI = Function->getNameInfo().getNamedTypeInfo();
5738 // TSI might be null if the function is named by a constructor template id.
5739 // E.g. S<T>() {} for class template S with a template parameter T.
5740 if (!TSI) {
5741 // We don't care about the DeclarationName of the instantiated function,
5742 // but only the DeclarationNameLoc. So if the TypeLoc is absent, we do
5743 // nothing.
5744 return PatternNameLoc;
5745 }
5746
5747 QualType InstT = TSI->getType();
5748 // We want to use a TypeLoc that reflects the transformed type while
5749 // preserving the source location from the pattern.
5750 TypeLocBuilder TLB;
5751 TypeSourceInfo *PatternTSI = PatternName.getNamedTypeInfo();
5752 assert(PatternTSI && "Pattern is supposed to have an associated TSI");
5753 // FIXME: PatternTSI is not trivial. We should copy the source location
5754 // along the TypeLoc chain. However a trivial TypeLoc is sufficient for
5755 // getNameInfo().getSourceRange().
5756 TLB.pushTrivial(Context, InstT, PatternTSI->getTypeLoc().getBeginLoc());
5758 TLB.getTypeSourceInfo(Context, InstT));
5759 };
5760 Function->setDeclarationNameLoc(NameLocPointsToPattern());
5761
5764
5765 Qualifiers ThisTypeQuals;
5766 CXXRecordDecl *ThisContext = nullptr;
5767 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
5768 ThisContext = Method->getParent();
5769 ThisTypeQuals = Method->getMethodQualifiers();
5770 }
5771 CXXThisScopeRAII ThisScope(*this, ThisContext, ThisTypeQuals);
5772
5773 // Introduce a new scope where local variable instantiations will be
5774 // recorded, unless we're actually a member function within a local
5775 // class, in which case we need to merge our results with the parent
5776 // scope (of the enclosing function). The exception is instantiating
5777 // a function template specialization, since the template to be
5778 // instantiated already has references to locals properly substituted.
5779 bool MergeWithParentScope = false;
5780 if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Function->getDeclContext()))
5781 MergeWithParentScope =
5782 Rec->isLocalClass() && !Function->isFunctionTemplateSpecialization();
5783
5784 LocalInstantiationScope Scope(*this, MergeWithParentScope);
5785 auto RebuildTypeSourceInfoForDefaultSpecialMembers = [&]() {
5786 // Special members might get their TypeSourceInfo set up w.r.t the
5787 // PatternDecl context, in which case parameters could still be pointing
5788 // back to the original class, make sure arguments are bound to the
5789 // instantiated record instead.
5790 assert(PatternDecl->isDefaulted() &&
5791 "Special member needs to be defaulted");
5792 auto PatternSM = getDefaultedFunctionKind(PatternDecl).asSpecialMember();
5793 if (!(PatternSM == CXXSpecialMemberKind::CopyConstructor ||
5797 return;
5798
5799 auto *NewRec = dyn_cast<CXXRecordDecl>(Function->getDeclContext());
5800 const auto *PatternRec =
5801 dyn_cast<CXXRecordDecl>(PatternDecl->getDeclContext());
5802 if (!NewRec || !PatternRec)
5803 return;
5804 if (!PatternRec->isLambda())
5805 return;
5806
5807 struct SpecialMemberTypeInfoRebuilder
5808 : TreeTransform<SpecialMemberTypeInfoRebuilder> {
5810 const CXXRecordDecl *OldDecl;
5811 CXXRecordDecl *NewDecl;
5812
5813 SpecialMemberTypeInfoRebuilder(Sema &SemaRef, const CXXRecordDecl *O,
5814 CXXRecordDecl *N)
5815 : TreeTransform(SemaRef), OldDecl(O), NewDecl(N) {}
5816
5817 bool TransformExceptionSpec(SourceLocation Loc,
5819 SmallVectorImpl<QualType> &Exceptions,
5820 bool &Changed) {
5821 return false;
5822 }
5823
5824 QualType TransformRecordType(TypeLocBuilder &TLB, RecordTypeLoc TL) {
5825 const RecordType *T = TL.getTypePtr();
5826 RecordDecl *Record = cast_or_null<RecordDecl>(
5827 getDerived().TransformDecl(TL.getNameLoc(), T->getDecl()));
5828 if (Record != OldDecl)
5829 return Base::TransformRecordType(TLB, TL);
5830
5831 // FIXME: transform the rest of the record type.
5832 QualType Result = getDerived().RebuildTagType(
5833 ElaboratedTypeKeyword::None, /*Qualifier=*/std::nullopt, NewDecl);
5834 if (Result.isNull())
5835 return QualType();
5836
5837 TagTypeLoc NewTL = TLB.push<RecordTypeLoc>(Result);
5840 NewTL.setNameLoc(TL.getNameLoc());
5841 return Result;
5842 }
5843 } IR{*this, PatternRec, NewRec};
5844
5845 TypeSourceInfo *NewSI = IR.TransformType(Function->getTypeSourceInfo());
5846 assert(NewSI && "Type Transform failed?");
5847 Function->setType(NewSI->getType());
5848 Function->setTypeSourceInfo(NewSI);
5849
5850 ParmVarDecl *Parm = Function->getParamDecl(0);
5851 TypeSourceInfo *NewParmSI = IR.TransformType(Parm->getTypeSourceInfo());
5852 assert(NewParmSI && "Type transformation failed.");
5853 Parm->setType(NewParmSI->getType());
5854 Parm->setTypeSourceInfo(NewParmSI);
5855 };
5856
5857 if (PatternDecl->isDefaulted()) {
5858 RebuildTypeSourceInfoForDefaultSpecialMembers();
5859 SetDeclDefaulted(Function, PatternDecl->getLocation());
5860 } else {
5861 DeclContext *DC = Function->getLexicalDeclContext();
5862 std::optional<ArrayRef<TemplateArgument>> Innermost;
5863 if (auto *Primary = Function->getPrimaryTemplate();
5864 Primary &&
5866 Function->getTemplateSpecializationKind() !=
5868 auto It = llvm::find_if(Primary->redecls(),
5869 [](const RedeclarableTemplateDecl *RTD) {
5870 return cast<FunctionTemplateDecl>(RTD)
5871 ->isCompatibleWithDefinition();
5872 });
5873 assert(It != Primary->redecls().end() &&
5874 "Should't get here without a definition");
5876 ->getTemplatedDecl()
5877 ->getDefinition())
5878 DC = Def->getLexicalDeclContext();
5879 else
5880 DC = (*It)->getLexicalDeclContext();
5881 Innermost.emplace(Function->getTemplateSpecializationArgs()->asArray());
5882 }
5884 Function, DC, /*Final=*/false, Innermost, false, PatternDecl);
5885
5886 // Substitute into the qualifier; we can get a substitution failure here
5887 // through evil use of alias templates.
5888 // FIXME: Is CurContext correct for this? Should we go to the (instantiation
5889 // of the) lexical context of the pattern?
5890 SubstQualifier(*this, PatternDecl, Function, TemplateArgs);
5891
5893
5894 // Enter the scope of this instantiation. We don't use
5895 // PushDeclContext because we don't have a scope.
5896 Sema::ContextRAII savedContext(*this, Function);
5897
5898 FPFeaturesStateRAII SavedFPFeatures(*this);
5900 FpPragmaStack.CurrentValue = FPOptionsOverride();
5901
5902 if (addInstantiatedParametersToScope(Function, PatternDecl, Scope,
5903 TemplateArgs))
5904 return;
5905
5906 StmtResult Body;
5907 if (PatternDecl->hasSkippedBody()) {
5909 Body = nullptr;
5910 } else {
5911 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Function)) {
5912 // If this is a constructor, instantiate the member initializers.
5914 TemplateArgs);
5915
5916 // If this is an MS ABI dllexport default constructor, instantiate any
5917 // default arguments.
5918 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
5919 Ctor->isDefaultConstructor()) {
5921 }
5922 }
5923
5924 // Instantiate the function body.
5925 Body = SubstStmt(Pattern, TemplateArgs);
5926
5927 if (Body.isInvalid())
5928 Function->setInvalidDecl();
5929 }
5930 // FIXME: finishing the function body while in an expression evaluation
5931 // context seems wrong. Investigate more.
5932 ActOnFinishFunctionBody(Function, Body.get(), /*IsInstantiation=*/true);
5933
5934 checkReferenceToTULocalFromOtherTU(Function, PointOfInstantiation);
5935
5936 PerformDependentDiagnostics(PatternDecl, TemplateArgs);
5937
5938 if (auto *Listener = getASTMutationListener())
5939 Listener->FunctionDefinitionInstantiated(Function);
5940
5941 savedContext.pop();
5942 }
5943
5944 // We never need to emit the code for a lambda in unevaluated context.
5945 // We also can't mangle a lambda in the require clause of a function template
5946 // during constraint checking as the MSI ABI would need to mangle the (not yet
5947 // specialized) enclosing declaration
5948 // FIXME: Should we try to skip this for non-lambda functions too?
5949 bool ShouldSkipCG = [&] {
5950 auto *RD = dyn_cast<CXXRecordDecl>(Function->getParent());
5951 if (!RD || !RD->isLambda())
5952 return false;
5953
5954 return llvm::any_of(ExprEvalContexts, [](auto &Context) {
5955 return Context.isUnevaluated() || Context.isImmediateFunctionContext();
5956 });
5957 }();
5958 if (!ShouldSkipCG) {
5960 Consumer.HandleTopLevelDecl(DG);
5961 }
5962
5963 // This class may have local implicit instantiations that need to be
5964 // instantiation within this scope.
5965 LocalInstantiations.perform();
5966 Scope.Exit();
5967 GlobalInstantiations.perform();
5968}
5969
5972 const TemplateArgumentList *PartialSpecArgs,
5974 SourceLocation PointOfInstantiation, LateInstantiatedAttrVec *LateAttrs,
5975 LocalInstantiationScope *StartingScope) {
5976 if (FromVar->isInvalidDecl())
5977 return nullptr;
5978
5979 NonSFINAEContext _(*this);
5980 InstantiatingTemplate Inst(*this, PointOfInstantiation, FromVar);
5981 if (Inst.isInvalid())
5982 return nullptr;
5983
5984 // Instantiate the first declaration of the variable template: for a partial
5985 // specialization of a static data member template, the first declaration may
5986 // or may not be the declaration in the class; if it's in the class, we want
5987 // to instantiate a member in the class (a declaration), and if it's outside,
5988 // we want to instantiate a definition.
5989 //
5990 // If we're instantiating an explicitly-specialized member template or member
5991 // partial specialization, don't do this. The member specialization completely
5992 // replaces the original declaration in this case.
5993 bool IsMemberSpec = false;
5994 MultiLevelTemplateArgumentList MultiLevelList;
5995 if (auto *PartialSpec =
5996 dyn_cast<VarTemplatePartialSpecializationDecl>(FromVar)) {
5997 assert(PartialSpecArgs);
5998 IsMemberSpec = PartialSpec->isMemberSpecialization();
5999 MultiLevelList.addOuterTemplateArguments(
6000 PartialSpec, PartialSpecArgs->asArray(), /*Final=*/false);
6001 } else {
6002 assert(VarTemplate == FromVar->getDescribedVarTemplate());
6003 IsMemberSpec = VarTemplate->isMemberSpecialization();
6004 MultiLevelList.addOuterTemplateArguments(VarTemplate, Converted,
6005 /*Final=*/false);
6006 }
6007 if (!IsMemberSpec)
6008 FromVar = FromVar->getFirstDecl();
6009
6010 TemplateDeclInstantiator Instantiator(*this, FromVar->getDeclContext(),
6011 MultiLevelList);
6012
6013 // TODO: Set LateAttrs and StartingScope ...
6014
6015 return Instantiator.VisitVarTemplateSpecializationDecl(VarTemplate, FromVar,
6016 Converted);
6017}
6018
6020 VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl,
6021 const MultiLevelTemplateArgumentList &TemplateArgs) {
6022 assert(PatternDecl->isThisDeclarationADefinition() &&
6023 "don't have a definition to instantiate from");
6024
6025 // Do substitution on the type of the declaration
6026 TypeSourceInfo *TSI =
6027 SubstType(PatternDecl->getTypeSourceInfo(), TemplateArgs,
6028 PatternDecl->getTypeSpecStartLoc(), PatternDecl->getDeclName());
6029 if (!TSI)
6030 return nullptr;
6031
6032 // Update the type of this variable template specialization.
6033 VarSpec->setType(TSI->getType());
6034
6035 // Convert the declaration into a definition now.
6036 VarSpec->setCompleteDefinition();
6037
6038 // Instantiate the initializer.
6039 InstantiateVariableInitializer(VarSpec, PatternDecl, TemplateArgs);
6040
6041 if (getLangOpts().OpenCL)
6042 deduceOpenCLAddressSpace(VarSpec);
6043
6044 return VarSpec;
6045}
6046
6048 VarDecl *NewVar, VarDecl *OldVar,
6049 const MultiLevelTemplateArgumentList &TemplateArgs,
6050 LateInstantiatedAttrVec *LateAttrs, DeclContext *Owner,
6051 LocalInstantiationScope *StartingScope,
6052 bool InstantiatingVarTemplate,
6053 VarTemplateSpecializationDecl *PrevDeclForVarTemplateSpecialization) {
6054 // Instantiating a partial specialization to produce a partial
6055 // specialization.
6056 bool InstantiatingVarTemplatePartialSpec =
6059 // Instantiating from a variable template (or partial specialization) to
6060 // produce a variable template specialization.
6061 bool InstantiatingSpecFromTemplate =
6063 (OldVar->getDescribedVarTemplate() ||
6065
6066 // If we are instantiating a local extern declaration, the
6067 // instantiation belongs lexically to the containing function.
6068 // If we are instantiating a static data member defined
6069 // out-of-line, the instantiation will have the same lexical
6070 // context (which will be a namespace scope) as the template.
6071 if (OldVar->isLocalExternDecl()) {
6072 NewVar->setLocalExternDecl();
6073 NewVar->setLexicalDeclContext(Owner);
6074 } else if (OldVar->isOutOfLine())
6076 NewVar->setTSCSpec(OldVar->getTSCSpec());
6077 NewVar->setInitStyle(OldVar->getInitStyle());
6078 NewVar->setCXXForRangeDecl(OldVar->isCXXForRangeDecl());
6079 NewVar->setObjCForDecl(OldVar->isObjCForDecl());
6080 NewVar->setConstexpr(OldVar->isConstexpr());
6081 NewVar->setInitCapture(OldVar->isInitCapture());
6084 NewVar->setAccess(OldVar->getAccess());
6085
6086 if (!OldVar->isStaticDataMember()) {
6087 if (OldVar->isUsed(false))
6088 NewVar->setIsUsed();
6089 NewVar->setReferenced(OldVar->isReferenced());
6090 }
6091
6092 InstantiateAttrs(TemplateArgs, OldVar, NewVar, LateAttrs, StartingScope);
6093
6095 *this, NewVar->getDeclName(), NewVar->getLocation(),
6100
6101 if (NewVar->isLocalExternDecl() && OldVar->getPreviousDecl() &&
6103 OldVar->getPreviousDecl()->getDeclContext()==OldVar->getDeclContext())) {
6104 // We have a previous declaration. Use that one, so we merge with the
6105 // right type.
6106 if (NamedDecl *NewPrev = FindInstantiatedDecl(
6107 NewVar->getLocation(), OldVar->getPreviousDecl(), TemplateArgs))
6108 Previous.addDecl(NewPrev);
6109 } else if (!isa<VarTemplateSpecializationDecl>(NewVar) &&
6110 OldVar->hasLinkage()) {
6111 LookupQualifiedName(Previous, NewVar->getDeclContext(), false);
6112 } else if (PrevDeclForVarTemplateSpecialization) {
6113 Previous.addDecl(PrevDeclForVarTemplateSpecialization);
6114 }
6116
6117 if (!InstantiatingVarTemplate) {
6118 NewVar->getLexicalDeclContext()->addHiddenDecl(NewVar);
6119 if (!NewVar->isLocalExternDecl() || !NewVar->getPreviousDecl())
6120 NewVar->getDeclContext()->makeDeclVisibleInContext(NewVar);
6121 }
6122
6123 if (!OldVar->isOutOfLine()) {
6124 if (NewVar->getDeclContext()->isFunctionOrMethod())
6125 CurrentInstantiationScope->InstantiatedLocal(OldVar, NewVar);
6126 }
6127
6128 // Link instantiations of static data members back to the template from
6129 // which they were instantiated.
6130 //
6131 // Don't do this when instantiating a template (we link the template itself
6132 // back in that case) nor when instantiating a static data member template
6133 // (that's not a member specialization).
6134 if (NewVar->isStaticDataMember() && !InstantiatingVarTemplate &&
6135 !InstantiatingSpecFromTemplate)
6138
6139 // If the pattern is an (in-class) explicit specialization, then the result
6140 // is also an explicit specialization.
6141 if (VarTemplateSpecializationDecl *OldVTSD =
6142 dyn_cast<VarTemplateSpecializationDecl>(OldVar)) {
6143 if (OldVTSD->getSpecializationKind() == TSK_ExplicitSpecialization &&
6145 cast<VarTemplateSpecializationDecl>(NewVar)->setSpecializationKind(
6147 }
6148
6149 // Forward the mangling number from the template to the instantiated decl.
6150 Context.setManglingNumber(NewVar, Context.getManglingNumber(OldVar));
6151 Context.setStaticLocalNumber(NewVar, Context.getStaticLocalNumber(OldVar));
6152
6153 // Figure out whether to eagerly instantiate the initializer.
6154 if (InstantiatingVarTemplate || InstantiatingVarTemplatePartialSpec) {
6155 // We're producing a template. Don't instantiate the initializer yet.
6156 } else if (NewVar->getType()->isUndeducedType()) {
6157 // We need the type to complete the declaration of the variable.
6158 InstantiateVariableInitializer(NewVar, OldVar, TemplateArgs);
6159 } else if (InstantiatingSpecFromTemplate ||
6160 (OldVar->isInline() && OldVar->isThisDeclarationADefinition() &&
6161 !NewVar->isThisDeclarationADefinition())) {
6162 // Delay instantiation of the initializer for variable template
6163 // specializations or inline static data members until a definition of the
6164 // variable is needed.
6165 } else {
6166 InstantiateVariableInitializer(NewVar, OldVar, TemplateArgs);
6167 }
6168
6169 // Diagnose unused local variables with dependent types, where the diagnostic
6170 // will have been deferred.
6171 if (!NewVar->isInvalidDecl() &&
6172 NewVar->getDeclContext()->isFunctionOrMethod() &&
6173 OldVar->getType()->isDependentType())
6174 DiagnoseUnusedDecl(NewVar);
6175}
6176
6178 VarDecl *Var, VarDecl *OldVar,
6179 const MultiLevelTemplateArgumentList &TemplateArgs) {
6181 L->VariableDefinitionInstantiated(Var);
6182
6183 // We propagate the 'inline' flag with the initializer, because it
6184 // would otherwise imply that the variable is a definition for a
6185 // non-static data member.
6186 if (OldVar->isInlineSpecified())
6187 Var->setInlineSpecified();
6188 else if (OldVar->isInline())
6189 Var->setImplicitlyInline();
6190
6191 ContextRAII SwitchContext(*this, Var->getDeclContext());
6192
6200
6201 // Set DeclForInitializer for this variable so DiagIfReachable can properly
6202 // suppress runtime diagnostics for constexpr/static member variables
6204
6205 if (OldVar->getInit()) {
6206 // Instantiate the initializer.
6208 SubstInitializer(OldVar->getInit(), TemplateArgs,
6209 OldVar->getInitStyle() == VarDecl::CallInit);
6210
6211 if (!Init.isInvalid()) {
6212 Expr *InitExpr = Init.get();
6213
6214 if (Var->hasAttr<DLLImportAttr>() &&
6215 (!InitExpr ||
6216 !InitExpr->isConstantInitializer(getASTContext(), false))) {
6217 // Do not dynamically initialize dllimport variables.
6218 } else if (InitExpr) {
6219 bool DirectInit = OldVar->isDirectInit();
6220 AddInitializerToDecl(Var, InitExpr, DirectInit);
6221 } else
6223 } else {
6224 // FIXME: Not too happy about invalidating the declaration
6225 // because of a bogus initializer.
6226 Var->setInvalidDecl();
6227 }
6228 } else {
6229 // `inline` variables are a definition and declaration all in one; we won't
6230 // pick up an initializer from anywhere else.
6231 if (Var->isStaticDataMember() && !Var->isInline()) {
6232 if (!Var->isOutOfLine())
6233 return;
6234
6235 // If the declaration inside the class had an initializer, don't add
6236 // another one to the out-of-line definition.
6237 if (OldVar->getFirstDecl()->hasInit())
6238 return;
6239 }
6240
6241 // We'll add an initializer to a for-range declaration later.
6242 if (Var->isCXXForRangeDecl() || Var->isObjCForDecl())
6243 return;
6244
6246 }
6247
6248 if (getLangOpts().CUDA)
6250}
6251
6253 VarDecl *Var, bool Recursive,
6254 bool DefinitionRequired, bool AtEndOfTU) {
6255 if (Var->isInvalidDecl())
6256 return;
6257
6258 // Never instantiate an explicitly-specialized entity.
6261 if (TSK == TSK_ExplicitSpecialization)
6262 return;
6263
6264 RecursiveInstGuard AlreadyInstantiating(*this, Var,
6266 if (AlreadyInstantiating)
6267 return;
6268
6269 // Find the pattern and the arguments to substitute into it.
6270 VarDecl *PatternDecl = Var->getTemplateInstantiationPattern();
6271 assert(PatternDecl && "no pattern for templated variable");
6272 MultiLevelTemplateArgumentList TemplateArgs =
6274
6276 dyn_cast<VarTemplateSpecializationDecl>(Var);
6277 if (VarSpec) {
6278 // If this is a static data member template, there might be an
6279 // uninstantiated initializer on the declaration. If so, instantiate
6280 // it now.
6281 //
6282 // FIXME: This largely duplicates what we would do below. The difference
6283 // is that along this path we may instantiate an initializer from an
6284 // in-class declaration of the template and instantiate the definition
6285 // from a separate out-of-class definition.
6286 if (PatternDecl->isStaticDataMember() &&
6287 (PatternDecl = PatternDecl->getFirstDecl())->hasInit() &&
6288 !Var->hasInit()) {
6289 // FIXME: Factor out the duplicated instantiation context setup/tear down
6290 // code here.
6291 NonSFINAEContext _(*this);
6292 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
6293 if (Inst.isInvalid())
6294 return;
6296 "instantiating variable initializer");
6297
6298 // The instantiation is visible here, even if it was first declared in an
6299 // unimported module.
6301
6302 // If we're performing recursive template instantiation, create our own
6303 // queue of pending implicit instantiations that we will instantiate
6304 // later, while we're still within our own instantiation context.
6305 GlobalEagerInstantiationScope GlobalInstantiations(
6306 *this,
6307 /*Enabled=*/Recursive, /*AtEndOfTU=*/AtEndOfTU);
6308 LocalInstantiationScope Local(*this);
6309 LocalEagerInstantiationScope LocalInstantiations(*this,
6310 /*AtEndOfTU=*/AtEndOfTU);
6311
6312 // Enter the scope of this instantiation. We don't use
6313 // PushDeclContext because we don't have a scope.
6314 ContextRAII PreviousContext(*this, Var->getDeclContext());
6315 InstantiateVariableInitializer(Var, PatternDecl, TemplateArgs);
6316 PreviousContext.pop();
6317
6318 // This variable may have local implicit instantiations that need to be
6319 // instantiated within this scope.
6320 LocalInstantiations.perform();
6321 Local.Exit();
6322 GlobalInstantiations.perform();
6323 }
6324 } else {
6325 assert(Var->isStaticDataMember() && PatternDecl->isStaticDataMember() &&
6326 "not a static data member?");
6327 }
6328
6329 VarDecl *Def = PatternDecl->getDefinition(getASTContext());
6330
6331 // If we don't have a definition of the variable template, we won't perform
6332 // any instantiation. Rather, we rely on the user to instantiate this
6333 // definition (or provide a specialization for it) in another translation
6334 // unit.
6335 if (!Def && !DefinitionRequired) {
6337 PendingInstantiations.emplace_back(Var, PointOfInstantiation);
6338 } else if (TSK == TSK_ImplicitInstantiation) {
6339 // Warn about missing definition at the end of translation unit.
6340 if (AtEndOfTU && !getDiagnostics().hasErrorOccurred() &&
6341 !getSourceManager().isInSystemHeader(PatternDecl->getBeginLoc())) {
6342 Diag(PointOfInstantiation, diag::warn_var_template_missing)
6343 << Var;
6344 Diag(PatternDecl->getLocation(), diag::note_forward_template_decl);
6346 Diag(PointOfInstantiation, diag::note_inst_declaration_hint) << Var;
6347 }
6348 return;
6349 }
6350 }
6351
6352 // FIXME: We need to track the instantiation stack in order to know which
6353 // definitions should be visible within this instantiation.
6354 // FIXME: Produce diagnostics when Var->getInstantiatedFromStaticDataMember().
6355 if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Var,
6356 /*InstantiatedFromMember*/false,
6357 PatternDecl, Def, TSK,
6358 /*Complain*/DefinitionRequired))
6359 return;
6360
6361 // C++11 [temp.explicit]p10:
6362 // Except for inline functions, const variables of literal types, variables
6363 // of reference types, [...] explicit instantiation declarations
6364 // have the effect of suppressing the implicit instantiation of the entity
6365 // to which they refer.
6366 //
6367 // FIXME: That's not exactly the same as "might be usable in constant
6368 // expressions", which only allows constexpr variables and const integral
6369 // types, not arbitrary const literal types.
6372 return;
6373
6374 // Make sure to pass the instantiated variable to the consumer at the end.
6375 struct PassToConsumerRAII {
6377 VarDecl *Var;
6378
6379 PassToConsumerRAII(ASTConsumer &Consumer, VarDecl *Var)
6380 : Consumer(Consumer), Var(Var) { }
6381
6382 ~PassToConsumerRAII() {
6383 Consumer.HandleCXXStaticMemberVarInstantiation(Var);
6384 }
6385 } PassToConsumerRAII(Consumer, Var);
6386
6387 // If we already have a definition, we're done.
6388 if (VarDecl *Def = Var->getDefinition()) {
6389 // We may be explicitly instantiating something we've already implicitly
6390 // instantiated.
6392 PointOfInstantiation);
6393 return;
6394 }
6395
6396 NonSFINAEContext _(*this);
6397 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
6398 if (Inst.isInvalid())
6399 return;
6401 "instantiating variable definition");
6402
6403 // If we're performing recursive template instantiation, create our own
6404 // queue of pending implicit instantiations that we will instantiate later,
6405 // while we're still within our own instantiation context.
6406 GlobalEagerInstantiationScope GlobalInstantiations(*this,
6407 /*Enabled=*/Recursive,
6408 /*AtEndOfTU=*/AtEndOfTU);
6409
6410 // Enter the scope of this instantiation. We don't use
6411 // PushDeclContext because we don't have a scope.
6412 ContextRAII PreviousContext(*this, Var->getDeclContext());
6413 LocalInstantiationScope Local(*this);
6414
6415 LocalEagerInstantiationScope LocalInstantiations(*this,
6416 /*AtEndOfTU=*/AtEndOfTU);
6417
6418 VarDecl *OldVar = Var;
6419 if (Def->isStaticDataMember() && !Def->isOutOfLine()) {
6420 // We're instantiating an inline static data member whose definition was
6421 // provided inside the class.
6422 InstantiateVariableInitializer(Var, Def, TemplateArgs);
6423 } else if (!VarSpec) {
6424 Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(),
6425 TemplateArgs));
6426 } else if (Var->isStaticDataMember() &&
6427 Var->getLexicalDeclContext()->isRecord()) {
6428 // We need to instantiate the definition of a static data member template,
6429 // and all we have is the in-class declaration of it. Instantiate a separate
6430 // declaration of the definition.
6431 TemplateDeclInstantiator Instantiator(*this, Var->getDeclContext(),
6432 TemplateArgs);
6433
6434 TemplateArgumentListInfo TemplateArgInfo;
6435 if (const ASTTemplateArgumentListInfo *ArgInfo =
6436 VarSpec->getTemplateArgsAsWritten()) {
6437 TemplateArgInfo.setLAngleLoc(ArgInfo->getLAngleLoc());
6438 TemplateArgInfo.setRAngleLoc(ArgInfo->getRAngleLoc());
6439 for (const TemplateArgumentLoc &Arg : ArgInfo->arguments())
6440 TemplateArgInfo.addArgument(Arg);
6441 }
6442
6445 VarSpec->getSpecializedTemplate(), Def,
6446 VarSpec->getTemplateArgs().asArray(), VarSpec);
6447 Var = VTSD;
6448
6449 if (Var) {
6450 VTSD->setTemplateArgsAsWritten(TemplateArgInfo);
6451
6452 llvm::PointerUnion<VarTemplateDecl *,
6456 PatternPtr.dyn_cast<VarTemplatePartialSpecializationDecl *>())
6457 cast<VarTemplateSpecializationDecl>(Var)->setInstantiationOf(
6458 Partial, &VarSpec->getTemplateInstantiationArgs());
6459
6460 // Attach the initializer.
6461 InstantiateVariableInitializer(Var, Def, TemplateArgs);
6462 }
6463 } else
6464 // Complete the existing variable's definition with an appropriately
6465 // substituted type and initializer.
6466 Var = CompleteVarTemplateSpecializationDecl(VarSpec, Def, TemplateArgs);
6467
6468 PreviousContext.pop();
6469
6470 if (Var) {
6471 PassToConsumerRAII.Var = Var;
6473 OldVar->getPointOfInstantiation());
6474 // Emit any deferred warnings for the variable's initializer
6475 AnalysisWarnings.issueWarningsForRegisteredVarDecl(Var);
6476 }
6477
6478 // This variable may have local implicit instantiations that need to be
6479 // instantiated within this scope.
6480 LocalInstantiations.perform();
6481 Local.Exit();
6482 GlobalInstantiations.perform();
6483}
6484
6485void
6487 const CXXConstructorDecl *Tmpl,
6488 const MultiLevelTemplateArgumentList &TemplateArgs) {
6489
6491 bool AnyErrors = Tmpl->isInvalidDecl();
6492
6493 // Instantiate all the initializers.
6494 for (const auto *Init : Tmpl->inits()) {
6495 // Only instantiate written initializers, let Sema re-construct implicit
6496 // ones.
6497 if (!Init->isWritten())
6498 continue;
6499
6500 SourceLocation EllipsisLoc;
6501
6502 if (Init->isPackExpansion()) {
6503 // This is a pack expansion. We should expand it now.
6504 TypeLoc BaseTL = Init->getTypeSourceInfo()->getTypeLoc();
6506 collectUnexpandedParameterPacks(BaseTL, Unexpanded);
6507 collectUnexpandedParameterPacks(Init->getInit(), Unexpanded);
6508 bool ShouldExpand = false;
6509 bool RetainExpansion = false;
6510 UnsignedOrNone NumExpansions = std::nullopt;
6512 Init->getEllipsisLoc(), BaseTL.getSourceRange(), Unexpanded,
6513 TemplateArgs, /*FailOnPackProducingTemplates=*/true, ShouldExpand,
6514 RetainExpansion, NumExpansions)) {
6515 AnyErrors = true;
6516 New->setInvalidDecl();
6517 continue;
6518 }
6519 assert(ShouldExpand && "Partial instantiation of base initializer?");
6520
6521 // Loop over all of the arguments in the argument pack(s),
6522 for (unsigned I = 0; I != *NumExpansions; ++I) {
6523 Sema::ArgPackSubstIndexRAII SubstIndex(*this, I);
6524
6525 // Instantiate the initializer.
6526 ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs,
6527 /*CXXDirectInit=*/true);
6528 if (TempInit.isInvalid()) {
6529 AnyErrors = true;
6530 break;
6531 }
6532
6533 // Instantiate the base type.
6534 TypeSourceInfo *BaseTInfo = SubstType(Init->getTypeSourceInfo(),
6535 TemplateArgs,
6536 Init->getSourceLocation(),
6537 New->getDeclName());
6538 if (!BaseTInfo) {
6539 AnyErrors = true;
6540 break;
6541 }
6542
6543 // Build the initializer.
6544 MemInitResult NewInit = BuildBaseInitializer(BaseTInfo->getType(),
6545 BaseTInfo, TempInit.get(),
6546 New->getParent(),
6547 SourceLocation());
6548 if (NewInit.isInvalid()) {
6549 AnyErrors = true;
6550 break;
6551 }
6552
6553 NewInits.push_back(NewInit.get());
6554 }
6555
6556 continue;
6557 }
6558
6559 // Instantiate the initializer.
6560 ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs,
6561 /*CXXDirectInit=*/true);
6562 if (TempInit.isInvalid()) {
6563 AnyErrors = true;
6564 continue;
6565 }
6566
6567 MemInitResult NewInit;
6568 if (Init->isDelegatingInitializer() || Init->isBaseInitializer()) {
6569 TypeSourceInfo *TInfo = SubstType(Init->getTypeSourceInfo(),
6570 TemplateArgs,
6571 Init->getSourceLocation(),
6572 New->getDeclName());
6573 if (!TInfo) {
6574 AnyErrors = true;
6575 New->setInvalidDecl();
6576 continue;
6577 }
6578
6579 if (Init->isBaseInitializer())
6580 NewInit = BuildBaseInitializer(TInfo->getType(), TInfo, TempInit.get(),
6581 New->getParent(), EllipsisLoc);
6582 else
6583 NewInit = BuildDelegatingInitializer(TInfo, TempInit.get(),
6584 cast<CXXRecordDecl>(CurContext->getParent()));
6585 } else if (Init->isMemberInitializer()) {
6586 FieldDecl *Member = cast_or_null<FieldDecl>(FindInstantiatedDecl(
6587 Init->getMemberLocation(),
6588 Init->getMember(),
6589 TemplateArgs));
6590 if (!Member) {
6591 AnyErrors = true;
6592 New->setInvalidDecl();
6593 continue;
6594 }
6595
6596 NewInit = BuildMemberInitializer(Member, TempInit.get(),
6597 Init->getSourceLocation());
6598 } else if (Init->isIndirectMemberInitializer()) {
6599 IndirectFieldDecl *IndirectMember =
6600 cast_or_null<IndirectFieldDecl>(FindInstantiatedDecl(
6601 Init->getMemberLocation(),
6602 Init->getIndirectMember(), TemplateArgs));
6603
6604 if (!IndirectMember) {
6605 AnyErrors = true;
6606 New->setInvalidDecl();
6607 continue;
6608 }
6609
6610 NewInit = BuildMemberInitializer(IndirectMember, TempInit.get(),
6611 Init->getSourceLocation());
6612 }
6613
6614 if (NewInit.isInvalid()) {
6615 AnyErrors = true;
6616 New->setInvalidDecl();
6617 } else {
6618 NewInits.push_back(NewInit.get());
6619 }
6620 }
6621
6622 // Assign all the initializers to the new constructor.
6624 /*FIXME: ColonLoc */
6626 NewInits,
6627 AnyErrors);
6628}
6629
6630// TODO: this could be templated if the various decl types used the
6631// same method name.
6633 ClassTemplateDecl *Instance) {
6634 Pattern = Pattern->getCanonicalDecl();
6635
6636 do {
6637 Instance = Instance->getCanonicalDecl();
6638 if (Pattern == Instance) return true;
6639 Instance = Instance->getInstantiatedFromMemberTemplate();
6640 } while (Instance);
6641
6642 return false;
6643}
6644
6646 FunctionTemplateDecl *Instance) {
6647 Pattern = Pattern->getCanonicalDecl();
6648
6649 do {
6650 Instance = Instance->getCanonicalDecl();
6651 if (Pattern == Instance) return true;
6652 Instance = Instance->getInstantiatedFromMemberTemplate();
6653 } while (Instance);
6654
6655 return false;
6656}
6657
6658static bool
6661 Pattern
6663 do {
6665 Instance->getCanonicalDecl());
6666 if (Pattern == Instance)
6667 return true;
6668 Instance = Instance->getInstantiatedFromMember();
6669 } while (Instance);
6670
6671 return false;
6672}
6673
6675 CXXRecordDecl *Instance) {
6676 Pattern = Pattern->getCanonicalDecl();
6677
6678 do {
6679 Instance = Instance->getCanonicalDecl();
6680 if (Pattern == Instance) return true;
6681 Instance = Instance->getInstantiatedFromMemberClass();
6682 } while (Instance);
6683
6684 return false;
6685}
6686
6687static bool isInstantiationOf(FunctionDecl *Pattern,
6688 FunctionDecl *Instance) {
6689 Pattern = Pattern->getCanonicalDecl();
6690
6691 do {
6692 Instance = Instance->getCanonicalDecl();
6693 if (Pattern == Instance) return true;
6694 Instance = Instance->getInstantiatedFromMemberFunction();
6695 } while (Instance);
6696
6697 return false;
6698}
6699
6700static bool isInstantiationOf(EnumDecl *Pattern,
6701 EnumDecl *Instance) {
6702 Pattern = Pattern->getCanonicalDecl();
6703
6704 do {
6705 Instance = Instance->getCanonicalDecl();
6706 if (Pattern == Instance) return true;
6707 Instance = Instance->getInstantiatedFromMemberEnum();
6708 } while (Instance);
6709
6710 return false;
6711}
6712
6714 UsingShadowDecl *Instance,
6715 ASTContext &C) {
6716 return declaresSameEntity(C.getInstantiatedFromUsingShadowDecl(Instance),
6717 Pattern);
6718}
6719
6720static bool isInstantiationOf(UsingDecl *Pattern, UsingDecl *Instance,
6721 ASTContext &C) {
6722 return declaresSameEntity(C.getInstantiatedFromUsingDecl(Instance), Pattern);
6723}
6724
6725template<typename T>
6727 ASTContext &Ctx) {
6728 // An unresolved using declaration can instantiate to an unresolved using
6729 // declaration, or to a using declaration or a using declaration pack.
6730 //
6731 // Multiple declarations can claim to be instantiated from an unresolved
6732 // using declaration if it's a pack expansion. We want the UsingPackDecl
6733 // in that case, not the individual UsingDecls within the pack.
6734 bool OtherIsPackExpansion;
6735 NamedDecl *OtherFrom;
6736 if (auto *OtherUUD = dyn_cast<T>(Other)) {
6737 OtherIsPackExpansion = OtherUUD->isPackExpansion();
6738 OtherFrom = Ctx.getInstantiatedFromUsingDecl(OtherUUD);
6739 } else if (auto *OtherUPD = dyn_cast<UsingPackDecl>(Other)) {
6740 OtherIsPackExpansion = true;
6741 OtherFrom = OtherUPD->getInstantiatedFromUsingDecl();
6742 } else if (auto *OtherUD = dyn_cast<UsingDecl>(Other)) {
6743 OtherIsPackExpansion = false;
6744 OtherFrom = Ctx.getInstantiatedFromUsingDecl(OtherUD);
6745 } else {
6746 return false;
6747 }
6748 return Pattern->isPackExpansion() == OtherIsPackExpansion &&
6749 declaresSameEntity(OtherFrom, Pattern);
6750}
6751
6753 VarDecl *Instance) {
6754 assert(Instance->isStaticDataMember());
6755
6756 Pattern = Pattern->getCanonicalDecl();
6757
6758 do {
6759 Instance = Instance->getCanonicalDecl();
6760 if (Pattern == Instance) return true;
6761 Instance = Instance->getInstantiatedFromStaticDataMember();
6762 } while (Instance);
6763
6764 return false;
6765}
6766
6767// Other is the prospective instantiation
6768// D is the prospective pattern
6770 if (auto *UUD = dyn_cast<UnresolvedUsingTypenameDecl>(D))
6772
6773 if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(D))
6775
6776 if (D->getKind() != Other->getKind())
6777 return false;
6778
6779 if (auto *Record = dyn_cast<CXXRecordDecl>(Other))
6781
6782 if (auto *Function = dyn_cast<FunctionDecl>(Other))
6783 return isInstantiationOf(cast<FunctionDecl>(D), Function);
6784
6785 if (auto *Enum = dyn_cast<EnumDecl>(Other))
6787
6788 if (auto *Var = dyn_cast<VarDecl>(Other))
6789 if (Var->isStaticDataMember())
6791
6792 if (auto *Temp = dyn_cast<ClassTemplateDecl>(Other))
6794
6795 if (auto *Temp = dyn_cast<FunctionTemplateDecl>(Other))
6797
6798 if (auto *PartialSpec =
6799 dyn_cast<ClassTemplatePartialSpecializationDecl>(Other))
6801 PartialSpec);
6802
6803 if (auto *Field = dyn_cast<FieldDecl>(Other)) {
6804 if (!Field->getDeclName()) {
6805 // This is an unnamed field.
6807 cast<FieldDecl>(D));
6808 }
6809 }
6810
6811 if (auto *Using = dyn_cast<UsingDecl>(Other))
6812 return isInstantiationOf(cast<UsingDecl>(D), Using, Ctx);
6813
6814 if (auto *Shadow = dyn_cast<UsingShadowDecl>(Other))
6815 return isInstantiationOf(cast<UsingShadowDecl>(D), Shadow, Ctx);
6816
6817 return D->getDeclName() &&
6818 D->getDeclName() == cast<NamedDecl>(Other)->getDeclName();
6819}
6820
6821template<typename ForwardIterator>
6823 NamedDecl *D,
6824 ForwardIterator first,
6825 ForwardIterator last) {
6826 for (; first != last; ++first)
6827 if (isInstantiationOf(Ctx, D, *first))
6828 return cast<NamedDecl>(*first);
6829
6830 return nullptr;
6831}
6832
6834 const MultiLevelTemplateArgumentList &TemplateArgs) {
6835 if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) {
6836 Decl* ID = FindInstantiatedDecl(Loc, D, TemplateArgs, true);
6837 return cast_or_null<DeclContext>(ID);
6838 } else return DC;
6839}
6840
6841/// Determine whether the given context is dependent on template parameters at
6842/// level \p Level or below.
6843///
6844/// Sometimes we only substitute an inner set of template arguments and leave
6845/// the outer templates alone. In such cases, contexts dependent only on the
6846/// outer levels are not effectively dependent.
6847static bool isDependentContextAtLevel(DeclContext *DC, unsigned Level) {
6848 if (!DC->isDependentContext())
6849 return false;
6850 if (!Level)
6851 return true;
6852 return cast<Decl>(DC)->getTemplateDepth() > Level;
6853}
6854
6856 const MultiLevelTemplateArgumentList &TemplateArgs,
6857 bool FindingInstantiatedContext) {
6858 DeclContext *ParentDC = D->getDeclContext();
6859 // Determine whether our parent context depends on any of the template
6860 // arguments we're currently substituting.
6861 bool ParentDependsOnArgs = isDependentContextAtLevel(
6862 ParentDC, TemplateArgs.getNumRetainedOuterLevels());
6863 // FIXME: Parameters of pointer to functions (y below) that are themselves
6864 // parameters (p below) can have their ParentDC set to the translation-unit
6865 // - thus we can not consistently check if the ParentDC of such a parameter
6866 // is Dependent or/and a FunctionOrMethod.
6867 // For e.g. this code, during Template argument deduction tries to
6868 // find an instantiated decl for (T y) when the ParentDC for y is
6869 // the translation unit.
6870 // e.g. template <class T> void Foo(auto (*p)(T y) -> decltype(y())) {}
6871 // float baz(float(*)()) { return 0.0; }
6872 // Foo(baz);
6873 // The better fix here is perhaps to ensure that a ParmVarDecl, by the time
6874 // it gets here, always has a FunctionOrMethod as its ParentDC??
6875 // For now:
6876 // - as long as we have a ParmVarDecl whose parent is non-dependent and
6877 // whose type is not instantiation dependent, do nothing to the decl
6878 // - otherwise find its instantiated decl.
6879 if (isa<ParmVarDecl>(D) && !ParentDependsOnArgs &&
6880 !cast<ParmVarDecl>(D)->getType()->isInstantiationDependentType())
6881 return D;
6884 (ParentDependsOnArgs && (ParentDC->isFunctionOrMethod() ||
6885 isa<OMPDeclareReductionDecl>(ParentDC) ||
6886 isa<OMPDeclareMapperDecl>(ParentDC))) ||
6887 (isa<CXXRecordDecl>(D) && cast<CXXRecordDecl>(D)->isLambda() &&
6888 cast<CXXRecordDecl>(D)->getTemplateDepth() >
6889 TemplateArgs.getNumRetainedOuterLevels())) {
6890 // D is a local of some kind. Look into the map of local
6891 // declarations to their instantiations.
6893 if (auto Found = CurrentInstantiationScope->findInstantiationOf(D)) {
6894 if (Decl *FD = Found->dyn_cast<Decl *>()) {
6895 if (auto *BD = dyn_cast<BindingDecl>(FD);
6896 BD && BD->isParameterPack() && ArgPackSubstIndex) {
6897 return BD->getBindingPackDecls()[*ArgPackSubstIndex];
6898 }
6899 return cast<NamedDecl>(FD);
6900 }
6901
6902 assert(ArgPackSubstIndex &&
6903 "found declaration pack but not pack expanding");
6904 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
6905 return cast<NamedDecl>(
6907 }
6908 }
6909
6910 // If we're performing a partial substitution during template argument
6911 // deduction, we may not have values for template parameters yet. They
6912 // just map to themselves.
6915 return D;
6916
6917 if (D->isInvalidDecl())
6918 return nullptr;
6919
6920 // Normally this function only searches for already instantiated declaration
6921 // however we have to make an exclusion for local types used before
6922 // definition as in the code:
6923 //
6924 // template<typename T> void f1() {
6925 // void g1(struct x1);
6926 // struct x1 {};
6927 // }
6928 //
6929 // In this case instantiation of the type of 'g1' requires definition of
6930 // 'x1', which is defined later. Error recovery may produce an enum used
6931 // before definition. In these cases we need to instantiate relevant
6932 // declarations here.
6933 bool NeedInstantiate = false;
6934 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
6935 NeedInstantiate = RD->isLocalClass();
6936 else if (isa<TypedefNameDecl>(D) &&
6938 NeedInstantiate = true;
6939 else
6940 NeedInstantiate = isa<EnumDecl>(D);
6941 if (NeedInstantiate) {
6942 Decl *Inst = SubstDecl(D, CurContext, TemplateArgs);
6943 CurrentInstantiationScope->InstantiatedLocal(D, Inst);
6944 return cast<TypeDecl>(Inst);
6945 }
6946
6947 // If we didn't find the decl, then we must have a label decl that hasn't
6948 // been found yet. Lazily instantiate it and return it now.
6949 assert(isa<LabelDecl>(D));
6950
6951 Decl *Inst = SubstDecl(D, CurContext, TemplateArgs);
6952 assert(Inst && "Failed to instantiate label??");
6953
6954 CurrentInstantiationScope->InstantiatedLocal(D, Inst);
6955 return cast<LabelDecl>(Inst);
6956 }
6957
6958 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
6959 if (!Record->isDependentContext())
6960 return D;
6961
6962 // Determine whether this record is the "templated" declaration describing
6963 // a class template or class template specialization.
6964 ClassTemplateDecl *ClassTemplate = Record->getDescribedClassTemplate();
6965 if (ClassTemplate)
6966 ClassTemplate = ClassTemplate->getCanonicalDecl();
6967 else if (ClassTemplateSpecializationDecl *Spec =
6968 dyn_cast<ClassTemplateSpecializationDecl>(Record))
6969 ClassTemplate = Spec->getSpecializedTemplate()->getCanonicalDecl();
6970
6971 // Walk the current context to find either the record or an instantiation of
6972 // it.
6973 DeclContext *DC = CurContext;
6974 while (!DC->isFileContext()) {
6975 // If we're performing substitution while we're inside the template
6976 // definition, we'll find our own context. We're done.
6977 if (DC->Equals(Record))
6978 return Record;
6979
6980 if (CXXRecordDecl *InstRecord = dyn_cast<CXXRecordDecl>(DC)) {
6981 // Check whether we're in the process of instantiating a class template
6982 // specialization of the template we're mapping.
6984 = dyn_cast<ClassTemplateSpecializationDecl>(InstRecord)){
6985 ClassTemplateDecl *SpecTemplate = InstSpec->getSpecializedTemplate();
6986 if (ClassTemplate && isInstantiationOf(ClassTemplate, SpecTemplate))
6987 return InstRecord;
6988 }
6989
6990 // Check whether we're in the process of instantiating a member class.
6991 if (isInstantiationOf(Record, InstRecord))
6992 return InstRecord;
6993 }
6994
6995 // Move to the outer template scope.
6996 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC)) {
6997 if (FD->getFriendObjectKind() &&
6999 DC = FD->getLexicalDeclContext();
7000 continue;
7001 }
7002 // An implicit deduction guide acts as if it's within the class template
7003 // specialization described by its name and first N template params.
7004 auto *Guide = dyn_cast<CXXDeductionGuideDecl>(FD);
7005 if (Guide && Guide->isImplicit()) {
7006 TemplateDecl *TD = Guide->getDeducedTemplate();
7007 // Convert the arguments to an "as-written" list.
7008 TemplateArgumentListInfo Args(Loc, Loc);
7009 for (TemplateArgument Arg : TemplateArgs.getInnermost().take_front(
7010 TD->getTemplateParameters()->size())) {
7011 ArrayRef<TemplateArgument> Unpacked(Arg);
7012 if (Arg.getKind() == TemplateArgument::Pack)
7013 Unpacked = Arg.pack_elements();
7014 for (TemplateArgument UnpackedArg : Unpacked)
7015 Args.addArgument(
7016 getTrivialTemplateArgumentLoc(UnpackedArg, QualType(), Loc));
7017 }
7020 /*Scope=*/nullptr, /*ForNestedNameSpecifier=*/false);
7021 // We may get a non-null type with errors, in which case
7022 // `getAsCXXRecordDecl` will return `nullptr`. For instance, this
7023 // happens when one of the template arguments is an invalid
7024 // expression. We return early to avoid triggering the assertion
7025 // about the `CodeSynthesisContext`.
7026 if (T.isNull() || T->containsErrors())
7027 return nullptr;
7028 CXXRecordDecl *SubstRecord = T->getAsCXXRecordDecl();
7029
7030 if (!SubstRecord) {
7031 // T can be a dependent TemplateSpecializationType when performing a
7032 // substitution for building a deduction guide or for template
7033 // argument deduction in the process of rebuilding immediate
7034 // expressions. (Because the default argument that involves a lambda
7035 // is untransformed and thus could be dependent at this point.)
7036 assert(SemaRef.RebuildingImmediateInvocation ||
7037 CodeSynthesisContexts.back().Kind ==
7039 // Return a nullptr as a sentinel value, we handle it properly in
7040 // the TemplateInstantiator::TransformInjectedClassNameType
7041 // override, which we transform it to a TemplateSpecializationType.
7042 return nullptr;
7043 }
7044 // Check that this template-id names the primary template and not a
7045 // partial or explicit specialization. (In the latter cases, it's
7046 // meaningless to attempt to find an instantiation of D within the
7047 // specialization.)
7048 // FIXME: The standard doesn't say what should happen here.
7049 if (FindingInstantiatedContext &&
7051 Loc, cast<ClassTemplateSpecializationDecl>(SubstRecord))) {
7052 Diag(Loc, diag::err_specialization_not_primary_template)
7053 << T << (SubstRecord->getTemplateSpecializationKind() ==
7055 return nullptr;
7056 }
7057 DC = SubstRecord;
7058 continue;
7059 }
7060 }
7061
7062 DC = DC->getParent();
7063 }
7064
7065 // Fall through to deal with other dependent record types (e.g.,
7066 // anonymous unions in class templates).
7067 }
7068
7069 if (!ParentDependsOnArgs)
7070 return D;
7071
7072 ParentDC = FindInstantiatedContext(Loc, ParentDC, TemplateArgs);
7073 if (!ParentDC)
7074 return nullptr;
7075
7076 if (ParentDC != D->getDeclContext()) {
7077 // We performed some kind of instantiation in the parent context,
7078 // so now we need to look into the instantiated parent context to
7079 // find the instantiation of the declaration D.
7080
7081 // If our context used to be dependent, we may need to instantiate
7082 // it before performing lookup into that context.
7083 bool IsBeingInstantiated = false;
7084 if (auto *Spec = dyn_cast<CXXRecordDecl>(ParentDC)) {
7085 if (!Spec->isDependentContext()) {
7086 if (Spec->isEntityBeingDefined())
7087 IsBeingInstantiated = true;
7088 else if (RequireCompleteType(Loc, Context.getCanonicalTagType(Spec),
7089 diag::err_incomplete_type))
7090 return nullptr;
7091
7092 ParentDC = Spec->getDefinitionOrSelf();
7093 }
7094 }
7095
7096 NamedDecl *Result = nullptr;
7097 // FIXME: If the name is a dependent name, this lookup won't necessarily
7098 // find it. Does that ever matter?
7099 if (auto Name = D->getDeclName()) {
7100 DeclarationNameInfo NameInfo(Name, D->getLocation());
7101 DeclarationNameInfo NewNameInfo =
7102 SubstDeclarationNameInfo(NameInfo, TemplateArgs);
7103 Name = NewNameInfo.getName();
7104 if (!Name)
7105 return nullptr;
7106 DeclContext::lookup_result Found = ParentDC->lookup(Name);
7107
7108 Result = findInstantiationOf(Context, D, Found.begin(), Found.end());
7109 } else {
7110 // Since we don't have a name for the entity we're looking for,
7111 // our only option is to walk through all of the declarations to
7112 // find that name. This will occur in a few cases:
7113 //
7114 // - anonymous struct/union within a template
7115 // - unnamed class/struct/union/enum within a template
7116 //
7117 // FIXME: Find a better way to find these instantiations!
7119 ParentDC->decls_begin(),
7120 ParentDC->decls_end());
7121 }
7122
7123 if (!Result) {
7124 if (isa<UsingShadowDecl>(D)) {
7125 // UsingShadowDecls can instantiate to nothing because of using hiding.
7126 } else if (hasUncompilableErrorOccurred()) {
7127 // We've already complained about some ill-formed code, so most likely
7128 // this declaration failed to instantiate. There's no point in
7129 // complaining further, since this is normal in invalid code.
7130 // FIXME: Use more fine-grained 'invalid' tracking for this.
7131 } else if (IsBeingInstantiated) {
7132 // The class in which this member exists is currently being
7133 // instantiated, and we haven't gotten around to instantiating this
7134 // member yet. This can happen when the code uses forward declarations
7135 // of member classes, and introduces ordering dependencies via
7136 // template instantiation.
7137 Diag(Loc, diag::err_member_not_yet_instantiated)
7138 << D->getDeclName()
7139 << Context.getCanonicalTagType(cast<CXXRecordDecl>(ParentDC));
7140 Diag(D->getLocation(), diag::note_non_instantiated_member_here);
7141 } else if (EnumConstantDecl *ED = dyn_cast<EnumConstantDecl>(D)) {
7142 // This enumeration constant was found when the template was defined,
7143 // but can't be found in the instantiation. This can happen if an
7144 // unscoped enumeration member is explicitly specialized.
7145 EnumDecl *Enum = cast<EnumDecl>(ED->getLexicalDeclContext());
7147 TemplateArgs));
7148 assert(Spec->getTemplateSpecializationKind() ==
7150 Diag(Loc, diag::err_enumerator_does_not_exist)
7151 << D->getDeclName()
7152 << Context.getTypeDeclType(cast<TypeDecl>(Spec->getDeclContext()));
7153 Diag(Spec->getLocation(), diag::note_enum_specialized_here)
7154 << Context.getCanonicalTagType(Spec);
7155 } else {
7156 // We should have found something, but didn't.
7157 llvm_unreachable("Unable to find instantiation of declaration!");
7158 }
7159 }
7160
7161 D = Result;
7162 }
7163
7164 return D;
7165}
7166
7167void Sema::PerformPendingInstantiations(bool LocalOnly, bool AtEndOfTU) {
7168 std::deque<PendingImplicitInstantiation> DelayedImplicitInstantiations;
7169 while (!PendingLocalImplicitInstantiations.empty() ||
7170 (!LocalOnly && !PendingInstantiations.empty())) {
7172
7173 bool LocalInstantiation = false;
7175 Inst = PendingInstantiations.front();
7176 PendingInstantiations.pop_front();
7177 } else {
7180 LocalInstantiation = true;
7181 }
7182
7183 // Instantiate function definitions
7184 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) {
7185 bool DefinitionRequired = Function->getTemplateSpecializationKind() ==
7187 if (Function->isMultiVersion()) {
7189 Function,
7190 [this, Inst, DefinitionRequired, AtEndOfTU](FunctionDecl *CurFD) {
7191 InstantiateFunctionDefinition(/*FIXME:*/ Inst.second, CurFD, true,
7192 DefinitionRequired, AtEndOfTU);
7193 if (CurFD->isDefined())
7194 CurFD->setInstantiationIsPending(false);
7195 });
7196 } else {
7197 InstantiateFunctionDefinition(/*FIXME:*/ Inst.second, Function, true,
7198 DefinitionRequired, AtEndOfTU);
7199 if (Function->isDefined())
7200 Function->setInstantiationIsPending(false);
7201 }
7202 // Definition of a PCH-ed template declaration may be available only in the TU.
7203 if (!LocalOnly && LangOpts.PCHInstantiateTemplates &&
7204 TUKind == TU_Prefix && Function->instantiationIsPending())
7205 DelayedImplicitInstantiations.push_back(Inst);
7206 else if (!AtEndOfTU && Function->instantiationIsPending() &&
7207 !LocalInstantiation)
7208 DelayedImplicitInstantiations.push_back(Inst);
7209 continue;
7210 }
7211
7212 // Instantiate variable definitions
7213 VarDecl *Var = cast<VarDecl>(Inst.first);
7214
7215 assert((Var->isStaticDataMember() ||
7217 "Not a static data member, nor a variable template"
7218 " specialization?");
7219
7220 // Don't try to instantiate declarations if the most recent redeclaration
7221 // is invalid.
7222 if (Var->getMostRecentDecl()->isInvalidDecl())
7223 continue;
7224
7225 // Check if the most recent declaration has changed the specialization kind
7226 // and removed the need for implicit instantiation.
7227 switch (Var->getMostRecentDecl()
7229 case TSK_Undeclared:
7230 llvm_unreachable("Cannot instantitiate an undeclared specialization.");
7233 continue; // No longer need to instantiate this type.
7235 // We only need an instantiation if the pending instantiation *is* the
7236 // explicit instantiation.
7237 if (Var != Var->getMostRecentDecl())
7238 continue;
7239 break;
7241 break;
7242 }
7243
7245 "instantiating variable definition");
7246 bool DefinitionRequired = Var->getTemplateSpecializationKind() ==
7248
7249 // Instantiate static data member definitions or variable template
7250 // specializations.
7251 InstantiateVariableDefinition(/*FIXME:*/ Inst.second, Var, true,
7252 DefinitionRequired, AtEndOfTU);
7253 }
7254
7255 if (!DelayedImplicitInstantiations.empty())
7256 PendingInstantiations.swap(DelayedImplicitInstantiations);
7257}
7258
7260 const MultiLevelTemplateArgumentList &TemplateArgs) {
7261 for (auto *DD : Pattern->ddiags()) {
7262 switch (DD->getKind()) {
7264 HandleDependentAccessCheck(*DD, TemplateArgs);
7265 break;
7266 }
7267 }
7268}
Defines the clang::ASTContext interface.
Defines the C++ template declaration subclasses.
Defines the clang::Expr interface and subclasses for C++ expressions.
TokenType getType() const
Returns the token's type, e.g.
FormatToken * Previous
The previous token in the unwrapped line.
FormatToken * Next
The next token in the unwrapped line.
#define X(type, name)
Definition Value.h:97
llvm::MachO::Record Record
Definition MachO.h:31
@ ForExternalRedeclaration
The lookup results will be used for redeclaration of a name with external linkage; non-visible lookup...
@ ForVisibleRedeclaration
The lookup results will be used for redeclaration of a name, if an entity by that name already exists...
llvm::SmallVector< std::pair< const MemRegion *, SVal >, 4 > Bindings
static std::string toString(const clang::SanitizerSet &Sanitizers)
Produce a string containing comma-separated names of sanitizers in Sanitizers set.
This file declares semantic analysis functions specific to AMDGPU.
static bool hasAttr(const Decl *D, bool IgnoreImplicitAttr)
Definition SemaCUDA.cpp:109
This file declares semantic analysis for CUDA constructs.
static const NamedDecl * getDefinition(const Decl *D)
This file declares semantic analysis for HLSL constructs.
This file declares semantic analysis for Objective-C.
This file declares semantic analysis for OpenMP constructs and clauses.
This file declares semantic analysis functions specific to Swift.
static void instantiateDependentAMDGPUWavesPerEUAttr(Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, const AMDGPUWavesPerEUAttr &Attr, Decl *New)
static NamedDecl * findInstantiationOf(ASTContext &Ctx, NamedDecl *D, ForwardIterator first, ForwardIterator last)
static void instantiateDependentAMDGPUMaxNumWorkGroupsAttr(Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, const AMDGPUMaxNumWorkGroupsAttr &Attr, Decl *New)
static void instantiateDependentAMDGPUFlatWorkGroupSizeAttr(Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, const AMDGPUFlatWorkGroupSizeAttr &Attr, Decl *New)
static void instantiateDependentCUDAClusterDimsAttr(Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, const CUDAClusterDimsAttr &Attr, Decl *New)
static void sharedInstantiateConstructorDestructorAttr(Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, const Attr *A, Decl *New, ASTContext &C)
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 void instantiateDependentReqdWorkGroupSizeAttr(Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, const ReqdWorkGroupSizeAttr &Attr, Decl *New)
#define CLAUSE_NOT_ON_DECLS(CLAUSE_NAME)
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 void instantiateDependentHLSLParamModifierAttr(Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, const HLSLParamModifierAttr *Attr, const Decl *Old, Decl *New)
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 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 void instantiateDependentOpenACCRoutineDeclAttr(Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, const OpenACCRoutineDeclAttr *OldAttr, const Decl *Old, Decl *New)
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.
ASTConsumer - This is an abstract interface that should be implemented by clients that read ASTs.
Definition ASTConsumer.h:34
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:220
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:788
void forEachMultiversionedFunctionVersion(const FunctionDecl *FD, llvm::function_ref< void(FunctionDecl *)> Pred) const
Visits all versions of a multiversioned function with the passed predicate.
OMPTraitInfo & getNewOMPTraitInfo()
Return a new OMPTraitInfo object owned by this context.
FieldDecl * getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) const
CanQualType UnsignedLongLongTy
static bool hasSameType(QualType T1, QualType T2)
Determine whether the given types T1 and T2 are equivalent.
CanQualType getCanonicalTagType(const TagDecl *TD) const
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:171
bool isInvalid() const
Definition Ownership.h:167
bool isUsable() const
Definition Ownership.h:169
Attr - This represents one attribute.
Definition Attr.h:45
attr::Kind getKind() const
Definition Attr.h:91
Attr * clone(ASTContext &C) const
SourceLocation getLocation() const
Definition Attr.h:98
SourceLocation getLoc() const
Represents a C++ declaration that introduces decls from somewhere else.
Definition DeclCXX.h:3492
shadow_range shadows() const
Definition DeclCXX.h:3558
A binding in a decomposition declaration.
Definition DeclCXX.h:4181
static BindingDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation IdLoc, IdentifierInfo *Id, QualType T)
Definition DeclCXX.cpp:3647
ArrayRef< BindingDecl * > getBindingPackDecls() const
Definition DeclCXX.cpp:3671
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:2604
bool isDefaultConstructor() const
Whether this constructor is a default constructor (C++ [class.ctor]p5), which can be used to default-...
Definition DeclCXX.cpp:2999
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(), const AssociatedConstraint &TrailingRequiresClause={})
Definition DeclCXX.cpp:2968
Represents a C++ conversion function within a class.
Definition DeclCXX.h:2939
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, const AssociatedConstraint &TrailingRequiresClause={})
Definition DeclCXX.cpp:3223
Represents a C++ deduction guide declaration.
Definition DeclCXX.h:1979
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, const AssociatedConstraint &TrailingRequiresClause={}, const CXXDeductionGuideDecl *SourceDG=nullptr, SourceDeductionGuideKind SK=SourceDeductionGuideKind::None)
Definition DeclCXX.cpp:2367
Represents a C++ destructor within a class.
Definition DeclCXX.h:2869
static CXXDestructorDecl * Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc, const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, bool UsesFPIntrin, bool isInline, bool isImplicitlyDeclared, ConstexprSpecKind ConstexprKind, const AssociatedConstraint &TrailingRequiresClause={})
Definition DeclCXX.cpp:3098
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2129
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, const AssociatedConstraint &TrailingRequiresClause={})
Definition DeclCXX.cpp:2488
bool isStatic() const
Definition DeclCXX.cpp:2401
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
static CXXRecordDecl * Create(const ASTContext &C, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, CXXRecordDecl *PrevDecl=nullptr)
Definition DeclCXX.cpp:132
bool isGenericLambda() const
Determine whether this class describes a generic lambda function object (i.e.
Definition DeclCXX.cpp:1673
unsigned getLambdaDependencyKind() const
Definition DeclCXX.h:1854
const FunctionDecl * isLocalClass() const
If the class is a local class [class.local], returns the enclosing function declaration.
Definition DeclCXX.h:1554
bool isLambda() const
Determine whether this class describes a lambda function object.
Definition DeclCXX.h:1018
CXXRecordDecl * getDefinition() const
Definition DeclCXX.h:548
static CXXRecordDecl * CreateLambda(const ASTContext &C, DeclContext *DC, TypeSourceInfo *Info, SourceLocation Loc, unsigned DependencyKind, bool IsGeneric, LambdaCaptureDefault CaptureDefault)
Definition DeclCXX.cpp:141
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine whether this particular class is a specialization or instantiation of a class template or m...
Definition DeclCXX.cpp:2050
TypeSourceInfo * getLambdaTypeInfo() const
Definition DeclCXX.h:1860
void setInstantiationOfMemberClass(CXXRecordDecl *RD, TemplateSpecializationKind TSK)
Specify that this record is an instantiation of the member class RD.
Definition DeclCXX.cpp:2033
bool isInjectedClassName() const
Determines whether this declaration represents the injected class name.
Definition DeclCXX.cpp:2146
LambdaCaptureDefault getLambdaCaptureDefault() const
Definition DeclCXX.h:1059
void setDescribedClassTemplate(ClassTemplateDecl *Template)
Definition DeclCXX.cpp:2046
CXXRecordDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition DeclCXX.h:522
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:103
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 the given declaration.
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)
Common * getCommonPtr() const
ClassTemplateSpecializationDecl * findSpecialization(ArrayRef< TemplateArgument > Args, void *&InsertPos)
Return the specialization with the provided arguments if it exists, otherwise return the insertion po...
void setInstantiatedFromMember(ClassTemplatePartialSpecializationDecl *PartialSpec)
static ClassTemplatePartialSpecializationDecl * Create(ASTContext &Context, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, TemplateParameterList *Params, ClassTemplateDecl *SpecializedTemplate, ArrayRef< TemplateArgument > Args, CanQualType CanonInjectedTST, ClassTemplatePartialSpecializationDecl *PrevDecl)
TemplateParameterList * getTemplateParameters() const
Get the list of template parameters.
Represents a class template specialization, which refers to a class template with a given set of temp...
TemplateSpecializationKind getSpecializationKind() const
Determine the kind of specialization that this declaration represents.
const ASTTemplateArgumentListInfo * getTemplateArgsAsWritten() const
Retrieve the template argument list as written in the sources, if any.
ClassTemplateDecl * getSpecializedTemplate() const
Retrieve the template that this specialization specializes.
static ClassTemplateSpecializationDecl * Create(ASTContext &Context, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, ClassTemplateDecl *SpecializedTemplate, ArrayRef< TemplateArgument > Args, bool StrictPackMatch, ClassTemplateSpecializationDecl *PrevDecl)
SourceLocation getPointOfInstantiation() const
Get the point of instantiation (if any), or null if none.
void setExternKeywordLoc(SourceLocation Loc)
Sets the location of the extern keyword.
void setSpecializationKind(TemplateSpecializationKind TSK)
SourceLocation getExternKeywordLoc() const
Gets the location of the extern keyword, if present.
SourceLocation getTemplateKeywordLoc() const
Gets the location of the template keyword, if present.
void setTemplateKeywordLoc(SourceLocation Loc)
Sets the location of the template keyword.
void setTemplateArgsAsWritten(const ASTTemplateArgumentListInfo *ArgsWritten)
Set the template argument list as written in the sources.
Declaration of a C++20 concept.
const TypeClass * getTypePtr() const
Definition TypeLoc.h:433
Represents a shadow constructor declaration introduced into a class by a C++11 using-declaration that...
Definition DeclCXX.h:3673
A POD class for pairing a NamedDecl* with an access specifier.
static DeclAccessPair make(NamedDecl *D, AccessSpecifier AS)
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition DeclBase.h:1449
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition DeclBase.h:2109
bool Equals(const DeclContext *DC) const
Determine whether this declaration context is equivalent to the declaration context DC.
Definition DeclBase.h:2238
bool isFileContext() const
Definition DeclBase.h:2180
void makeDeclVisibleInContext(NamedDecl *D)
Makes a declaration visible within this context.
DeclContextLookupResult lookup_result
Definition DeclBase.h:2577
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
bool isRecord() const
Definition DeclBase.h:2189
DeclContext * getRedeclContext()
getRedeclContext - Retrieve the context in which an entity conflicts with other entities of the same ...
void addDecl(Decl *D)
Add the declaration D into this context.
decl_iterator decls_end() const
Definition DeclBase.h:2375
ddiag_range ddiags() const
decl_range decls() const
decls_begin/decls_end - Iterate over the declarations stored in this context.
Definition DeclBase.h:2373
bool isFunctionOrMethod() const
Definition DeclBase.h:2161
void addHiddenDecl(Decl *D)
Add the declaration D to this context without modifying any lookup tables.
decl_iterator decls_begin() const
Decl * getSingleDecl()
Definition DeclGroup.h:79
bool isNull() const
Definition DeclGroup.h:75
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:487
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
Decl * getPreviousDecl()
Retrieve the previous declaration that declares the same entity as this declaration,...
Definition DeclBase.h:1061
SourceLocation getEndLoc() const LLVM_READONLY
Definition DeclBase.h:435
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:573
void addAttr(Attr *A)
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition DeclBase.h:593
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:99
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
Definition DeclBase.cpp:178
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:600
unsigned getTemplateDepth() const
Determine the number of levels of template parameter surrounding this declaration.
Definition DeclBase.cpp:320
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:793
bool isInLocalScopeForInstantiation() const
Determine whether a substitution into this declaration would occur as part of a substitution into a d...
Definition DeclBase.cpp:422
DeclContext * getNonTransparentDeclContext()
Return the non transparent context.
bool isInvalidDecl() const
Definition DeclBase.h:588
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:559
void setAccess(AccessSpecifier AS)
Definition DeclBase.h:502
SourceLocation getLocation() const
Definition DeclBase.h:439
const char * getDeclKindName() const
Definition DeclBase.cpp:169
@ IDNS_Ordinary
Ordinary names.
Definition DeclBase.h:144
void setImplicit(bool I=true)
Definition DeclBase.h:594
void setReferenced(bool R=true)
Definition DeclBase.h:623
void setIsUsed()
Set whether the declaration is used, in the sense of odr-use.
Definition DeclBase.h:608
bool isUsed(bool CheckUsedAttr=true) const
Whether any (re-)declaration of the entity was used, meaning that a definition is required.
Definition DeclBase.cpp:575
DeclContext * getDeclContext()
Definition DeclBase.h:448
attr_range attrs() const
Definition DeclBase.h:535
AccessSpecifier getAccess() const
Definition DeclBase.h:507
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclBase.h:431
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition DeclBase.h:918
bool hasAttr() const
Definition DeclBase.h:577
void setNonMemberOperator()
Specifies that this declaration is a C++ overloaded non-member.
Definition DeclBase.h:1235
void setLexicalDeclContext(DeclContext *DC)
Definition DeclBase.cpp:386
Kind getKind() const
Definition DeclBase.h:442
void setVisibleDespiteOwningModule()
Set that this declaration is globally visible, even if it came from a module that is not visible.
Definition DeclBase.h:870
DeclarationNameLoc - Additional source/type location info for a declaration name.
static DeclarationNameLoc makeNamedTypeLoc(TypeSourceInfo *TInfo)
Construct location information for a constructor, destructor or conversion operator.
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:780
SourceLocation getInnerLocStart() const
Return start of source range ignoring outer template declarations.
Definition Decl.h:822
TemplateParameterList * getTemplateParameterList(unsigned index) const
Definition Decl.h:866
SourceLocation getTypeSpecStartLoc() const
Definition Decl.cpp:1988
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Decl.h:831
const AssociatedConstraint & getTrailingRequiresClause() const
Get the constraint-expression introduced by the trailing requires-clause in the function/member decla...
Definition Decl.h:855
unsigned getNumTemplateParameterLists() const
Definition Decl.h:862
void setTypeSourceInfo(TypeSourceInfo *TI)
Definition Decl.h:814
NestedNameSpecifierLoc getQualifierLoc() const
Retrieve the nested-name-specifier (with source-location information) that qualifies the name of this...
Definition Decl.h:845
TypeSourceInfo * getTypeSourceInfo() const
Definition Decl.h:809
A decomposition declaration.
Definition DeclCXX.h:4245
ArrayRef< BindingDecl * > bindings() const
Definition DeclCXX.h:4283
static DecompositionDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation LSquareLoc, QualType T, TypeSourceInfo *TInfo, StorageClass S, ArrayRef< BindingDecl * > Bindings)
Definition DeclCXX.cpp:3682
Provides information about a dependent function-template specialization declaration.
RAII object that enters a new function expression evaluation context.
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:3423
Represents an enum.
Definition Decl.h:4007
enumerator_range enumerators() const
Definition Decl.h:4144
bool isScoped() const
Returns true if this is a C++11 scoped enumeration.
Definition Decl.h:4216
bool isScopedUsingClassTag() const
Returns true if this is a C++11 scoped enumeration.
Definition Decl.h:4219
static EnumDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, EnumDecl *PrevDecl, bool IsScoped, bool IsScopedUsingClassTag, bool IsFixed)
Definition Decl.cpp:5001
TypeSourceInfo * getIntegerTypeSourceInfo() const
Return the type source info for the underlying integer type, if no type source info exists,...
Definition Decl.h:4187
bool isFixed() const
Returns true if this is an Objective-C, C++11, or Microsoft-style enumeration with a fixed underlying...
Definition Decl.h:4225
EnumDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.h:4088
QualType getIntegerType() const
Return the integer type this enum decl corresponds to.
Definition Decl.h:4171
EnumDecl * getDefinition() const
Definition Decl.h:4110
TemplateSpecializationKind getTemplateSpecializationKind() const
If this enumeration is a member of a specialization of a templated class, determine what kind of temp...
Definition Decl.cpp:5048
Store information needed for an explicit specifier.
Definition DeclCXX.h:1924
ExplicitSpecKind getKind() const
Definition DeclCXX.h:1932
bool isInvalid() const
Determine if the explicit specifier is invalid.
Definition DeclCXX.h:1953
static ExplicitSpecifier Invalid()
Definition DeclCXX.h:1964
const Expr * getExpr() const
Definition DeclCXX.h:1933
static ExplicitSpecifier getFromDecl(FunctionDecl *Function)
Definition DeclCXX.cpp:2354
This represents one expression.
Definition Expr.h:112
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:177
std::optional< llvm::APSInt > getIntegerConstantExpr(const ASTContext &Ctx) const
isIntegerConstantExpr - Return the value if this expression is a valid integer constant expression.
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:3345
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition Expr.cpp:276
QualType getType() const
Definition Expr.h:144
Declaration context for names declared as extern "C" in C++.
Definition Decl.h:247
Abstract interface for external sources of AST nodes.
Represents difference between two FPOptions values.
Represents a member of a struct/union/class.
Definition Decl.h:3160
bool isMutable() const
Determines whether this field is mutable (C++ only).
Definition Decl.h:3260
InClassInitStyle getInClassInitStyle() const
Get the kind of (C++11) default member initializer that this field has.
Definition Decl.h:3334
Expr * getBitWidth() const
Returns the expression that represents the bit width, if this field is a bit field.
Definition Decl.h:3276
FriendDecl - Represents the declaration of a friend entity, which can be a function,...
Definition DeclFriend.h:54
bool isUnsupportedFriend() const
Determines if this friend kind is unsupported.
Definition DeclFriend.h:183
static FriendDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, FriendUnion Friend_, SourceLocation FriendL, SourceLocation EllipsisLoc={}, ArrayRef< TemplateParameterList * > FriendTypeTPLists={})
SourceLocation getFriendLoc() const
Retrieves the location of the 'friend' keyword.
Definition DeclFriend.h:144
void setUnsupportedFriend(bool Unsupported)
Definition DeclFriend.h:186
SourceRange getSourceRange() const override LLVM_READONLY
Retrieves the source range for the friend declaration.
Definition DeclFriend.h:152
SourceLocation getEllipsisLoc() const
Retrieves the location of the '...', if present.
Definition DeclFriend.h:149
NamedDecl * getFriendDecl() const
If this friend declaration doesn't name a type, return the inner declaration.
Definition DeclFriend.h:139
TypeSourceInfo * getFriendType() const
If this friend declaration names an (untemplated but possibly dependent) type, return the type; other...
Definition DeclFriend.h:125
bool isPackExpansion() const
Definition DeclFriend.h:190
Declaration of a friend template.
static DefaultedOrDeletedFunctionInfo * Create(ASTContext &Context, ArrayRef< DeclAccessPair > Lookups, StringLiteral *DeletedMessage=nullptr)
Definition Decl.cpp:3129
Represents a function declaration or definition.
Definition Decl.h:2000
void setInstantiationIsPending(bool IC)
State that the instantiation of this function is pending.
Definition Decl.h:2513
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, const AssociatedConstraint &TrailingRequiresClause={})
Definition Decl.h:2189
const ParmVarDecl * getParamDecl(unsigned i) const
Definition Decl.h:2797
Stmt * getBody(const FunctionDecl *&Definition) const
Retrieve the body (definition) of the function.
Definition Decl.cpp:3268
ConstexprSpecKind getConstexprKind() const
Definition Decl.h:2476
DefaultedOrDeletedFunctionInfo * getDefaultedOrDeletedInfo() const
Definition Decl.cpp:3183
FunctionTemplateDecl * getDescribedFunctionTemplate() const
Retrieves the function template that is described by this function declaration.
Definition Decl.cpp:4182
bool isThisDeclarationADefinition() const
Returns whether this specific declaration of the function is also a definition that does not contain ...
Definition Decl.h:2314
bool isDestroyingOperatorDelete() const
Determine whether this is a destroying operator delete.
Definition Decl.cpp:3540
StringLiteral * getDeletedMessage() const
Get the message that indicates why this function was deleted.
Definition Decl.h:2758
bool isInlined() const
Determine whether this function should be inlined, because it is either marked "inline" or "constexpr...
Definition Decl.h:2921
bool UsesFPIntrin() const
Determine whether the function was declared in source context that requires constrained FP intrinsics...
Definition Decl.h:2909
QualType getReturnType() const
Definition Decl.h:2845
ArrayRef< ParmVarDecl * > parameters() const
Definition Decl.h:2774
FunctionDecl * getTemplateInstantiationPattern(bool ForDefinition=true) const
Retrieve the function declaration from which this function could be instantiated, if it is an instant...
Definition Decl.cpp:4253
bool isExplicitlyDefaulted() const
Whether this function is explicitly defaulted.
Definition Decl.h:2389
bool hasWrittenPrototype() const
Whether this function has a written prototype.
Definition Decl.h:2448
FunctionDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.cpp:3736
DependentFunctionTemplateSpecializationInfo * getDependentSpecializationInfo() const
Definition Decl.cpp:4378
bool isDeleted() const
Whether this function has been deleted.
Definition Decl.h:2540
StorageClass getStorageClass() const
Returns the storage class as written in the source.
Definition Decl.h:2888
bool isOutOfLine() const override
Determine whether this is or was instantiated from an out-of-line definition of a member function.
Definition Decl.cpp:4515
bool FriendConstraintRefersToEnclosingTemplate() const
Definition Decl.h:2707
bool isDeletedAsWritten() const
Definition Decl.h:2544
bool isPureVirtual() const
Whether this virtual function is pure, i.e.
Definition Decl.h:2353
bool isLateTemplateParsed() const
Whether this templated function will be late parsed.
Definition Decl.h:2357
bool hasSkippedBody() const
True if the function was a definition but its body was skipped.
Definition Decl.h:2679
FunctionDecl * getDefinition()
Get the definition for this declaration.
Definition Decl.h:2282
bool isTypeAwareOperatorNewOrDelete() const
Determine whether this is a type aware operator new or delete.
Definition Decl.cpp:3548
bool isThisDeclarationInstantiatedFromAFriendDefinition() const
Determine whether this specific declaration of the function is a friend declaration that was instanti...
Definition Decl.cpp:3212
bool isDefaulted() const
Whether this function is defaulted.
Definition Decl.h:2385
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition Decl.cpp:4538
bool isVirtualAsWritten() const
Whether this function is marked as virtual explicitly.
Definition Decl.h:2344
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition Decl.cpp:3815
DeclarationNameInfo getNameInfo() const
Definition Decl.h:2211
bool hasBody(const FunctionDecl *&Definition) const
Returns true if the function has a body.
Definition Decl.cpp:3188
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:3235
FunctionDecl * getPreviousDecl()
Return the previous declaration of this declaration or NULL if this is the first declaration.
bool isInlineSpecified() const
Determine whether the "inline" keyword was specified for this function.
Definition Decl.h:2899
bool willHaveBody() const
True if this function will eventually have a body, once it's fully parsed.
Definition Decl.h:2685
const ASTTemplateArgumentListInfo * getTemplateSpecializationArgsAsWritten() const
Retrieve the template argument list as written in the sources, if any.
Definition Decl.cpp:4328
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5254
ExceptionSpecificationType getExceptionSpecType() const
Get the kind of exception specification on this function.
Definition TypeBase.h:5561
QualType getParamType(unsigned i) const
Definition TypeBase.h:5534
bool hasExceptionSpec() const
Return whether this function has any kind of exception spec.
Definition TypeBase.h:5567
ExtProtoInfo getExtProtoInfo() const
Definition TypeBase.h:5543
FunctionDecl * getExceptionSpecTemplate() const
If this function type has an uninstantiated exception specification, this is the function whose excep...
Definition TypeBase.h:5640
ArrayRef< QualType > getParamTypes() const
Definition TypeBase.h:5539
Declaration of a template function.
FunctionTemplateDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
FunctionDecl * getTemplatedDecl() const
Get the underlying function declaration of the template.
FunctionTemplateDecl * getInstantiatedFromMemberTemplate() const
void setInstantiatedFromMemberTemplate(FunctionTemplateDecl *D)
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:1693
void setParam(unsigned i, ParmVarDecl *VD)
Definition TypeLoc.h:1694
ExtInfo getExtInfo() const
Definition TypeBase.h:4806
bool getNoReturnAttr() const
Determine whether this function type includes the GNU noreturn attribute.
Definition TypeBase.h:4798
QualType getReturnType() const
Definition TypeBase.h:4790
HLSLBufferDecl - Represent a cbuffer or tbuffer declaration.
Definition Decl.h:5176
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:3467
unsigned getChainingSize() const
Definition Decl.h:3492
static IndirectFieldDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, const IdentifierInfo *Id, QualType T, MutableArrayRef< NamedDecl * > CH)
Definition Decl.cpp:5658
ArrayRef< NamedDecl * > chain() const
Definition Decl.h:3488
Description of a constructor that was inherited from a base class.
Definition DeclCXX.h:2575
const TypeClass * getTypePtr() const
Definition TypeLoc.h:526
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:974
Represents the declaration of a label.
Definition Decl.h:524
static LabelDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation IdentL, IdentifierInfo *II)
Definition Decl.cpp:5475
A stack-allocated class that identifies which local variable declaration instantiations are present i...
Definition Template.h:369
SmallVector< ValueDecl *, 4 > DeclArgumentPack
A set of declarations.
Definition Template.h:372
void InstantiatedLocal(const Decl *D, Decl *Inst)
void InstantiatedLocalPackArg(const Decl *D, VarDecl *Inst)
Represents the results of name lookup.
Definition Lookup.h:147
A global _GUID constant.
Definition DeclCXX.h:4394
An instance of this class represents the declaration of a property member.
Definition DeclCXX.h:4340
static MSPropertyDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, DeclarationName N, QualType T, TypeSourceInfo *TInfo, SourceLocation StartL, IdentifierInfo *Getter, IdentifierInfo *Setter)
Definition DeclCXX.cpp:3722
IdentifierInfo * getGetterId() const
Definition DeclCXX.h:4362
IdentifierInfo * getSetterId() const
Definition DeclCXX.h:4364
Provides information a specialization of a member of a class template, which may be a member function...
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:269
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
void addOuterRetainedLevels(unsigned Num)
Definition Template.h:264
unsigned getNumRetainedOuterLevels() const
Definition Template.h:139
This represents a decl that may have a name.
Definition Decl.h:274
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition Decl.h:295
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition Decl.h:340
bool hasLinkage() const
Determine whether this declaration has linkage.
Definition Decl.cpp:1930
bool isCXXClassMember() const
Determine whether this declaration is a C++ class member.
Definition Decl.h:397
Represents a C++ namespace alias.
Definition DeclCXX.h:3197
NestedNameSpecifierLoc getQualifierLoc() const
Retrieve the nested-name-specifier that qualifies the name of the namespace, with source-location inf...
Definition DeclCXX.h:3258
SourceLocation getAliasLoc() const
Returns the location of the alias name, i.e.
Definition DeclCXX.h:3280
static NamespaceAliasDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation NamespaceLoc, SourceLocation AliasLoc, IdentifierInfo *Alias, NestedNameSpecifierLoc QualifierLoc, SourceLocation IdentLoc, NamespaceBaseDecl *Namespace)
Definition DeclCXX.cpp:3354
SourceLocation getNamespaceLoc() const
Returns the location of the namespace keyword.
Definition DeclCXX.h:3283
SourceLocation getTargetNameLoc() const
Returns the location of the identifier in the named namespace.
Definition DeclCXX.h:3286
NamespaceDecl * getNamespace()
Retrieve the namespace declaration aliased by this directive.
Definition DeclCXX.h:3267
Represent a C++ namespace.
Definition Decl.h:592
A C++ nested-name-specifier augmented with source location information.
SourceRange getSourceRange() const LLVM_READONLY
Retrieve the source range covering the entirety of this nested-name-specifier.
bool hasQualifier() const
Evaluates true when this nested-name-specifier location is non-empty.
NonTypeTemplateParmDecl - Declares a non-type template parameter, e.g., "Size" in.
bool isPackExpansion() const
Whether this parameter pack is a pack expansion.
bool hasDefaultArgument() const
Determine whether this template parameter has a default argument.
unsigned getPosition() const
Get the position of the template parameter within its parameter list.
bool defaultArgumentWasInherited() const
Determines whether the default argument was inherited from a previous declaration of this template.
TypeSourceInfo * getExpansionTypeSourceInfo(unsigned I) const
Retrieve a particular expansion type source info within an expanded parameter pack.
unsigned getNumExpansionTypes() const
Retrieves the number of expansion types in an expanded parameter pack.
const TemplateArgumentLoc & getDefaultArgument() const
Retrieve the default argument, if any.
bool isExpandedParameterPack() const
Whether this parameter is a non-type template parameter pack that has a known list of different types...
static NonTypeTemplateParmDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, unsigned D, unsigned P, const IdentifierInfo *Id, QualType T, bool ParameterPack, TypeSourceInfo *TInfo)
bool isParameterPack() const
Whether this parameter is a non-type template parameter pack.
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)...
void setDefaultArgument(const ASTContext &C, const TemplateArgumentLoc &DefArg)
Set the default argument for this template parameter, and whether that default argument was inherited...
This represents 'pragma omp allocate ...' directive.
Definition DeclOpenMP.h:536
clauselist_range clauselists()
Definition DeclOpenMP.h:589
varlist_range varlist()
Definition DeclOpenMP.h:578
Pseudo declaration for capturing expressions.
Definition DeclOpenMP.h:445
This represents 'pragma omp declare mapper ...' directive.
Definition DeclOpenMP.h:349
OMPDeclareMapperDecl * getPrevDeclInScope()
Get reference to previous declare mapper construct in the same scope with the same name.
clauselist_iterator clauselist_begin()
Definition DeclOpenMP.h:401
clauselist_range clauselists()
Definition DeclOpenMP.h:395
DeclarationName getVarName()
Get the name of the variable declared in the mapper.
Definition DeclOpenMP.h:421
Expr * getMapperVarRef()
Get the variable declared in the mapper.
Definition DeclOpenMP.h:411
This represents 'pragma omp declare reduction ...' directive.
Definition DeclOpenMP.h:239
Expr * getInitializer()
Get initializer expression (if specified) of the declare reduction construct.
Definition DeclOpenMP.h:300
Expr * getInitPriv()
Get Priv variable of the initializer.
Definition DeclOpenMP.h:311
Expr * getCombinerOut()
Get Out variable of the combiner.
Definition DeclOpenMP.h:288
Expr * getCombinerIn()
Get In variable of the combiner.
Definition DeclOpenMP.h:285
Expr * getCombiner()
Get combiner expression of the declare reduction construct.
Definition DeclOpenMP.h:282
OMPDeclareReductionDecl * getPrevDeclInScope()
Get reference to previous declare reduction construct in the same scope with the same name.
Expr * getInitOrig()
Get Orig variable of the initializer.
Definition DeclOpenMP.h:308
OMPDeclareReductionInitKind getInitializerKind() const
Get initializer kind.
Definition DeclOpenMP.h:303
This represents 'pragma omp groupprivate ...' directive.
Definition DeclOpenMP.h:173
varlist_range varlist()
Definition DeclOpenMP.h:208
This represents 'pragma omp requires...' directive.
Definition DeclOpenMP.h:479
This represents 'pragma omp threadprivate ...' directive.
Definition DeclOpenMP.h:110
Helper data structure representing the traits in a match clause of an declare variant or metadirectiv...
bool anyScoreOrCondition(llvm::function_ref< bool(Expr *&, bool)> Cond)
Represents a field declaration created by an @defs(...).
Definition DeclObjC.h:2030
PtrTy get() const
Definition Ownership.h:81
static OpaquePtr make(QualType P)
Definition Ownership.h:61
static OpenACCBindClause * Create(const ASTContext &C, SourceLocation BeginLoc, SourceLocation LParenLoc, const IdentifierInfo *ID, SourceLocation EndLoc)
OpenACCDirectiveKind getDirectiveKind() const
Definition DeclOpenACC.h:56
ArrayRef< const OpenACCClause * > clauses() const
Definition DeclOpenACC.h:62
SourceLocation getDirectiveLoc() const
Definition DeclOpenACC.h:57
static OpenACCCopyClause * Create(const ASTContext &C, OpenACCClauseKind Spelling, SourceLocation BeginLoc, SourceLocation LParenLoc, OpenACCModifierKind Mods, ArrayRef< Expr * > VarList, SourceLocation EndLoc)
static OpenACCCopyInClause * Create(const ASTContext &C, OpenACCClauseKind Spelling, SourceLocation BeginLoc, SourceLocation LParenLoc, OpenACCModifierKind Mods, ArrayRef< Expr * > VarList, SourceLocation EndLoc)
static OpenACCCopyOutClause * Create(const ASTContext &C, OpenACCClauseKind Spelling, SourceLocation BeginLoc, SourceLocation LParenLoc, OpenACCModifierKind Mods, ArrayRef< Expr * > VarList, SourceLocation EndLoc)
static OpenACCCreateClause * Create(const ASTContext &C, OpenACCClauseKind Spelling, SourceLocation BeginLoc, SourceLocation LParenLoc, OpenACCModifierKind Mods, ArrayRef< Expr * > VarList, SourceLocation EndLoc)
static OpenACCDevicePtrClause * Create(const ASTContext &C, SourceLocation BeginLoc, SourceLocation LParenLoc, ArrayRef< Expr * > VarList, SourceLocation EndLoc)
static OpenACCDeviceResidentClause * Create(const ASTContext &C, SourceLocation BeginLoc, SourceLocation LParenLoc, ArrayRef< Expr * > VarList, SourceLocation EndLoc)
A 'device_type' or 'dtype' clause, takes a list of either an 'asterisk' or an identifier.
static OpenACCDeviceTypeClause * Create(const ASTContext &C, OpenACCClauseKind K, SourceLocation BeginLoc, SourceLocation LParenLoc, ArrayRef< DeviceTypeArgument > Archs, SourceLocation EndLoc)
static OpenACCLinkClause * Create(const ASTContext &C, SourceLocation BeginLoc, SourceLocation LParenLoc, ArrayRef< Expr * > VarList, SourceLocation EndLoc)
static OpenACCNoHostClause * Create(const ASTContext &Ctx, SourceLocation BeginLoc, SourceLocation EndLoc)
static OpenACCPresentClause * Create(const ASTContext &C, SourceLocation BeginLoc, SourceLocation LParenLoc, ArrayRef< Expr * > VarList, SourceLocation EndLoc)
SourceLocation getRParenLoc() const
const Expr * getFunctionReference() const
SourceLocation getLParenLoc() const
static OpenACCSeqClause * Create(const ASTContext &Ctx, SourceLocation BeginLoc, SourceLocation EndLoc)
static OpenACCVectorClause * Create(const ASTContext &Ctx, SourceLocation BeginLoc, SourceLocation LParenLoc, Expr *IntExpr, SourceLocation EndLoc)
static OpenACCWorkerClause * Create(const ASTContext &Ctx, SourceLocation BeginLoc, SourceLocation LParenLoc, Expr *IntExpr, SourceLocation EndLoc)
SourceLocation getEllipsisLoc() const
Definition TypeLoc.h:2600
TypeLoc getPatternLoc() const
Definition TypeLoc.h:2616
Represents a parameter to a function.
Definition Decl.h:1790
Represents a #pragma comment line.
Definition Decl.h:167
Represents a #pragma detect_mismatch line.
Definition Decl.h:201
PrettyDeclStackTraceEntry - If a crash occurs in the parser while parsing something related to a decl...
A (possibly-)qualified type.
Definition TypeBase.h:937
bool isRestrictQualified() const
Determine whether this type is restrict-qualified.
Definition TypeBase.h:8356
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition TypeBase.h:1004
QualType getNonReferenceType() const
If Type is a reference type (e.g., const int&), returns the type that the reference refers to ("const...
Definition TypeBase.h:8463
QualType getAtomicUnqualifiedType() const
Remove all qualifiers including _Atomic.
Definition Type.cpp:1670
The collection of all-type qualifiers we support.
Definition TypeBase.h:331
Represents a struct/union/class.
Definition Decl.h:4312
bool isAnonymousStructOrUnion() const
Whether this is an anonymous struct or union.
Definition Decl.h:4364
Wrapper for source info for record types.
Definition TypeLoc.h:855
Declaration of a redeclarable template.
void setInstantiatedFromMemberTemplate(RedeclarableTemplateDecl *TD)
decl_type * getFirstDecl()
Return the first declaration of this declaration or itself if this is the only declaration.
void setPreviousDecl(decl_type *PrevDecl)
Set the previous declaration.
Definition Decl.h:5312
Represents the body of a requires-expression.
Definition DeclCXX.h:2098
static RequiresExprBodyDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc)
Definition DeclCXX.cpp:2389
Scope - A scope is a transient data structure that is used while parsing the program.
Definition Scope.h:41
void addAMDGPUFlatWorkGroupSizeAttr(Decl *D, const AttributeCommonInfo &CI, Expr *Min, Expr *Max)
addAMDGPUFlatWorkGroupSizeAttr - Adds an amdgpu_flat_work_group_size attribute to a particular declar...
void addAMDGPUWavesPerEUAttr(Decl *D, const AttributeCommonInfo &CI, Expr *Min, Expr *Max)
addAMDGPUWavePersEUAttr - Adds an amdgpu_waves_per_eu attribute to a particular declaration.
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...
Sema & SemaRef
Definition SemaBase.h:40
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID)
Emit a diagnostic.
Definition SemaBase.cpp:61
void checkAllowedInitializer(VarDecl *VD)
Definition SemaCUDA.cpp:672
QualType getInoutParameterType(QualType Ty)
bool inferObjCARCLifetime(ValueDecl *decl)
void AddXConsumedAttr(Decl *D, const AttributeCommonInfo &CI, Sema::RetainOwnershipKind K, bool IsTemplateInstantiation)
A type to represent all the data for an OpenACC Clause that has been parsed, but not yet created/sema...
OpenACCDirectiveKind getDirectiveKind() const
OpenACCClauseKind getClauseKind() const
void ActOnOpenMPDeclareVariantDirective(FunctionDecl *FD, Expr *VariantRef, OMPTraitInfo &TI, ArrayRef< Expr * > AdjustArgsNothing, ArrayRef< Expr * > AdjustArgsNeedDevicePtr, ArrayRef< Expr * > AdjustArgsNeedDeviceAddr, ArrayRef< OMPInteropInfo > AppendArgs, SourceLocation AdjustArgsLoc, SourceLocation AppendArgsLoc, SourceRange SR)
Called on well-formed '#pragma omp declare variant' after parsing of the associated method/function.
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...
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.
void AddParameterABIAttr(Decl *D, const AttributeCommonInfo &CI, ParameterABI abi)
RAII object used to change the argument pack substitution index within a Sema object.
Definition Sema.h:13584
RAII object used to temporarily allow the C++ 'this' expression to be used, with the given qualifiers...
Definition Sema.h:8412
A RAII object to temporarily push a declaration context.
Definition Sema.h:3467
CXXSpecialMemberKind asSpecialMember() const
Definition Sema.h:6356
A helper class for building up ExtParameterInfos.
Definition Sema.h:12977
Records and restores the CurFPFeatures state on entry/exit of compound statements.
Definition Sema.h:13981
RAII class used to indicate that we are performing provisional semantic analysis to determine the val...
Definition Sema.h:12456
Sema - This implements semantic analysis and AST building for C.
Definition Sema.h:854
SemaAMDGPU & AMDGPU()
Definition Sema.h:1416
MemInitResult BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init, CXXRecordDecl *ClassDecl)
SmallVector< CodeSynthesisContext, 16 > CodeSynthesisContexts
List of active code synthesis contexts.
Definition Sema.h:13523
LocalInstantiationScope * CurrentInstantiationScope
The current instantiation scope used to store local variables.
Definition Sema.h:13006
TemplateArgumentLoc getTrivialTemplateArgumentLoc(const TemplateArgument &Arg, QualType NTTPType, SourceLocation Loc, NamedDecl *TemplateParam=nullptr)
Allocate a TemplateArgumentLoc where all locations have been initialized to the given location.
bool CheckUsingDeclQualifier(SourceLocation UsingLoc, bool HasTypename, const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, SourceLocation NameLoc, const LookupResult *R=nullptr, const UsingDecl *UD=nullptr)
Checks that the given nested-name qualifier used in a using decl in the current context is appropriat...
DefaultedFunctionKind getDefaultedFunctionKind(const FunctionDecl *FD)
Determine the kind of defaulting that would be done for a given function.
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition Sema.h:9303
@ LookupUsingDeclName
Look up all declarations in a scope with the given name, including resolved using declarations.
Definition Sema.h:9330
@ LookupRedeclarationWithLinkage
Look up an ordinary name that is going to be redeclared as a name with linkage.
Definition Sema.h:9335
Decl * ActOnSkippedFunctionBody(Decl *Decl)
NamedDecl * FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D, const MultiLevelTemplateArgumentList &TemplateArgs, bool FindingInstantiatedContext=false)
Find the instantiation of the given declaration within the current instantiation.
MemInitResult BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo, Expr *Init, CXXRecordDecl *ClassDecl, SourceLocation EllipsisLoc)
RetainOwnershipKind
Definition Sema.h:5019
bool InstantiateDefaultArgument(SourceLocation CallLoc, FunctionDecl *FD, ParmVarDecl *Param)
SemaOpenMP & OpenMP()
Definition Sema.h:1501
void AddAlignedAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E, bool IsPackExpansion)
AddAlignedAttr - Adds an aligned attribute to a particular declaration.
const TranslationUnitKind TUKind
The kind of translation unit we are processing.
Definition Sema.h:1241
void InstantiateExceptionSpec(SourceLocation PointOfInstantiation, FunctionDecl *Function)
void AddAssumeAlignedAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E, Expr *OE)
AddAssumeAlignedAttr - Adds an assume_aligned attribute to a particular declaration.
SemaCUDA & CUDA()
Definition Sema.h:1441
const ExpressionEvaluationContextRecord & currentEvaluationContext() const
Definition Sema.h:6901
void deduceOpenCLAddressSpace(ValueDecl *decl)
PragmaStack< FPOptionsOverride > FpPragmaStack
Definition Sema.h:2044
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)
VarTemplateSpecializationDecl * BuildVarTemplateInstantiation(VarTemplateDecl *VarTemplate, VarDecl *FromVar, const TemplateArgumentList *PartialSpecArgs, SmallVectorImpl< TemplateArgument > &Converted, SourceLocation PointOfInstantiation, LateInstantiatedAttrVec *LateAttrs=nullptr, LocalInstantiationScope *StartingScope=nullptr)
Decl * ActOnFinishFunctionBody(Decl *Decl, Stmt *Body, bool IsInstantiation=false, bool RetainFunctionScopeInfo=false)
Performs semantic analysis at the end of a function body.
void SubstExceptionSpec(FunctionDecl *New, const FunctionProtoType *Proto, const MultiLevelTemplateArgumentList &Args)
ExpressionEvaluationContextRecord & parentEvaluationContext()
Definition Sema.h:6913
LateParsedTemplateMapT LateParsedTemplateMap
Definition Sema.h:11326
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...
StmtResult SubstStmt(Stmt *S, const MultiLevelTemplateArgumentList &TemplateArgs)
ASTContext & Context
Definition Sema.h:1283
ExprResult SubstExpr(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs)
DiagnosticsEngine & getDiagnostics() const
Definition Sema.h:922
bool CheckParameterPacksForExpansion(SourceLocation EllipsisLoc, SourceRange PatternRange, ArrayRef< UnexpandedParameterPack > Unexpanded, const MultiLevelTemplateArgumentList &TemplateArgs, bool FailOnPackProducingTemplates, bool &ShouldExpand, bool &RetainExpansion, UnsignedOrNone &NumExpansions, bool Diagnose=true)
Determine whether we could expand a pack expansion with the given set of parameter packs into separat...
SemaObjC & ObjC()
Definition Sema.h:1486
DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType=nullptr)
Definition SemaDecl.cpp:76
void InstantiateMemInitializers(CXXConstructorDecl *New, const CXXConstructorDecl *Tmpl, const MultiLevelTemplateArgumentList &TemplateArgs)
void CleanupVarDeclMarking()
ASTContext & getASTContext() const
Definition Sema.h:925
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.
SmallVector< LateInstantiatedAttribute, 1 > LateInstantiatedAttrVec
Definition Sema.h:14063
PrintingPolicy getPrintingPolicy() const
Retrieve a suitable printing policy for diagnostics.
Definition Sema.h:1191
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:12112
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...
Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer, TranslationUnitKind TUKind=TU_Complete, CodeCompleteConsumer *CompletionConsumer=nullptr)
Definition Sema.cpp:272
void InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs, const Decl *Pattern, Decl *Inst, LateInstantiatedAttrVec *LateAttrs=nullptr, LocalInstantiationScope *OuterMostScope=nullptr)
const LangOptions & getLangOpts() const
Definition Sema.h:918
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:1325
void collectUnexpandedParameterPacks(TemplateArgument Arg, SmallVectorImpl< UnexpandedParameterPack > &Unexpanded)
Collect the set of unexpanded parameter packs within the given template argument.
const LangOptions & LangOpts
Definition Sema.h:1281
Decl * ActOnStartOfFunctionDef(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParamLists, SkipBodyInfo *SkipBody=nullptr, FnBodyKind BodyKind=FnBodyKind::Other)
SemaHLSL & HLSL()
Definition Sema.h:1451
VarTemplateSpecializationDecl * CompleteVarTemplateSpecializationDecl(VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl, const MultiLevelTemplateArgumentList &TemplateArgs)
Instantiates a variable template specialization by completing it with appropriate type information an...
void updateAttrsForLateParsedTemplate(const Decl *Pattern, Decl *Inst)
Update instantiation attributes after template was late parsed.
void InstantiateVariableInitializer(VarDecl *Var, VarDecl *OldVar, const MultiLevelTemplateArgumentList &TemplateArgs)
Instantiate the initializer of a variable.
SmallVector< PendingImplicitInstantiation, 1 > LateParsedInstantiations
Queue of implicit template instantiations that cannot be performed eagerly.
Definition Sema.h:13937
DeclarationNameInfo SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo, const MultiLevelTemplateArgumentList &TemplateArgs)
Do template substitution on declaration name info.
SemaSwift & Swift()
Definition Sema.h:1531
const VarDecl * getCopyElisionCandidate(NamedReturnInfo &Info, QualType ReturnType)
Updates given NamedReturnInfo's move-eligible and copy-elidable statuses, considering the function re...
void AddAllocAlignAttr(Decl *D, const AttributeCommonInfo &CI, Expr *ParamExpr)
AddAllocAlignAttr - Adds an alloc_align attribute to a particular declaration.
UnsignedOrNone getNumArgumentsInExpansion(QualType T, const MultiLevelTemplateArgumentList &TemplateArgs)
Determine the number of arguments in the given pack expansion type.
bool usesPartialOrExplicitSpecialization(SourceLocation Loc, ClassTemplateSpecializationDecl *ClassTemplateSpec)
ExplicitSpecifier instantiateExplicitSpecifier(const MultiLevelTemplateArgumentList &TemplateArgs, ExplicitSpecifier ES)
bool CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous)
Perform semantic checking on a newly-created variable declaration.
sema::BlockScopeInfo * getCurBlock()
Retrieve the current block, if any.
Definition Sema.cpp:2516
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition Sema.h:1414
MultiLevelTemplateArgumentList getTemplateInstantiationArgs(const NamedDecl *D, const DeclContext *DC=nullptr, bool Final=false, std::optional< ArrayRef< TemplateArgument > > Innermost=std::nullopt, bool RelativeToPrimary=false, const FunctionDecl *Pattern=nullptr, bool ForConstraintInstantiation=false, bool SkipForSpecialization=false, bool ForDefaultArgumentSubstitution=false)
Retrieve the template argument list(s) that should be used to instantiate the definition of the given...
SemaOpenCL & OpenCL()
Definition Sema.h:1496
std::deque< PendingImplicitInstantiation > PendingLocalImplicitInstantiations
The queue of implicit template instantiations that are required and must be performed within the curr...
Definition Sema.h:13950
ExprResult PerformContextuallyConvertToBool(Expr *From)
PerformContextuallyConvertToBool - Perform a contextual conversion of the expression From to bool (C+...
SourceManager & getSourceManager() const
Definition Sema.h:923
FunctionDecl * SubstSpaceshipAsEqualEqual(CXXRecordDecl *RD, FunctionDecl *Spaceship)
Substitute the name and return type of a defaulted 'operator<=>' to form an implicit 'operator=='.
void PerformPendingInstantiations(bool LocalOnly=false, bool AtEndOfTU=true)
Performs template instantiation for all implicit template instantiations we have seen until this poin...
Decl * SubstDecl(Decl *D, DeclContext *Owner, const MultiLevelTemplateArgumentList &TemplateArgs)
void ActOnMemInitializers(Decl *ConstructorDecl, SourceLocation ColonLoc, ArrayRef< CXXCtorInitializer * > MemInits, bool AnyErrors)
ActOnMemInitializers - Handle the member initializers for a constructor.
TemplateParameterList * SubstTemplateParams(TemplateParameterList *Params, DeclContext *Owner, const MultiLevelTemplateArgumentList &TemplateArgs, bool EvaluateConstraints=true)
void AddLaunchBoundsAttr(Decl *D, const AttributeCommonInfo &CI, Expr *MaxThreads, Expr *MinBlocks, Expr *MaxBlocks)
AddLaunchBoundsAttr - Adds a launch_bounds attribute to a particular declaration.
UnsignedOrNone ArgPackSubstIndex
The current index into pack expansion arguments that will be used for substitution of parameter packs...
Definition Sema.h:13578
void InstantiateDefaultCtorDefaultArgs(CXXConstructorDecl *Ctor)
In the MS ABI, we need to instantiate default arguments of dllexported default constructors along wit...
QualType CheckTemplateIdType(ElaboratedTypeKeyword Keyword, TemplateName Template, SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs, Scope *Scope, bool ForNestedNameSpecifier)
RedeclarationKind forRedeclarationInCurContext() const
void InstantiateFunctionDefinition(SourceLocation PointOfInstantiation, FunctionDecl *Function, bool Recursive=false, bool DefinitionRequired=false, bool AtEndOfTU=false)
Instantiate the definition of the given function from its template.
bool CheckUsingDeclRedeclaration(SourceLocation UsingLoc, bool HasTypenameKeyword, const CXXScopeSpec &SS, SourceLocation NameLoc, const LookupResult &Previous)
Checks that the given using declaration is not an invalid redeclaration.
bool SubstDefaultArgument(SourceLocation Loc, ParmVarDecl *Param, const MultiLevelTemplateArgumentList &TemplateArgs, bool ForCallExpr=false)
Substitute the given template arguments into the default argument.
void InstantiateAttrsForDecl(const MultiLevelTemplateArgumentList &TemplateArgs, const Decl *Pattern, Decl *Inst, LateInstantiatedAttrVec *LateAttrs=nullptr, LocalInstantiationScope *OuterMostScope=nullptr)
IntrusiveRefCntPtr< ExternalSemaSource > ExternalSource
Source of additional semantic information.
Definition Sema.h:1552
ASTConsumer & Consumer
Definition Sema.h:1284
sema::AnalysisBasedWarnings AnalysisWarnings
Worker object for performing CFG-based warnings.
Definition Sema.h:1319
bool hasUncompilableErrorOccurred() const
Whether uncompilable error has occurred.
Definition Sema.cpp:1777
std::deque< PendingImplicitInstantiation > PendingInstantiations
The queue of implicit template instantiations that are required but have not yet been performed.
Definition Sema.h:13933
bool CheckInheritingConstructorUsingDecl(UsingDecl *UD)
Additional checks for a using declaration referring to a constructor name.
void addClusterDimsAttr(Decl *D, const AttributeCommonInfo &CI, Expr *X, Expr *Y, Expr *Z)
@ ConstantEvaluated
The current context is "potentially evaluated" in C++11 terms, but the expression is evaluated at com...
Definition Sema.h:6702
@ PotentiallyEvaluated
The current expression is potentially evaluated at run time, which means that code may be generated t...
Definition Sema.h:6712
@ Unevaluated
The current expression and its subexpressions occur within an unevaluated operand (C++11 [expr]p7),...
Definition Sema.h:6681
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.
LateTemplateParserCB * LateTemplateParser
Definition Sema.h:1324
bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, bool InUnqualifiedLookup=false)
Perform qualified name lookup into a given context.
SmallVector< ExpressionEvaluationContextRecord, 8 > ExprEvalContexts
A stack of expression evaluation contexts.
Definition Sema.h:8281
bool DiagnoseUninstantiableTemplate(SourceLocation PointOfInstantiation, NamedDecl *Instantiation, bool InstantiatedFromMember, const NamedDecl *Pattern, const NamedDecl *PatternDef, TemplateSpecializationKind TSK, bool Complain=true, bool *Unreachable=nullptr)
Determine whether we would be unable to instantiate this template (because it either has no definitio...
SourceManager & SourceMgr
Definition Sema.h:1286
bool CheckAlignasTypeArgument(StringRef KWName, TypeSourceInfo *TInfo, SourceLocation OpLoc, SourceRange R)
FPOptions CurFPFeatures
Definition Sema.h:1279
static bool adjustContextForLocalExternDecl(DeclContext *&DC)
Adjust the DeclContext for a function or variable that might be a function-local external declaration...
Attr * CreateAnnotationAttr(const AttributeCommonInfo &CI, StringRef Annot, MutableArrayRef< Expr * > Args)
CreateAnnotationAttr - Creates an annotation Annot with Args arguments.
Definition Sema.cpp:2937
@ TPC_FriendFunctionTemplate
Definition Sema.h:11544
@ TPC_FriendFunctionTemplateDefinition
Definition Sema.h:11545
void DiagnoseUnusedDecl(const NamedDecl *ND)
void ActOnUninitializedDecl(Decl *dcl)
void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit)
AddInitializerToDecl - Adds the initializer Init to the declaration dcl.
void runWithSufficientStackSpace(SourceLocation Loc, llvm::function_ref< void()> Fn)
Run some code with "sufficient" stack space.
Definition Sema.cpp:625
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.
void UpdateExceptionSpec(FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI)
std::pair< ValueDecl *, SourceLocation > PendingImplicitInstantiation
An entity for which implicit template instantiation is required.
Definition Sema.h:13929
DeclContext * FindInstantiatedContext(SourceLocation Loc, DeclContext *DC, const MultiLevelTemplateArgumentList &TemplateArgs)
Finds the instantiation of the given declaration context within the current instantiation.
void AddAlignValueAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E)
AddAlignValueAttr - Adds an align_value attribute to a particular declaration.
ArrayRef< sema::FunctionScopeInfo * > getFunctionScopes() const
Definition Sema.h:11318
void PerformDependentDiagnostics(const DeclContext *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs)
OpaquePtr< DeclGroupRef > DeclGroupPtrTy
Definition Sema.h:1274
bool checkStringLiteralArgumentAttr(const AttributeCommonInfo &CI, const Expr *E, StringRef &Str, SourceLocation *ArgLocation=nullptr)
Check if the argument E is a ASCII string literal.
bool CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, ParmVarDecl *Param, Expr *Init=nullptr, bool SkipImmediateInvocations=true)
Instantiate or parse a C++ default argument expression as necessary.
ASTMutationListener * getASTMutationListener() const
Definition Sema.cpp:651
ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue)
Definition Sema.h:8621
Encodes a location in the source.
A trivial tuple used to represent a source range.
SourceLocation getEnd() const
Represents a C++11 static_assert declaration.
Definition DeclCXX.h:4132
bool isFailed() const
Definition DeclCXX.h:4161
SourceLocation getRParenLoc() const
Definition DeclCXX.h:4163
Stmt - This represents one statement.
Definition Stmt.h:85
SourceLocation getEndLoc() const LLVM_READONLY
Definition Stmt.cpp:362
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Stmt.cpp:350
Represents the declaration of a struct/union/class/enum.
Definition Decl.h:3717
bool isThisDeclarationADefinition() const
Return true if this declaration is a completion definition of the type.
Definition Decl.h:3807
bool isCompleteDefinition() const
Return true if this decl has its body fully specified.
Definition Decl.h:3812
NestedNameSpecifierLoc getQualifierLoc() const
Retrieve the nested-name-specifier (with source-location information) that qualifies the name of this...
Definition Decl.h:3965
TypedefNameDecl * getTypedefNameForAnonDecl() const
Definition Decl.h:3948
void setTypedefNameForAnonDecl(TypedefNameDecl *TDD)
Definition Decl.cpp:4890
void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc)
Definition Decl.cpp:4932
bool hasNameForLinkage() const
Is this tag type named, either directly or via being defined in a typedef of this type?
Definition Decl.h:3944
TagKind getTagKind() const
Definition Decl.h:3911
SourceLocation getNameLoc() const
Definition TypeLoc.h:822
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition TypeLoc.h:816
void setNameLoc(SourceLocation Loc)
Definition TypeLoc.h:824
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition TypeLoc.h:805
A convenient class for passing around template argument information.
void setLAngleLoc(SourceLocation Loc)
void setRAngleLoc(SourceLocation Loc)
void addArgument(const TemplateArgumentLoc &Loc)
A template argument list.
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.
Location wrapper for a TemplateArgument.
const TemplateArgument & getArgument() const
SourceLocation getTemplateNameLoc() const
SourceLocation getTemplateKWLoc() const
NestedNameSpecifierLoc getTemplateQualifierLoc() const
Represents a template argument.
TemplateName getAsTemplate() const
Retrieve the template name for a template name argument.
@ Pack
The template argument is actually a parameter pack.
void setEvaluateConstraints(bool B)
Definition Template.h:612
VarTemplateSpecializationDecl * VisitVarTemplateSpecializationDecl(VarTemplateDecl *VarTemplate, VarDecl *FromVar, ArrayRef< TemplateArgument > Converted, VarTemplateSpecializationDecl *PrevDecl=nullptr)
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)
void InstantiateEnumDefinition(EnumDecl *Enum, EnumDecl *Pattern)
Decl * VisitFunctionDecl(FunctionDecl *D, TemplateParameterList *TemplateParams, RewriteKind RK=RewriteKind::None)
Normal class members are of more specific types and therefore don't make it here.
Decl * VisitCXXMethodDecl(CXXMethodDecl *D, TemplateParameterList *TemplateParams, RewriteKind RK=RewriteKind::None)
Decl * InstantiateTypeAliasTemplateDecl(TypeAliasTemplateDecl *D)
Decl * VisitBaseUsingDecls(BaseUsingDecl *D, BaseUsingDecl *Inst, LookupResult *Lookup)
bool SubstQualifier(const DeclaratorDecl *OldDecl, DeclaratorDecl *NewDecl)
TemplateParameterList * SubstTemplateParams(TemplateParameterList *List)
Instantiates a nested template parameter list in the current instantiation context.
Decl * InstantiateTypedefNameDecl(TypedefNameDecl *D, bool IsTypeAlias)
ClassTemplatePartialSpecializationDecl * InstantiateClassTemplatePartialSpecialization(ClassTemplateDecl *ClassTemplate, ClassTemplatePartialSpecializationDecl *PartialSpec)
Instantiate the declaration of a class template partial specialization.
bool SubstDefaultedFunction(FunctionDecl *New, FunctionDecl *Tmpl)
The base class of all kinds of template declarations (e.g., class, function, etc.).
TemplateParameterList * getTemplateParameters() const
Get the list of template parameters.
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.
SourceRange getSourceRange() const LLVM_READONLY
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.
SourceLocation getRAngleLoc() const
SourceLocation getLAngleLoc() const
ArrayRef< NamedDecl * > asArray()
SourceLocation getTemplateLoc() const
TemplateTemplateParmDecl - Declares a template template parameter, e.g., "T" in.
bool wasDeclaredWithTypename() const
Whether this template template parameter was declared with the 'typename' keyword.
TemplateParameterList * getExpansionTemplateParameters(unsigned I) const
Retrieve a particular expansion type within an expanded parameter pack.
bool isPackExpansion() const
Whether this parameter pack is a pack expansion.
unsigned getNumExpansionTemplateParameters() const
Retrieves the number of expansion template parameters in an expanded parameter pack.
TemplateNameKind templateParameterKind() const
const TemplateArgumentLoc & getDefaultArgument() const
Retrieve the default argument, if any.
unsigned getPosition() const
Get the position of the template parameter within its parameter list.
static TemplateTemplateParmDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation L, unsigned D, unsigned P, bool ParameterPack, IdentifierInfo *Id, TemplateNameKind ParameterKind, bool Typename, TemplateParameterList *Params)
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...
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.
const TemplateArgumentLoc & getDefaultArgument() const
Retrieve the default argument, if any.
unsigned getIndex() const
Retrieve the index of the template parameter.
bool hasTypeConstraint() const
Determine whether this template parameter has a type-constraint.
const TypeConstraint * getTypeConstraint() const
Returns the type constraint associated with this template parameter (if any).
UnsignedOrNone getNumExpansionParameters() const
Whether this parameter is a template type parameter pack that has a known list of different type-cons...
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 isParameterPack() const
Returns whether this is a parameter pack.
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, UnsignedOrNone NumExpanded=std::nullopt)
unsigned getDepth() const
Retrieve the depth of the template parameter.
void setDefaultArgument(const ASTContext &C, const TemplateArgumentLoc &DefArg)
Set the default argument for this template parameter.
bool isPackExpansion() const
Whether this parameter pack is a pack expansion.
The top declaration context.
Definition Decl.h:105
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:3688
static TypeAliasDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, TypeSourceInfo *TInfo)
Definition Decl.cpp:5732
void setDescribedAliasTemplate(TypeAliasTemplateDecl *TAT)
Definition Decl.h:3707
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.
const Type * getTypeForDecl() const
Definition Decl.h:3538
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Decl.h:3547
TyLocType push(QualType T)
Pushes space for a new TypeLoc of the given type.
TypeSourceInfo * getTypeSourceInfo(ASTContext &Context, QualType T)
Creates a TypeSourceInfo for the given type.
void pushTrivial(ASTContext &Context, QualType T, SourceLocation Loc)
Pushes 'T' with all locations pointing to 'Loc'.
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:1408
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:154
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:879
T getAsAdjusted() const
Convert to the specified TypeLoc type, returning a null TypeLoc if this TypeLoc is not of the desired...
Definition TypeLoc.h:2706
SourceLocation getBeginLoc() const
Get the begin source location.
Definition TypeLoc.cpp:193
A container of type source information.
Definition TypeBase.h:8249
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
Definition TypeLoc.h:267
QualType getType() const
Return the type wrapped by this type source info.
Definition TypeBase.h:8260
The base class of the type hierarchy.
Definition TypeBase.h:1833
bool isRValueReferenceType() const
Definition TypeBase.h:8547
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9158
bool isReferenceType() const
Definition TypeBase.h:8539
AutoType * getContainedAutoType() const
Get the AutoType whose type will be deduced for a variable with an initializer of this type.
Definition TypeBase.h:2899
bool isInstantiationDependentType() const
Determine whether this type is an instantiation-dependent type, meaning that the type involves a temp...
Definition TypeBase.h:2790
bool isLValueReferenceType() const
Definition TypeBase.h:8543
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition TypeBase.h:2782
bool containsUnexpandedParameterPack() const
Whether this type is or contains an unexpanded parameter pack, used to support C++0x variadic templat...
Definition TypeBase.h:2405
bool isTemplateTypeParmType() const
Definition TypeBase.h:8836
bool isAtomicType() const
Definition TypeBase.h:8697
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition TypeBase.h:2800
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition TypeBase.h:9007
bool isFunctionType() const
Definition TypeBase.h:8511
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9091
Represents the declaration of a typedef-name via the 'typedef' type specifier.
Definition Decl.h:3667
static TypedefDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, TypeSourceInfo *TInfo)
Definition Decl.cpp:5681
Base class for declarations which introduce a typedef-name.
Definition Decl.h:3562
TypeSourceInfo * getTypeSourceInfo() const
Definition Decl.h:3612
QualType getUnderlyingType() const
Definition Decl.h:3617
An artificial decl, representing a global anonymous constant value which is uniquified by value withi...
Definition DeclCXX.h:4451
This node is generated when a using-declaration that was annotated with attribute((using_if_exists)) ...
Definition DeclCXX.h:4114
static UnresolvedUsingIfExistsDecl * Create(ASTContext &Ctx, DeclContext *DC, SourceLocation Loc, DeclarationName Name)
Definition DeclCXX.cpp:3599
Represents a dependent using declaration which was marked with typename.
Definition DeclCXX.h:4033
SourceLocation getTypenameLoc() const
Returns the source location of the 'typename' keyword.
Definition DeclCXX.h:4063
Represents a dependent using declaration which was not marked with typename.
Definition DeclCXX.h:3936
Represents a C++ using-declaration.
Definition DeclCXX.h:3587
bool hasTypename() const
Return true if the using declaration has 'typename'.
Definition DeclCXX.h:3636
NestedNameSpecifierLoc getQualifierLoc() const
Retrieve the nested-name-specifier that qualifies the name, with source-location information.
Definition DeclCXX.h:3621
DeclarationNameInfo getNameInfo() const
Definition DeclCXX.h:3628
static UsingDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation UsingL, NestedNameSpecifierLoc QualifierLoc, const DeclarationNameInfo &NameInfo, bool HasTypenameKeyword)
Definition DeclCXX.cpp:3487
SourceLocation getUsingLoc() const
Return the source location of the 'using' keyword.
Definition DeclCXX.h:3614
Represents C++ using-directive.
Definition DeclCXX.h:3092
static UsingDirectiveDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation UsingLoc, SourceLocation NamespaceLoc, NestedNameSpecifierLoc QualifierLoc, SourceLocation IdentLoc, NamedDecl *Nominated, DeclContext *CommonAncestor)
Definition DeclCXX.cpp:3270
NamespaceDecl * getNominatedNamespace()
Returns the namespace nominated by this using-directive.
Definition DeclCXX.cpp:3297
DeclContext * getCommonAncestor()
Returns the common ancestor context of this using-directive and its nominated namespace.
Definition DeclCXX.h:3159
SourceLocation getNamespaceKeyLocation() const
Returns the location of the namespace keyword.
Definition DeclCXX.h:3167
SourceLocation getIdentLocation() const
Returns the location of this using declaration's identifier.
Definition DeclCXX.h:3170
NestedNameSpecifierLoc getQualifierLoc() const
Retrieve the nested-name-specifier that qualifies the name of the namespace, with source-location inf...
Definition DeclCXX.h:3137
Represents a C++ using-enum-declaration.
Definition DeclCXX.h:3788
SourceLocation getEnumLoc() const
The source location of the 'enum' keyword.
Definition DeclCXX.h:3812
EnumDecl * getEnumDecl() const
Definition DeclCXX.h:3830
TypeSourceInfo * getEnumType() const
Definition DeclCXX.h:3824
static UsingEnumDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation UsingL, SourceLocation EnumL, SourceLocation NameL, TypeSourceInfo *EnumType)
Definition DeclCXX.cpp:3508
SourceLocation getUsingLoc() const
The source location of the 'using' keyword.
Definition DeclCXX.h:3808
Represents a pack of using declarations that a single using-declarator pack-expanded into.
Definition DeclCXX.h:3869
ArrayRef< NamedDecl * > expansions() const
Get the set of using declarations that this pack expanded into.
Definition DeclCXX.h:3902
Represents a shadow declaration implicitly introduced into a scope by a (resolved) using-declaration ...
Definition DeclCXX.h:3395
void setType(QualType newType)
Definition Decl.h:724
QualType getType() const
Definition Decl.h:723
bool isParameterPack() const
Determine whether this value is actually a function parameter pack, init-capture pack,...
Definition Decl.cpp:5513
Represents a variable declaration or definition.
Definition Decl.h:926
VarTemplateDecl * getDescribedVarTemplate() const
Retrieves the variable template that is described by this variable declaration.
Definition Decl.cpp:2810
void setObjCForDecl(bool FRD)
Definition Decl.h:1536
static VarDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, StorageClass S)
Definition Decl.cpp:2151
void setCXXForRangeDecl(bool FRD)
Definition Decl.h:1525
bool isConstexpr() const
Whether this variable is (C++11) constexpr.
Definition Decl.h:1569
void setInstantiationOfStaticDataMember(VarDecl *VD, TemplateSpecializationKind TSK)
Specify that this variable is an instantiation of the static data member VD.
Definition Decl.cpp:2935
TLSKind getTLSKind() const
Definition Decl.cpp:2168
bool hasInit() const
Definition Decl.cpp:2398
void setInitStyle(InitializationStyle Style)
Definition Decl.h:1452
VarDecl * getMostRecentDecl()
Returns the most recent (re)declaration of this declaration.
InitializationStyle getInitStyle() const
The style of initialization for this declaration.
Definition Decl.h:1466
void setInitCapture(bool IC)
Definition Decl.h:1581
DefinitionKind isThisDeclarationADefinition(ASTContext &) const
Check whether this declaration is a definition.
Definition Decl.cpp:2260
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:2461
VarDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.cpp:2257
bool isInitCapture() const
Whether this variable is the implicit variable for a lambda init-capture.
Definition Decl.h:1578
@ CallInit
Call-style initialization (C++98)
Definition Decl.h:934
bool isObjCForDecl() const
Determine whether this variable is a for-loop declaration for a for-in statement in Objective-C.
Definition Decl.h:1532
void setPreviousDeclInSameBlockScope(bool Same)
Definition Decl.h:1593
bool isInlineSpecified() const
Definition Decl.h:1554
bool isStaticDataMember() const
Determines whether this is a static data member.
Definition Decl.h:1283
VarDecl * getTemplateInstantiationPattern() const
Retrieve the variable declaration from which this variable could be instantiated, if it is an instant...
Definition Decl.cpp:2714
bool isCXXForRangeDecl() const
Determine whether this variable is the for-range-declaration in a C++0x for-range statement.
Definition Decl.h:1522
VarDecl * getDefinition(ASTContext &)
Get the real (not just tentative) definition for this declaration.
Definition Decl.cpp:2366
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:2486
bool isNRVOVariable() const
Determine whether this local variable can be used with the named return value optimization (NRVO).
Definition Decl.h:1512
void setInlineSpecified()
Definition Decl.h:1558
bool isStaticLocal() const
Returns true if a variable with function scope is a static local variable.
Definition Decl.h:1208
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:2907
void setTSCSpec(ThreadStorageClassSpecifier TSC)
Definition Decl.h:1173
void setNRVOVariable(bool NRVO)
Definition Decl.h:1515
bool isInline() const
Whether this variable is (C++1z) inline.
Definition Decl.h:1551
ThreadStorageClassSpecifier getTSCSpec() const
Definition Decl.h:1177
const Expr * getInit() const
Definition Decl.h:1368
void setConstexpr(bool IC)
Definition Decl.h:1572
void setDescribedVarTemplate(VarTemplateDecl *Template)
Definition Decl.cpp:2815
bool isDirectInit() const
Whether the initializer is a direct-initializer (list or call).
Definition Decl.h:1471
StorageClass getStorageClass() const
Returns the storage class as written in the source.
Definition Decl.h:1168
void setImplicitlyInline()
Definition Decl.h:1563
bool isPreviousDeclInSameBlockScope() const
Whether this local extern variable declaration's previous declaration was declared in the same block ...
Definition Decl.h:1588
VarDecl * getPreviousDecl()
Return the previous declaration of this declaration or NULL if this is the first declaration.
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:2800
TemplateSpecializationKind getTemplateSpecializationKindForInstantiation() const
Get the template specialization kind of this variable for the purposes of template instantiation.
Definition Decl.cpp:2790
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:2779
Declaration of a variable template.
VarDecl * getTemplatedDecl() const
Get the underlying variable declarations of the template.
static VarTemplateDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, DeclarationName Name, TemplateParameterList *Params, VarDecl *Decl)
Create a variable template node.
llvm::FoldingSetVector< VarTemplatePartialSpecializationDecl > & getPartialSpecializations() const
Retrieve the set of partial specializations of this class template.
VarTemplateSpecializationDecl * findSpecialization(ArrayRef< TemplateArgument > Args, void *&InsertPos)
Return the specialization with the provided arguments if it exists, otherwise return the insertion po...
VarTemplatePartialSpecializationDecl * findPartialSpecInstantiatedFromMember(VarTemplatePartialSpecializationDecl *D)
Find a variable template partial specialization which was instantiated from the given member partial ...
static VarTemplatePartialSpecializationDecl * Create(ASTContext &Context, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, TemplateParameterList *Params, VarTemplateDecl *SpecializedTemplate, QualType T, TypeSourceInfo *TInfo, StorageClass S, ArrayRef< TemplateArgument > Args)
TemplateParameterList * getTemplateParameters() const
Get the list of template parameters.
void setInstantiatedFromMember(VarTemplatePartialSpecializationDecl *PartialSpec)
Represents a variable template specialization, which refers to a variable template with a given set o...
SourceLocation getPointOfInstantiation() const
Get the point of instantiation (if any), or null if none.
void setTemplateArgsAsWritten(const ASTTemplateArgumentListInfo *ArgsWritten)
Set the template argument list as written in the sources.
const ASTTemplateArgumentListInfo * getTemplateArgsAsWritten() const
Retrieve the template argument list as written in the sources, if any.
const TemplateArgumentList & getTemplateArgs() const
Retrieve the template arguments of the variable template specialization.
const TemplateArgumentList & getTemplateInstantiationArgs() const
Retrieve the set of template arguments that should be used to instantiate the initializer of the vari...
static VarTemplateSpecializationDecl * Create(ASTContext &Context, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, VarTemplateDecl *SpecializedTemplate, QualType T, TypeSourceInfo *TInfo, StorageClass S, ArrayRef< TemplateArgument > Args)
llvm::PointerUnion< VarTemplateDecl *, VarTemplatePartialSpecializationDecl * > getSpecializedTemplateOrPartial() const
Retrieve the variable template or variable template partial specialization which was specialized by t...
TemplateSpecializationKind getSpecializationKind() const
Determine the kind of specialization that this declaration represents.
VarTemplateDecl * getSpecializedTemplate() const
Retrieve the template that this specialization specializes.
QualType FunctionType
BlockType - The function type of the block, if one was given.
Definition ScopeInfo.h:800
void addCapture(ValueDecl *Var, bool isBlock, bool isByref, bool isNested, SourceLocation Loc, SourceLocation EllipsisLoc, QualType CaptureType, bool Invalid)
Definition ScopeInfo.h:737
#define bool
Definition gpuintrin.h:32
Defines the clang::TargetInfo interface.
const internal::VariadicAllOfMatcher< Decl > decl
Matches declarations.
bool NE(InterpState &S, CodePtr OpPC)
Definition Interp.h:1235
std::variant< struct RequiresDecl, struct HeaderDecl, struct UmbrellaDirDecl, struct ModuleDecl, struct ExcludeDecl, struct ExportDecl, struct ExportAsDecl, struct ExternModuleDecl, struct UseDecl, struct LinkDecl, struct ConfigMacrosDecl, struct ConflictDecl > Decl
All declarations that can appear in a module declaration.
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.
CanQual< Type > CanQualType
Represents a canonical, potentially-qualified type.
void atTemplateEnd(TemplateInstantiationCallbackPtrs &Callbacks, const Sema &TheSema, const Sema::CodeSynthesisContext &Inst)
OpenACCDirectiveKind
bool isa(CodeGen::Address addr)
Definition Address.h:330
@ CPlusPlus11
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...
Definition Template.h:54
@ TemplateName
The identifier is a template name. FIXME: Add an annotation for that.
Definition Parser.h:61
@ DevicePtr
'deviceptr' clause, allowed on Compute and Combined Constructs, plus 'data' and 'declare'.
@ VectorLength
'vector_length' clause, allowed on 'parallel', 'kernels', 'parallel loop', and 'kernels loop' constru...
@ Async
'async' clause, allowed on Compute, Data, 'update', 'wait', and Combined constructs.
@ Collapse
'collapse' clause, allowed on 'loop' and Combined constructs.
@ DeviceNum
'device_num' clause, allowed on 'init', 'shutdown', and 'set' constructs.
@ DefaultAsync
'default_async' clause, allowed on 'set' construct.
@ Attach
'attach' clause, allowed on Compute and Combined constructs, plus 'data' and 'enter data'.
@ NumGangs
'num_gangs' clause, allowed on 'parallel', 'kernels', parallel loop', and 'kernels loop' constructs.
@ If
'if' clause, allowed on all the Compute Constructs, Data Constructs, Executable Constructs,...
@ UseDevice
'use_device' clause, allowed on 'host_data' construct.
@ NoCreate
'no_create' clause, allowed on allowed on Compute and Combined constructs, plus 'data'.
@ Reduction
'reduction' clause, allowed on Parallel, Serial, Loop, and the combined constructs.
@ Self
'self' clause, allowed on Compute and Combined Constructs, plus 'update'.
@ FirstPrivate
'firstprivate' clause, allowed on 'parallel', 'serial', 'parallel loop', and 'serial loop' constructs...
@ Tile
'tile' clause, allowed on 'loop' and Combined constructs.
@ Independent
'independent' clause, allowed on 'loop' directives.
@ NumWorkers
'num_workers' clause, allowed on 'parallel', 'kernels', parallel loop', and 'kernels loop' constructs...
@ IfPresent
'if_present' clause, allowed on 'host_data' and 'update' directives.
@ Detach
'detach' clause, allowed on the 'exit data' construct.
@ Delete
'delete' clause, allowed on the 'exit data' construct.
@ Finalize
'finalize' clause, allowed on 'exit data' directive.
@ AS_public
Definition Specifiers.h:124
@ AS_none
Definition Specifiers.h:127
StorageClass
Storage classes.
Definition Specifiers.h:248
@ SC_Static
Definition Specifiers.h:252
@ SC_None
Definition Specifiers.h:250
Expr * Cond
};
ExprResult ExprEmpty()
Definition Ownership.h:272
bool isGenericLambdaCallOperatorOrStaticInvokerSpecialization(const DeclContext *DC)
Definition ASTLambda.h:89
@ Property
The type of a property.
Definition TypeBase.h:911
@ Result
The result type of a method or function.
Definition TypeBase.h:905
ActionResult< CXXCtorInitializer * > MemInitResult
Definition Ownership.h:253
const FunctionProtoType * T
@ Template
We are parsing a template declaration.
Definition Parser.h:81
@ FunctionTemplate
The name was classified as a function template name.
Definition Sema.h:585
@ VarTemplate
The name was classified as a variable template name.
Definition Sema.h:583
@ TU_Prefix
The translation unit is a prefix to a translation unit, and is not complete.
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition Specifiers.h:135
bool declaresSameEntity(const Decl *D1, const Decl *D2)
Determine whether two declarations declare the same entity.
Definition DeclBase.h:1288
TemplateSpecializationKind
Describes the kind of template specialization that a particular template specialization declaration r...
Definition Specifiers.h:188
@ TSK_ExplicitInstantiationDefinition
This template specialization was instantiated from a template due to an explicit instantiation defini...
Definition Specifiers.h:206
@ TSK_ExplicitInstantiationDeclaration
This template specialization was instantiated from a template due to an explicit instantiation declar...
Definition Specifiers.h:202
@ TSK_ExplicitSpecialization
This template specialization was declared or defined by an explicit specialization (C++ [temp....
Definition Specifiers.h:198
@ TSK_ImplicitInstantiation
This template specialization was implicitly instantiated from a template.
Definition Specifiers.h:194
@ TSK_Undeclared
This template specialization was formed from a template-id but has not yet been declared,...
Definition Specifiers.h:191
U cast(CodeGen::Address addr)
Definition Address.h:327
@ None
No keyword precedes the qualified type name.
Definition TypeBase.h:5874
@ Enum
The "enum" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:5867
bool isLambdaMethod(const DeclContext *DC)
Definition ASTLambda.h:39
ActionResult< Expr * > ExprResult
Definition Ownership.h:249
@ Other
Other implicit parameter.
Definition Decl.h:1746
ExceptionSpecificationType
The various types of exception specifications that exist in C++11.
@ EST_Uninstantiated
not instantiated yet
@ EST_None
no exception specification
@ EST_BasicNoexcept
noexcept
@ EST_Unevaluated
not evaluated yet, for special member function
ActionResult< Stmt * > StmtResult
Definition Ownership.h:250
Represents an explicit template argument list in C++, e.g., the "<int>" in "sort<int>".
SourceLocation RAngleLoc
The source location of the right angle bracket ('>').
SourceLocation LAngleLoc
The source location of the left angle bracket ('<').
ArrayRef< TemplateArgumentLoc > arguments() const
DeclarationNameInfo - A collector data type for bundling together a DeclarationName and the correspon...
DeclarationName getName() const
getName - Returns the embedded declaration name.
void setName(DeclarationName N)
setName - Sets the embedded declaration name.
const DeclarationNameLoc & getInfo() const
TypeSourceInfo * getNamedTypeInfo() const
getNamedTypeInfo - Returns the source type info associated to the name.
Holds information about the various types of exception specification.
Definition TypeBase.h:5311
FunctionDecl * SourceDecl
The function whose exception specification this is, for EST_Unevaluated and EST_Uninstantiated.
Definition TypeBase.h:5323
FunctionDecl * SourceTemplate
The function template whose exception specification this is instantiated from, for EST_Uninstantiated...
Definition TypeBase.h:5327
ExceptionSpecificationType Type
The kind of exception specification this is.
Definition TypeBase.h:5313
Extra information about a function prototype.
Definition TypeBase.h:5339
bool StrictPackMatch
Is set to true when, in the context of TTP matching, a pack parameter matches non-pack arguments.
Definition Sema.h:11962
SmallVector< TemplateArgument, 4 > CanonicalConverted
Definition Sema.h:11948
A context in which code is being synthesized (where a source location alone is not sufficient to iden...
Definition Sema.h:13054
SynthesisKind
The kind of template instantiation we are performing.
Definition Sema.h:13056
@ BuildingDeductionGuides
We are building deduction guides for a class.
Definition Sema.h:13161
@ DeducedTemplateArgumentSubstitution
We are substituting template argument determined as part of template argument deduction for either a ...
Definition Sema.h:13082
bool InLifetimeExtendingContext
Whether we are currently in a context in which all temporaries must be lifetime-extended,...
Definition Sema.h:6823
bool RebuildDefaultArgOrDefaultInit
Whether we should rebuild CXXDefaultArgExpr and CXXDefaultInitExpr.
Definition Sema.h:6829
VarDecl * DeclForInitializer
Declaration for initializer if one is currently being parsed.
Definition Sema.h:6762
A stack object to be created when performing template instantiation.
Definition Sema.h:13240
bool isInvalid() const
Determines whether we have exceeded the maximum recursive template instantiations.
Definition Sema.h:13393