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