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