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