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