1 //===--- SemaTemplateInstantiateDecl.cpp - C++ Template Decl Instantiation ===/
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 //===----------------------------------------------------------------------===/
8 // This file implements C++ template instantiation for declarations.
10 //===----------------------------------------------------------------------===/
11 #include "clang/Sema/SemaInternal.h"
12 #include "clang/AST/ASTConsumer.h"
13 #include "clang/AST/ASTContext.h"
14 #include "clang/AST/ASTMutationListener.h"
15 #include "clang/AST/DeclTemplate.h"
16 #include "clang/AST/DeclVisitor.h"
17 #include "clang/AST/DependentDiagnostic.h"
18 #include "clang/AST/Expr.h"
19 #include "clang/AST/ExprCXX.h"
20 #include "clang/AST/PrettyDeclStackTrace.h"
21 #include "clang/AST/TypeLoc.h"
22 #include "clang/Sema/Initialization.h"
23 #include "clang/Sema/Lookup.h"
24 #include "clang/Sema/Template.h"
25 #include "clang/Sema/TemplateInstCallback.h"
26 #include "llvm/Support/TimeProfiler.h"
28 using namespace clang;
30 static bool isDeclWithinFunction(const Decl *D) {
31 const DeclContext *DC = D->getDeclContext();
32 if (DC->isFunctionOrMethod())
36 return cast<CXXRecordDecl>(DC)->isLocalClass();
41 template<typename DeclT>
42 static bool SubstQualifier(Sema &SemaRef, const DeclT *OldDecl, DeclT *NewDecl,
43 const MultiLevelTemplateArgumentList &TemplateArgs) {
44 if (!OldDecl->getQualifierLoc())
47 assert((NewDecl->getFriendObjectKind() ||
48 !OldDecl->getLexicalDeclContext()->isDependentContext()) &&
49 "non-friend with qualified name defined in dependent context");
50 Sema::ContextRAII SavedContext(
52 const_cast<DeclContext *>(NewDecl->getFriendObjectKind()
53 ? NewDecl->getLexicalDeclContext()
54 : OldDecl->getLexicalDeclContext()));
56 NestedNameSpecifierLoc NewQualifierLoc
57 = SemaRef.SubstNestedNameSpecifierLoc(OldDecl->getQualifierLoc(),
63 NewDecl->setQualifierInfo(NewQualifierLoc);
67 bool TemplateDeclInstantiator::SubstQualifier(const DeclaratorDecl *OldDecl,
68 DeclaratorDecl *NewDecl) {
69 return ::SubstQualifier(SemaRef, OldDecl, NewDecl, TemplateArgs);
72 bool TemplateDeclInstantiator::SubstQualifier(const TagDecl *OldDecl,
74 return ::SubstQualifier(SemaRef, OldDecl, NewDecl, TemplateArgs);
77 // Include attribute instantiation code.
78 #include "clang/Sema/AttrTemplateInstantiate.inc"
80 static void instantiateDependentAlignedAttr(
81 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
82 const AlignedAttr *Aligned, Decl *New, bool IsPackExpansion) {
83 if (Aligned->isAlignmentExpr()) {
84 // The alignment expression is a constant expression.
85 EnterExpressionEvaluationContext Unevaluated(
86 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
87 ExprResult Result = S.SubstExpr(Aligned->getAlignmentExpr(), TemplateArgs);
88 if (!Result.isInvalid())
89 S.AddAlignedAttr(New, *Aligned, Result.getAs<Expr>(), IsPackExpansion);
91 TypeSourceInfo *Result = S.SubstType(Aligned->getAlignmentType(),
92 TemplateArgs, Aligned->getLocation(),
95 S.AddAlignedAttr(New, *Aligned, Result, IsPackExpansion);
99 static void instantiateDependentAlignedAttr(
100 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
101 const AlignedAttr *Aligned, Decl *New) {
102 if (!Aligned->isPackExpansion()) {
103 instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, false);
107 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
108 if (Aligned->isAlignmentExpr())
109 S.collectUnexpandedParameterPacks(Aligned->getAlignmentExpr(),
112 S.collectUnexpandedParameterPacks(Aligned->getAlignmentType()->getTypeLoc(),
114 assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
116 // Determine whether we can expand this attribute pack yet.
117 bool Expand = true, RetainExpansion = false;
118 Optional<unsigned> NumExpansions;
119 // FIXME: Use the actual location of the ellipsis.
120 SourceLocation EllipsisLoc = Aligned->getLocation();
121 if (S.CheckParameterPacksForExpansion(EllipsisLoc, Aligned->getRange(),
122 Unexpanded, TemplateArgs, Expand,
123 RetainExpansion, NumExpansions))
127 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(S, -1);
128 instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, true);
130 for (unsigned I = 0; I != *NumExpansions; ++I) {
131 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(S, I);
132 instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, false);
137 static void instantiateDependentAssumeAlignedAttr(
138 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
139 const AssumeAlignedAttr *Aligned, Decl *New) {
140 // The alignment expression is a constant expression.
141 EnterExpressionEvaluationContext Unevaluated(
142 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
144 Expr *E, *OE = nullptr;
145 ExprResult Result = S.SubstExpr(Aligned->getAlignment(), TemplateArgs);
146 if (Result.isInvalid())
148 E = Result.getAs<Expr>();
150 if (Aligned->getOffset()) {
151 Result = S.SubstExpr(Aligned->getOffset(), TemplateArgs);
152 if (Result.isInvalid())
154 OE = Result.getAs<Expr>();
157 S.AddAssumeAlignedAttr(New, *Aligned, E, OE);
160 static void instantiateDependentAlignValueAttr(
161 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
162 const AlignValueAttr *Aligned, Decl *New) {
163 // The alignment expression is a constant expression.
164 EnterExpressionEvaluationContext Unevaluated(
165 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
166 ExprResult Result = S.SubstExpr(Aligned->getAlignment(), TemplateArgs);
167 if (!Result.isInvalid())
168 S.AddAlignValueAttr(New, *Aligned, Result.getAs<Expr>());
171 static void instantiateDependentAllocAlignAttr(
172 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
173 const AllocAlignAttr *Align, Decl *New) {
174 Expr *Param = IntegerLiteral::Create(
176 llvm::APInt(64, Align->getParamIndex().getSourceIndex()),
177 S.getASTContext().UnsignedLongLongTy, Align->getLocation());
178 S.AddAllocAlignAttr(New, *Align, Param);
181 static Expr *instantiateDependentFunctionAttrCondition(
182 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
183 const Attr *A, Expr *OldCond, const Decl *Tmpl, FunctionDecl *New) {
184 Expr *Cond = nullptr;
186 Sema::ContextRAII SwitchContext(S, New);
187 EnterExpressionEvaluationContext Unevaluated(
188 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
189 ExprResult Result = S.SubstExpr(OldCond, TemplateArgs);
190 if (Result.isInvalid())
192 Cond = Result.getAs<Expr>();
194 if (!Cond->isTypeDependent()) {
195 ExprResult Converted = S.PerformContextuallyConvertToBool(Cond);
196 if (Converted.isInvalid())
198 Cond = Converted.get();
201 SmallVector<PartialDiagnosticAt, 8> Diags;
202 if (OldCond->isValueDependent() && !Cond->isValueDependent() &&
203 !Expr::isPotentialConstantExprUnevaluated(Cond, New, Diags)) {
204 S.Diag(A->getLocation(), diag::err_attr_cond_never_constant_expr) << A;
205 for (const auto &P : Diags)
206 S.Diag(P.first, P.second);
212 static void instantiateDependentEnableIfAttr(
213 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
214 const EnableIfAttr *EIA, const Decl *Tmpl, FunctionDecl *New) {
215 Expr *Cond = instantiateDependentFunctionAttrCondition(
216 S, TemplateArgs, EIA, EIA->getCond(), Tmpl, New);
219 New->addAttr(new (S.getASTContext()) EnableIfAttr(S.getASTContext(), *EIA,
220 Cond, EIA->getMessage()));
223 static void instantiateDependentDiagnoseIfAttr(
224 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
225 const DiagnoseIfAttr *DIA, const Decl *Tmpl, FunctionDecl *New) {
226 Expr *Cond = instantiateDependentFunctionAttrCondition(
227 S, TemplateArgs, DIA, DIA->getCond(), Tmpl, New);
230 New->addAttr(new (S.getASTContext()) DiagnoseIfAttr(
231 S.getASTContext(), *DIA, Cond, DIA->getMessage(),
232 DIA->getDiagnosticType(), DIA->getArgDependent(), New));
235 // Constructs and adds to New a new instance of CUDALaunchBoundsAttr using
236 // template A as the base and arguments from TemplateArgs.
237 static void instantiateDependentCUDALaunchBoundsAttr(
238 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
239 const CUDALaunchBoundsAttr &Attr, Decl *New) {
240 // The alignment expression is a constant expression.
241 EnterExpressionEvaluationContext Unevaluated(
242 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
244 ExprResult Result = S.SubstExpr(Attr.getMaxThreads(), TemplateArgs);
245 if (Result.isInvalid())
247 Expr *MaxThreads = Result.getAs<Expr>();
249 Expr *MinBlocks = nullptr;
250 if (Attr.getMinBlocks()) {
251 Result = S.SubstExpr(Attr.getMinBlocks(), TemplateArgs);
252 if (Result.isInvalid())
254 MinBlocks = Result.getAs<Expr>();
257 S.AddLaunchBoundsAttr(New, Attr, MaxThreads, MinBlocks);
261 instantiateDependentModeAttr(Sema &S,
262 const MultiLevelTemplateArgumentList &TemplateArgs,
263 const ModeAttr &Attr, Decl *New) {
264 S.AddModeAttr(New, Attr, Attr.getMode(),
265 /*InInstantiation=*/true);
268 /// Instantiation of 'declare simd' attribute and its arguments.
269 static void instantiateOMPDeclareSimdDeclAttr(
270 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
271 const OMPDeclareSimdDeclAttr &Attr, Decl *New) {
272 // Allow 'this' in clauses with varlists.
273 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(New))
274 New = FTD->getTemplatedDecl();
275 auto *FD = cast<FunctionDecl>(New);
276 auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(FD->getDeclContext());
277 SmallVector<Expr *, 4> Uniforms, Aligneds, Alignments, Linears, Steps;
278 SmallVector<unsigned, 4> LinModifiers;
280 auto SubstExpr = [&](Expr *E) -> ExprResult {
281 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
282 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
283 Sema::ContextRAII SavedContext(S, FD);
284 LocalInstantiationScope Local(S);
285 if (FD->getNumParams() > PVD->getFunctionScopeIndex())
286 Local.InstantiatedLocal(
287 PVD, FD->getParamDecl(PVD->getFunctionScopeIndex()));
288 return S.SubstExpr(E, TemplateArgs);
290 Sema::CXXThisScopeRAII ThisScope(S, ThisContext, Qualifiers(),
291 FD->isCXXInstanceMember());
292 return S.SubstExpr(E, TemplateArgs);
295 // Substitute a single OpenMP clause, which is a potentially-evaluated
297 auto Subst = [&](Expr *E) -> ExprResult {
298 EnterExpressionEvaluationContext Evaluated(
299 S, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
300 ExprResult Res = SubstExpr(E);
303 return S.ActOnFinishFullExpr(Res.get(), false);
307 if (auto *E = Attr.getSimdlen())
310 if (Attr.uniforms_size() > 0) {
311 for(auto *E : Attr.uniforms()) {
312 ExprResult Inst = Subst(E);
313 if (Inst.isInvalid())
315 Uniforms.push_back(Inst.get());
319 auto AI = Attr.alignments_begin();
320 for (auto *E : Attr.aligneds()) {
321 ExprResult Inst = Subst(E);
322 if (Inst.isInvalid())
324 Aligneds.push_back(Inst.get());
327 Inst = S.SubstExpr(*AI, TemplateArgs);
328 Alignments.push_back(Inst.get());
332 auto SI = Attr.steps_begin();
333 for (auto *E : Attr.linears()) {
334 ExprResult Inst = Subst(E);
335 if (Inst.isInvalid())
337 Linears.push_back(Inst.get());
340 Inst = S.SubstExpr(*SI, TemplateArgs);
341 Steps.push_back(Inst.get());
344 LinModifiers.append(Attr.modifiers_begin(), Attr.modifiers_end());
345 (void)S.ActOnOpenMPDeclareSimdDirective(
346 S.ConvertDeclToDeclGroup(New), Attr.getBranchState(), Simdlen.get(),
347 Uniforms, Aligneds, Alignments, Linears, LinModifiers, Steps,
351 /// Instantiation of 'declare variant' attribute and its arguments.
352 static void instantiateOMPDeclareVariantAttr(
353 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
354 const OMPDeclareVariantAttr &Attr, Decl *New) {
355 // Allow 'this' in clauses with varlists.
356 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(New))
357 New = FTD->getTemplatedDecl();
358 auto *FD = cast<FunctionDecl>(New);
359 auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(FD->getDeclContext());
361 auto &&SubstExpr = [FD, ThisContext, &S, &TemplateArgs](Expr *E) {
362 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
363 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
364 Sema::ContextRAII SavedContext(S, FD);
365 LocalInstantiationScope Local(S);
366 if (FD->getNumParams() > PVD->getFunctionScopeIndex())
367 Local.InstantiatedLocal(
368 PVD, FD->getParamDecl(PVD->getFunctionScopeIndex()));
369 return S.SubstExpr(E, TemplateArgs);
371 Sema::CXXThisScopeRAII ThisScope(S, ThisContext, Qualifiers(),
372 FD->isCXXInstanceMember());
373 return S.SubstExpr(E, TemplateArgs);
376 // Substitute a single OpenMP clause, which is a potentially-evaluated
378 auto &&Subst = [&SubstExpr, &S](Expr *E) {
379 EnterExpressionEvaluationContext Evaluated(
380 S, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
381 ExprResult Res = SubstExpr(E);
384 return S.ActOnFinishFullExpr(Res.get(), false);
387 ExprResult VariantFuncRef;
388 if (Expr *E = Attr.getVariantFuncRef())
389 VariantFuncRef = Subst(E);
392 if (Expr *E = Attr.getScore())
395 // Check function/variant ref.
396 Optional<std::pair<FunctionDecl *, Expr *>> DeclVarData =
397 S.checkOpenMPDeclareVariantFunction(
398 S.ConvertDeclToDeclGroup(New), VariantFuncRef.get(), Attr.getRange());
401 // Instantiate the attribute.
402 Sema::OpenMPDeclareVariantCtsSelectorData Data(
403 Attr.getCtxSelectorSet(), Attr.getCtxSelector(),
404 llvm::makeMutableArrayRef(Attr.implVendors_begin(),
405 Attr.implVendors_size()),
407 S.ActOnOpenMPDeclareVariantDirective(DeclVarData.getValue().first,
408 DeclVarData.getValue().second,
409 Attr.getRange(), Data);
412 static void instantiateDependentAMDGPUFlatWorkGroupSizeAttr(
413 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
414 const AMDGPUFlatWorkGroupSizeAttr &Attr, Decl *New) {
415 // Both min and max expression are constant expressions.
416 EnterExpressionEvaluationContext Unevaluated(
417 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
419 ExprResult Result = S.SubstExpr(Attr.getMin(), TemplateArgs);
420 if (Result.isInvalid())
422 Expr *MinExpr = Result.getAs<Expr>();
424 Result = S.SubstExpr(Attr.getMax(), TemplateArgs);
425 if (Result.isInvalid())
427 Expr *MaxExpr = Result.getAs<Expr>();
429 S.addAMDGPUFlatWorkGroupSizeAttr(New, Attr, MinExpr, MaxExpr);
432 static ExplicitSpecifier
433 instantiateExplicitSpecifier(Sema &S,
434 const MultiLevelTemplateArgumentList &TemplateArgs,
435 ExplicitSpecifier ES, FunctionDecl *New) {
438 Expr *OldCond = ES.getExpr();
439 Expr *Cond = nullptr;
441 EnterExpressionEvaluationContext Unevaluated(
442 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
443 ExprResult SubstResult = S.SubstExpr(OldCond, TemplateArgs);
444 if (SubstResult.isInvalid()) {
445 return ExplicitSpecifier::Invalid();
447 Cond = SubstResult.get();
449 ExplicitSpecifier Result(Cond, ES.getKind());
450 if (!Cond->isTypeDependent())
451 S.tryResolveExplicitSpecifier(Result);
455 static void instantiateDependentAMDGPUWavesPerEUAttr(
456 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
457 const AMDGPUWavesPerEUAttr &Attr, Decl *New) {
458 // Both min and max expression are constant expressions.
459 EnterExpressionEvaluationContext Unevaluated(
460 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
462 ExprResult Result = S.SubstExpr(Attr.getMin(), TemplateArgs);
463 if (Result.isInvalid())
465 Expr *MinExpr = Result.getAs<Expr>();
467 Expr *MaxExpr = nullptr;
468 if (auto Max = Attr.getMax()) {
469 Result = S.SubstExpr(Max, TemplateArgs);
470 if (Result.isInvalid())
472 MaxExpr = Result.getAs<Expr>();
475 S.addAMDGPUWavesPerEUAttr(New, Attr, MinExpr, MaxExpr);
478 void Sema::InstantiateAttrsForDecl(
479 const MultiLevelTemplateArgumentList &TemplateArgs, const Decl *Tmpl,
480 Decl *New, LateInstantiatedAttrVec *LateAttrs,
481 LocalInstantiationScope *OuterMostScope) {
482 if (NamedDecl *ND = dyn_cast<NamedDecl>(New)) {
483 for (const auto *TmplAttr : Tmpl->attrs()) {
484 // FIXME: If any of the special case versions from InstantiateAttrs become
485 // applicable to template declaration, we'll need to add them here.
486 CXXThisScopeRAII ThisScope(
487 *this, dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext()),
488 Qualifiers(), ND->isCXXInstanceMember());
490 Attr *NewAttr = sema::instantiateTemplateAttributeForDecl(
491 TmplAttr, Context, *this, TemplateArgs);
493 New->addAttr(NewAttr);
498 static Sema::RetainOwnershipKind
499 attrToRetainOwnershipKind(const Attr *A) {
500 switch (A->getKind()) {
501 case clang::attr::CFConsumed:
502 return Sema::RetainOwnershipKind::CF;
503 case clang::attr::OSConsumed:
504 return Sema::RetainOwnershipKind::OS;
505 case clang::attr::NSConsumed:
506 return Sema::RetainOwnershipKind::NS;
508 llvm_unreachable("Wrong argument supplied");
512 void Sema::InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs,
513 const Decl *Tmpl, Decl *New,
514 LateInstantiatedAttrVec *LateAttrs,
515 LocalInstantiationScope *OuterMostScope) {
516 for (const auto *TmplAttr : Tmpl->attrs()) {
517 // FIXME: This should be generalized to more than just the AlignedAttr.
518 const AlignedAttr *Aligned = dyn_cast<AlignedAttr>(TmplAttr);
519 if (Aligned && Aligned->isAlignmentDependent()) {
520 instantiateDependentAlignedAttr(*this, TemplateArgs, Aligned, New);
524 if (const auto *AssumeAligned = dyn_cast<AssumeAlignedAttr>(TmplAttr)) {
525 instantiateDependentAssumeAlignedAttr(*this, TemplateArgs, AssumeAligned, New);
529 if (const auto *AlignValue = dyn_cast<AlignValueAttr>(TmplAttr)) {
530 instantiateDependentAlignValueAttr(*this, TemplateArgs, AlignValue, New);
534 if (const auto *AllocAlign = dyn_cast<AllocAlignAttr>(TmplAttr)) {
535 instantiateDependentAllocAlignAttr(*this, TemplateArgs, AllocAlign, New);
540 if (const auto *EnableIf = dyn_cast<EnableIfAttr>(TmplAttr)) {
541 instantiateDependentEnableIfAttr(*this, TemplateArgs, EnableIf, Tmpl,
542 cast<FunctionDecl>(New));
546 if (const auto *DiagnoseIf = dyn_cast<DiagnoseIfAttr>(TmplAttr)) {
547 instantiateDependentDiagnoseIfAttr(*this, TemplateArgs, DiagnoseIf, Tmpl,
548 cast<FunctionDecl>(New));
552 if (const auto *CUDALaunchBounds =
553 dyn_cast<CUDALaunchBoundsAttr>(TmplAttr)) {
554 instantiateDependentCUDALaunchBoundsAttr(*this, TemplateArgs,
555 *CUDALaunchBounds, New);
559 if (const auto *Mode = dyn_cast<ModeAttr>(TmplAttr)) {
560 instantiateDependentModeAttr(*this, TemplateArgs, *Mode, New);
564 if (const auto *OMPAttr = dyn_cast<OMPDeclareSimdDeclAttr>(TmplAttr)) {
565 instantiateOMPDeclareSimdDeclAttr(*this, TemplateArgs, *OMPAttr, New);
569 if (const auto *OMPAttr = dyn_cast<OMPDeclareVariantAttr>(TmplAttr)) {
570 instantiateOMPDeclareVariantAttr(*this, TemplateArgs, *OMPAttr, New);
574 if (const auto *AMDGPUFlatWorkGroupSize =
575 dyn_cast<AMDGPUFlatWorkGroupSizeAttr>(TmplAttr)) {
576 instantiateDependentAMDGPUFlatWorkGroupSizeAttr(
577 *this, TemplateArgs, *AMDGPUFlatWorkGroupSize, New);
580 if (const auto *AMDGPUFlatWorkGroupSize =
581 dyn_cast<AMDGPUWavesPerEUAttr>(TmplAttr)) {
582 instantiateDependentAMDGPUWavesPerEUAttr(*this, TemplateArgs,
583 *AMDGPUFlatWorkGroupSize, New);
586 // Existing DLL attribute on the instantiation takes precedence.
587 if (TmplAttr->getKind() == attr::DLLExport ||
588 TmplAttr->getKind() == attr::DLLImport) {
589 if (New->hasAttr<DLLExportAttr>() || New->hasAttr<DLLImportAttr>()) {
594 if (const auto *ABIAttr = dyn_cast<ParameterABIAttr>(TmplAttr)) {
595 AddParameterABIAttr(New, *ABIAttr, ABIAttr->getABI());
599 if (isa<NSConsumedAttr>(TmplAttr) || isa<OSConsumedAttr>(TmplAttr) ||
600 isa<CFConsumedAttr>(TmplAttr)) {
601 AddXConsumedAttr(New, *TmplAttr, attrToRetainOwnershipKind(TmplAttr),
602 /*template instantiation=*/true);
606 if (auto *A = dyn_cast<PointerAttr>(TmplAttr)) {
607 if (!New->hasAttr<PointerAttr>())
608 New->addAttr(A->clone(Context));
612 if (auto *A = dyn_cast<OwnerAttr>(TmplAttr)) {
613 if (!New->hasAttr<OwnerAttr>())
614 New->addAttr(A->clone(Context));
618 assert(!TmplAttr->isPackExpansion());
619 if (TmplAttr->isLateParsed() && LateAttrs) {
620 // Late parsed attributes must be instantiated and attached after the
621 // enclosing class has been instantiated. See Sema::InstantiateClass.
622 LocalInstantiationScope *Saved = nullptr;
623 if (CurrentInstantiationScope)
624 Saved = CurrentInstantiationScope->cloneScopes(OuterMostScope);
625 LateAttrs->push_back(LateInstantiatedAttribute(TmplAttr, Saved, New));
627 // Allow 'this' within late-parsed attributes.
628 NamedDecl *ND = dyn_cast<NamedDecl>(New);
629 CXXRecordDecl *ThisContext =
630 dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext());
631 CXXThisScopeRAII ThisScope(*this, ThisContext, Qualifiers(),
632 ND && ND->isCXXInstanceMember());
634 Attr *NewAttr = sema::instantiateTemplateAttribute(TmplAttr, Context,
635 *this, TemplateArgs);
637 New->addAttr(NewAttr);
642 /// Get the previous declaration of a declaration for the purposes of template
643 /// instantiation. If this finds a previous declaration, then the previous
644 /// declaration of the instantiation of D should be an instantiation of the
645 /// result of this function.
646 template<typename DeclT>
647 static DeclT *getPreviousDeclForInstantiation(DeclT *D) {
648 DeclT *Result = D->getPreviousDecl();
650 // If the declaration is within a class, and the previous declaration was
651 // merged from a different definition of that class, then we don't have a
652 // previous declaration for the purpose of template instantiation.
653 if (Result && isa<CXXRecordDecl>(D->getDeclContext()) &&
654 D->getLexicalDeclContext() != Result->getLexicalDeclContext())
661 TemplateDeclInstantiator::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
662 llvm_unreachable("Translation units cannot be instantiated");
666 TemplateDeclInstantiator::VisitPragmaCommentDecl(PragmaCommentDecl *D) {
667 llvm_unreachable("pragma comment cannot be instantiated");
670 Decl *TemplateDeclInstantiator::VisitPragmaDetectMismatchDecl(
671 PragmaDetectMismatchDecl *D) {
672 llvm_unreachable("pragma comment cannot be instantiated");
676 TemplateDeclInstantiator::VisitExternCContextDecl(ExternCContextDecl *D) {
677 llvm_unreachable("extern \"C\" context cannot be instantiated");
681 TemplateDeclInstantiator::VisitLabelDecl(LabelDecl *D) {
682 LabelDecl *Inst = LabelDecl::Create(SemaRef.Context, Owner, D->getLocation(),
684 Owner->addDecl(Inst);
689 TemplateDeclInstantiator::VisitNamespaceDecl(NamespaceDecl *D) {
690 llvm_unreachable("Namespaces cannot be instantiated");
694 TemplateDeclInstantiator::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
695 NamespaceAliasDecl *Inst
696 = NamespaceAliasDecl::Create(SemaRef.Context, Owner,
697 D->getNamespaceLoc(),
700 D->getQualifierLoc(),
701 D->getTargetNameLoc(),
703 Owner->addDecl(Inst);
707 Decl *TemplateDeclInstantiator::InstantiateTypedefNameDecl(TypedefNameDecl *D,
709 bool Invalid = false;
710 TypeSourceInfo *DI = D->getTypeSourceInfo();
711 if (DI->getType()->isInstantiationDependentType() ||
712 DI->getType()->isVariablyModifiedType()) {
713 DI = SemaRef.SubstType(DI, TemplateArgs,
714 D->getLocation(), D->getDeclName());
717 DI = SemaRef.Context.getTrivialTypeSourceInfo(SemaRef.Context.IntTy);
720 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
723 // HACK: g++ has a bug where it gets the value kind of ?: wrong.
724 // libstdc++ relies upon this bug in its implementation of common_type.
725 // If we happen to be processing that implementation, fake up the g++ ?:
726 // semantics. See LWG issue 2141 for more information on the bug.
727 const DecltypeType *DT = DI->getType()->getAs<DecltypeType>();
728 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D->getDeclContext());
729 if (DT && RD && isa<ConditionalOperator>(DT->getUnderlyingExpr()) &&
730 DT->isReferenceType() &&
731 RD->getEnclosingNamespaceContext() == SemaRef.getStdNamespace() &&
732 RD->getIdentifier() && RD->getIdentifier()->isStr("common_type") &&
733 D->getIdentifier() && D->getIdentifier()->isStr("type") &&
734 SemaRef.getSourceManager().isInSystemHeader(D->getBeginLoc()))
735 // Fold it to the (non-reference) type which g++ would have produced.
736 DI = SemaRef.Context.getTrivialTypeSourceInfo(
737 DI->getType().getNonReferenceType());
739 // Create the new typedef
740 TypedefNameDecl *Typedef;
742 Typedef = TypeAliasDecl::Create(SemaRef.Context, Owner, D->getBeginLoc(),
743 D->getLocation(), D->getIdentifier(), DI);
745 Typedef = TypedefDecl::Create(SemaRef.Context, Owner, D->getBeginLoc(),
746 D->getLocation(), D->getIdentifier(), DI);
748 Typedef->setInvalidDecl();
750 // If the old typedef was the name for linkage purposes of an anonymous
751 // tag decl, re-establish that relationship for the new typedef.
752 if (const TagType *oldTagType = D->getUnderlyingType()->getAs<TagType>()) {
753 TagDecl *oldTag = oldTagType->getDecl();
754 if (oldTag->getTypedefNameForAnonDecl() == D && !Invalid) {
755 TagDecl *newTag = DI->getType()->castAs<TagType>()->getDecl();
756 assert(!newTag->hasNameForLinkage());
757 newTag->setTypedefNameForAnonDecl(Typedef);
761 if (TypedefNameDecl *Prev = getPreviousDeclForInstantiation(D)) {
762 NamedDecl *InstPrev = SemaRef.FindInstantiatedDecl(D->getLocation(), Prev,
767 TypedefNameDecl *InstPrevTypedef = cast<TypedefNameDecl>(InstPrev);
769 // If the typedef types are not identical, reject them.
770 SemaRef.isIncompatibleTypedef(InstPrevTypedef, Typedef);
772 Typedef->setPreviousDecl(InstPrevTypedef);
775 SemaRef.InstantiateAttrs(TemplateArgs, D, Typedef);
777 if (D->getUnderlyingType()->getAs<DependentNameType>())
778 SemaRef.inferGslPointerAttribute(Typedef);
780 Typedef->setAccess(D->getAccess());
785 Decl *TemplateDeclInstantiator::VisitTypedefDecl(TypedefDecl *D) {
786 Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/false);
788 Owner->addDecl(Typedef);
792 Decl *TemplateDeclInstantiator::VisitTypeAliasDecl(TypeAliasDecl *D) {
793 Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/true);
795 Owner->addDecl(Typedef);
800 TemplateDeclInstantiator::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) {
801 // Create a local instantiation scope for this type alias template, which
802 // will contain the instantiations of the template parameters.
803 LocalInstantiationScope Scope(SemaRef);
805 TemplateParameterList *TempParams = D->getTemplateParameters();
806 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
810 TypeAliasDecl *Pattern = D->getTemplatedDecl();
812 TypeAliasTemplateDecl *PrevAliasTemplate = nullptr;
813 if (getPreviousDeclForInstantiation<TypedefNameDecl>(Pattern)) {
814 DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
815 if (!Found.empty()) {
816 PrevAliasTemplate = dyn_cast<TypeAliasTemplateDecl>(Found.front());
820 TypeAliasDecl *AliasInst = cast_or_null<TypeAliasDecl>(
821 InstantiateTypedefNameDecl(Pattern, /*IsTypeAlias=*/true));
825 TypeAliasTemplateDecl *Inst
826 = TypeAliasTemplateDecl::Create(SemaRef.Context, Owner, D->getLocation(),
827 D->getDeclName(), InstParams, AliasInst);
828 AliasInst->setDescribedAliasTemplate(Inst);
829 if (PrevAliasTemplate)
830 Inst->setPreviousDecl(PrevAliasTemplate);
832 Inst->setAccess(D->getAccess());
834 if (!PrevAliasTemplate)
835 Inst->setInstantiatedFromMemberTemplate(D);
837 Owner->addDecl(Inst);
842 Decl *TemplateDeclInstantiator::VisitBindingDecl(BindingDecl *D) {
843 auto *NewBD = BindingDecl::Create(SemaRef.Context, Owner, D->getLocation(),
845 NewBD->setReferenced(D->isReferenced());
846 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewBD);
850 Decl *TemplateDeclInstantiator::VisitDecompositionDecl(DecompositionDecl *D) {
851 // Transform the bindings first.
852 SmallVector<BindingDecl*, 16> NewBindings;
853 for (auto *OldBD : D->bindings())
854 NewBindings.push_back(cast<BindingDecl>(VisitBindingDecl(OldBD)));
855 ArrayRef<BindingDecl*> NewBindingArray = NewBindings;
857 auto *NewDD = cast_or_null<DecompositionDecl>(
858 VisitVarDecl(D, /*InstantiatingVarTemplate=*/false, &NewBindingArray));
860 if (!NewDD || NewDD->isInvalidDecl())
861 for (auto *NewBD : NewBindings)
862 NewBD->setInvalidDecl();
867 Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D) {
868 return VisitVarDecl(D, /*InstantiatingVarTemplate=*/false);
871 Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D,
872 bool InstantiatingVarTemplate,
873 ArrayRef<BindingDecl*> *Bindings) {
875 // Do substitution on the type of the declaration
876 TypeSourceInfo *DI = SemaRef.SubstType(
877 D->getTypeSourceInfo(), TemplateArgs, D->getTypeSpecStartLoc(),
878 D->getDeclName(), /*AllowDeducedTST*/true);
882 if (DI->getType()->isFunctionType()) {
883 SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function)
884 << D->isStaticDataMember() << DI->getType();
888 DeclContext *DC = Owner;
889 if (D->isLocalExternDecl())
890 SemaRef.adjustContextForLocalExternDecl(DC);
892 // Build the instantiated declaration.
895 Var = DecompositionDecl::Create(SemaRef.Context, DC, D->getInnerLocStart(),
896 D->getLocation(), DI->getType(), DI,
897 D->getStorageClass(), *Bindings);
899 Var = VarDecl::Create(SemaRef.Context, DC, D->getInnerLocStart(),
900 D->getLocation(), D->getIdentifier(), DI->getType(),
901 DI, D->getStorageClass());
903 // In ARC, infer 'retaining' for variables of retainable type.
904 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
905 SemaRef.inferObjCARCLifetime(Var))
906 Var->setInvalidDecl();
908 // Substitute the nested name specifier, if any.
909 if (SubstQualifier(D, Var))
912 SemaRef.BuildVariableInstantiation(Var, D, TemplateArgs, LateAttrs, Owner,
913 StartingScope, InstantiatingVarTemplate);
915 if (D->isNRVOVariable()) {
916 QualType ReturnType = cast<FunctionDecl>(DC)->getReturnType();
917 if (SemaRef.isCopyElisionCandidate(ReturnType, Var, Sema::CES_Strict))
918 Var->setNRVOVariable(true);
921 Var->setImplicit(D->isImplicit());
923 if (Var->isStaticLocal())
924 SemaRef.CheckStaticLocalForDllExport(Var);
929 Decl *TemplateDeclInstantiator::VisitAccessSpecDecl(AccessSpecDecl *D) {
931 = AccessSpecDecl::Create(SemaRef.Context, D->getAccess(), Owner,
932 D->getAccessSpecifierLoc(), D->getColonLoc());
933 Owner->addHiddenDecl(AD);
937 Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) {
938 bool Invalid = false;
939 TypeSourceInfo *DI = D->getTypeSourceInfo();
940 if (DI->getType()->isInstantiationDependentType() ||
941 DI->getType()->isVariablyModifiedType()) {
942 DI = SemaRef.SubstType(DI, TemplateArgs,
943 D->getLocation(), D->getDeclName());
945 DI = D->getTypeSourceInfo();
947 } else if (DI->getType()->isFunctionType()) {
948 // C++ [temp.arg.type]p3:
949 // If a declaration acquires a function type through a type
950 // dependent on a template-parameter and this causes a
951 // declaration that does not use the syntactic form of a
952 // function declarator to have function type, the program is
954 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
959 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
962 Expr *BitWidth = D->getBitWidth();
966 // The bit-width expression is a constant expression.
967 EnterExpressionEvaluationContext Unevaluated(
968 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
970 ExprResult InstantiatedBitWidth
971 = SemaRef.SubstExpr(BitWidth, TemplateArgs);
972 if (InstantiatedBitWidth.isInvalid()) {
976 BitWidth = InstantiatedBitWidth.getAs<Expr>();
979 FieldDecl *Field = SemaRef.CheckFieldDecl(D->getDeclName(),
981 cast<RecordDecl>(Owner),
985 D->getInClassInitStyle(),
986 D->getInnerLocStart(),
990 cast<Decl>(Owner)->setInvalidDecl();
994 SemaRef.InstantiateAttrs(TemplateArgs, D, Field, LateAttrs, StartingScope);
996 if (Field->hasAttrs())
997 SemaRef.CheckAlignasUnderalignment(Field);
1000 Field->setInvalidDecl();
1002 if (!Field->getDeclName()) {
1003 // Keep track of where this decl came from.
1004 SemaRef.Context.setInstantiatedFromUnnamedFieldDecl(Field, D);
1006 if (CXXRecordDecl *Parent= dyn_cast<CXXRecordDecl>(Field->getDeclContext())) {
1007 if (Parent->isAnonymousStructOrUnion() &&
1008 Parent->getRedeclContext()->isFunctionOrMethod())
1009 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Field);
1012 Field->setImplicit(D->isImplicit());
1013 Field->setAccess(D->getAccess());
1014 Owner->addDecl(Field);
1019 Decl *TemplateDeclInstantiator::VisitMSPropertyDecl(MSPropertyDecl *D) {
1020 bool Invalid = false;
1021 TypeSourceInfo *DI = D->getTypeSourceInfo();
1023 if (DI->getType()->isVariablyModifiedType()) {
1024 SemaRef.Diag(D->getLocation(), diag::err_property_is_variably_modified)
1027 } else if (DI->getType()->isInstantiationDependentType()) {
1028 DI = SemaRef.SubstType(DI, TemplateArgs,
1029 D->getLocation(), D->getDeclName());
1031 DI = D->getTypeSourceInfo();
1033 } else if (DI->getType()->isFunctionType()) {
1034 // C++ [temp.arg.type]p3:
1035 // If a declaration acquires a function type through a type
1036 // dependent on a template-parameter and this causes a
1037 // declaration that does not use the syntactic form of a
1038 // function declarator to have function type, the program is
1040 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
1045 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
1048 MSPropertyDecl *Property = MSPropertyDecl::Create(
1049 SemaRef.Context, Owner, D->getLocation(), D->getDeclName(), DI->getType(),
1050 DI, D->getBeginLoc(), D->getGetterId(), D->getSetterId());
1052 SemaRef.InstantiateAttrs(TemplateArgs, D, Property, LateAttrs,
1056 Property->setInvalidDecl();
1058 Property->setAccess(D->getAccess());
1059 Owner->addDecl(Property);
1064 Decl *TemplateDeclInstantiator::VisitIndirectFieldDecl(IndirectFieldDecl *D) {
1065 NamedDecl **NamedChain =
1066 new (SemaRef.Context)NamedDecl*[D->getChainingSize()];
1069 for (auto *PI : D->chain()) {
1070 NamedDecl *Next = SemaRef.FindInstantiatedDecl(D->getLocation(), PI,
1075 NamedChain[i++] = Next;
1078 QualType T = cast<FieldDecl>(NamedChain[i-1])->getType();
1079 IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
1080 SemaRef.Context, Owner, D->getLocation(), D->getIdentifier(), T,
1081 {NamedChain, D->getChainingSize()});
1083 for (const auto *Attr : D->attrs())
1084 IndirectField->addAttr(Attr->clone(SemaRef.Context));
1086 IndirectField->setImplicit(D->isImplicit());
1087 IndirectField->setAccess(D->getAccess());
1088 Owner->addDecl(IndirectField);
1089 return IndirectField;
1092 Decl *TemplateDeclInstantiator::VisitFriendDecl(FriendDecl *D) {
1093 // Handle friend type expressions by simply substituting template
1094 // parameters into the pattern type and checking the result.
1095 if (TypeSourceInfo *Ty = D->getFriendType()) {
1096 TypeSourceInfo *InstTy;
1097 // If this is an unsupported friend, don't bother substituting template
1098 // arguments into it. The actual type referred to won't be used by any
1099 // parts of Clang, and may not be valid for instantiating. Just use the
1100 // same info for the instantiated friend.
1101 if (D->isUnsupportedFriend()) {
1104 InstTy = SemaRef.SubstType(Ty, TemplateArgs,
1105 D->getLocation(), DeclarationName());
1110 FriendDecl *FD = SemaRef.CheckFriendTypeDecl(D->getBeginLoc(),
1111 D->getFriendLoc(), InstTy);
1115 FD->setAccess(AS_public);
1116 FD->setUnsupportedFriend(D->isUnsupportedFriend());
1121 NamedDecl *ND = D->getFriendDecl();
1122 assert(ND && "friend decl must be a decl or a type!");
1124 // All of the Visit implementations for the various potential friend
1125 // declarations have to be carefully written to work for friend
1126 // objects, with the most important detail being that the target
1127 // decl should almost certainly not be placed in Owner.
1128 Decl *NewND = Visit(ND);
1129 if (!NewND) return nullptr;
1132 FriendDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1133 cast<NamedDecl>(NewND), D->getFriendLoc());
1134 FD->setAccess(AS_public);
1135 FD->setUnsupportedFriend(D->isUnsupportedFriend());
1140 Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) {
1141 Expr *AssertExpr = D->getAssertExpr();
1143 // The expression in a static assertion is a constant expression.
1144 EnterExpressionEvaluationContext Unevaluated(
1145 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
1147 ExprResult InstantiatedAssertExpr
1148 = SemaRef.SubstExpr(AssertExpr, TemplateArgs);
1149 if (InstantiatedAssertExpr.isInvalid())
1152 return SemaRef.BuildStaticAssertDeclaration(D->getLocation(),
1153 InstantiatedAssertExpr.get(),
1159 Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) {
1160 EnumDecl *PrevDecl = nullptr;
1161 if (EnumDecl *PatternPrev = getPreviousDeclForInstantiation(D)) {
1162 NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
1165 if (!Prev) return nullptr;
1166 PrevDecl = cast<EnumDecl>(Prev);
1170 EnumDecl::Create(SemaRef.Context, Owner, D->getBeginLoc(),
1171 D->getLocation(), D->getIdentifier(), PrevDecl,
1172 D->isScoped(), D->isScopedUsingClassTag(), D->isFixed());
1174 if (TypeSourceInfo *TI = D->getIntegerTypeSourceInfo()) {
1175 // If we have type source information for the underlying type, it means it
1176 // has been explicitly set by the user. Perform substitution on it before
1178 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
1179 TypeSourceInfo *NewTI = SemaRef.SubstType(TI, TemplateArgs, UnderlyingLoc,
1181 if (!NewTI || SemaRef.CheckEnumUnderlyingType(NewTI))
1182 Enum->setIntegerType(SemaRef.Context.IntTy);
1184 Enum->setIntegerTypeSourceInfo(NewTI);
1186 assert(!D->getIntegerType()->isDependentType()
1187 && "Dependent type without type source info");
1188 Enum->setIntegerType(D->getIntegerType());
1192 SemaRef.InstantiateAttrs(TemplateArgs, D, Enum);
1194 Enum->setInstantiationOfMemberEnum(D, TSK_ImplicitInstantiation);
1195 Enum->setAccess(D->getAccess());
1196 // Forward the mangling number from the template to the instantiated decl.
1197 SemaRef.Context.setManglingNumber(Enum, SemaRef.Context.getManglingNumber(D));
1198 // See if the old tag was defined along with a declarator.
1199 // If it did, mark the new tag as being associated with that declarator.
1200 if (DeclaratorDecl *DD = SemaRef.Context.getDeclaratorForUnnamedTagDecl(D))
1201 SemaRef.Context.addDeclaratorForUnnamedTagDecl(Enum, DD);
1202 // See if the old tag was defined along with a typedef.
1203 // If it did, mark the new tag as being associated with that typedef.
1204 if (TypedefNameDecl *TND = SemaRef.Context.getTypedefNameForUnnamedTagDecl(D))
1205 SemaRef.Context.addTypedefNameForUnnamedTagDecl(Enum, TND);
1206 if (SubstQualifier(D, Enum)) return nullptr;
1207 Owner->addDecl(Enum);
1209 EnumDecl *Def = D->getDefinition();
1210 if (Def && Def != D) {
1211 // If this is an out-of-line definition of an enum member template, check
1212 // that the underlying types match in the instantiation of both
1214 if (TypeSourceInfo *TI = Def->getIntegerTypeSourceInfo()) {
1215 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
1216 QualType DefnUnderlying =
1217 SemaRef.SubstType(TI->getType(), TemplateArgs,
1218 UnderlyingLoc, DeclarationName());
1219 SemaRef.CheckEnumRedeclaration(Def->getLocation(), Def->isScoped(),
1220 DefnUnderlying, /*IsFixed=*/true, Enum);
1224 // C++11 [temp.inst]p1: The implicit instantiation of a class template
1225 // specialization causes the implicit instantiation of the declarations, but
1226 // not the definitions of scoped member enumerations.
1228 // DR1484 clarifies that enumeration definitions inside of a template
1229 // declaration aren't considered entities that can be separately instantiated
1230 // from the rest of the entity they are declared inside of.
1231 if (isDeclWithinFunction(D) ? D == Def : Def && !Enum->isScoped()) {
1232 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Enum);
1233 InstantiateEnumDefinition(Enum, Def);
1239 void TemplateDeclInstantiator::InstantiateEnumDefinition(
1240 EnumDecl *Enum, EnumDecl *Pattern) {
1241 Enum->startDefinition();
1243 // Update the location to refer to the definition.
1244 Enum->setLocation(Pattern->getLocation());
1246 SmallVector<Decl*, 4> Enumerators;
1248 EnumConstantDecl *LastEnumConst = nullptr;
1249 for (auto *EC : Pattern->enumerators()) {
1250 // The specified value for the enumerator.
1251 ExprResult Value((Expr *)nullptr);
1252 if (Expr *UninstValue = EC->getInitExpr()) {
1253 // The enumerator's value expression is a constant expression.
1254 EnterExpressionEvaluationContext Unevaluated(
1255 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
1257 Value = SemaRef.SubstExpr(UninstValue, TemplateArgs);
1260 // Drop the initial value and continue.
1261 bool isInvalid = false;
1262 if (Value.isInvalid()) {
1267 EnumConstantDecl *EnumConst
1268 = SemaRef.CheckEnumConstant(Enum, LastEnumConst,
1269 EC->getLocation(), EC->getIdentifier(),
1274 EnumConst->setInvalidDecl();
1275 Enum->setInvalidDecl();
1279 SemaRef.InstantiateAttrs(TemplateArgs, EC, EnumConst);
1281 EnumConst->setAccess(Enum->getAccess());
1282 Enum->addDecl(EnumConst);
1283 Enumerators.push_back(EnumConst);
1284 LastEnumConst = EnumConst;
1286 if (Pattern->getDeclContext()->isFunctionOrMethod() &&
1287 !Enum->isScoped()) {
1288 // If the enumeration is within a function or method, record the enum
1289 // constant as a local.
1290 SemaRef.CurrentInstantiationScope->InstantiatedLocal(EC, EnumConst);
1295 SemaRef.ActOnEnumBody(Enum->getLocation(), Enum->getBraceRange(), Enum,
1296 Enumerators, nullptr, ParsedAttributesView());
1299 Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) {
1300 llvm_unreachable("EnumConstantDecls can only occur within EnumDecls.");
1304 TemplateDeclInstantiator::VisitBuiltinTemplateDecl(BuiltinTemplateDecl *D) {
1305 llvm_unreachable("BuiltinTemplateDecls cannot be instantiated.");
1308 Decl *TemplateDeclInstantiator::VisitClassTemplateDecl(ClassTemplateDecl *D) {
1309 bool isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
1311 // Create a local instantiation scope for this class template, which
1312 // will contain the instantiations of the template parameters.
1313 LocalInstantiationScope Scope(SemaRef);
1314 TemplateParameterList *TempParams = D->getTemplateParameters();
1315 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1319 CXXRecordDecl *Pattern = D->getTemplatedDecl();
1321 // Instantiate the qualifier. We have to do this first in case
1322 // we're a friend declaration, because if we are then we need to put
1323 // the new declaration in the appropriate context.
1324 NestedNameSpecifierLoc QualifierLoc = Pattern->getQualifierLoc();
1326 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
1332 CXXRecordDecl *PrevDecl = nullptr;
1333 ClassTemplateDecl *PrevClassTemplate = nullptr;
1335 if (!isFriend && getPreviousDeclForInstantiation(Pattern)) {
1336 DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
1337 if (!Found.empty()) {
1338 PrevClassTemplate = dyn_cast<ClassTemplateDecl>(Found.front());
1339 if (PrevClassTemplate)
1340 PrevDecl = PrevClassTemplate->getTemplatedDecl();
1344 // If this isn't a friend, then it's a member template, in which
1345 // case we just want to build the instantiation in the
1346 // specialization. If it is a friend, we want to build it in
1347 // the appropriate context.
1348 DeclContext *DC = Owner;
1352 SS.Adopt(QualifierLoc);
1353 DC = SemaRef.computeDeclContext(SS);
1354 if (!DC) return nullptr;
1356 DC = SemaRef.FindInstantiatedContext(Pattern->getLocation(),
1357 Pattern->getDeclContext(),
1361 // Look for a previous declaration of the template in the owning
1363 LookupResult R(SemaRef, Pattern->getDeclName(), Pattern->getLocation(),
1364 Sema::LookupOrdinaryName,
1365 SemaRef.forRedeclarationInCurContext());
1366 SemaRef.LookupQualifiedName(R, DC);
1368 if (R.isSingleResult()) {
1369 PrevClassTemplate = R.getAsSingle<ClassTemplateDecl>();
1370 if (PrevClassTemplate)
1371 PrevDecl = PrevClassTemplate->getTemplatedDecl();
1374 if (!PrevClassTemplate && QualifierLoc) {
1375 SemaRef.Diag(Pattern->getLocation(), diag::err_not_tag_in_scope)
1376 << D->getTemplatedDecl()->getTagKind() << Pattern->getDeclName() << DC
1377 << QualifierLoc.getSourceRange();
1381 bool AdoptedPreviousTemplateParams = false;
1382 if (PrevClassTemplate) {
1383 bool Complain = true;
1385 // HACK: libstdc++ 4.2.1 contains an ill-formed friend class
1386 // template for struct std::tr1::__detail::_Map_base, where the
1387 // template parameters of the friend declaration don't match the
1388 // template parameters of the original declaration. In this one
1389 // case, we don't complain about the ill-formed friend
1391 if (isFriend && Pattern->getIdentifier() &&
1392 Pattern->getIdentifier()->isStr("_Map_base") &&
1393 DC->isNamespace() &&
1394 cast<NamespaceDecl>(DC)->getIdentifier() &&
1395 cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__detail")) {
1396 DeclContext *DCParent = DC->getParent();
1397 if (DCParent->isNamespace() &&
1398 cast<NamespaceDecl>(DCParent)->getIdentifier() &&
1399 cast<NamespaceDecl>(DCParent)->getIdentifier()->isStr("tr1")) {
1400 if (cast<Decl>(DCParent)->isInStdNamespace())
1405 TemplateParameterList *PrevParams
1406 = PrevClassTemplate->getMostRecentDecl()->getTemplateParameters();
1408 // Make sure the parameter lists match.
1409 if (!SemaRef.TemplateParameterListsAreEqual(InstParams, PrevParams,
1411 Sema::TPL_TemplateMatch)) {
1415 AdoptedPreviousTemplateParams = true;
1416 InstParams = PrevParams;
1419 // Do some additional validation, then merge default arguments
1420 // from the existing declarations.
1421 if (!AdoptedPreviousTemplateParams &&
1422 SemaRef.CheckTemplateParameterList(InstParams, PrevParams,
1423 Sema::TPC_ClassTemplate))
1428 CXXRecordDecl *RecordInst = CXXRecordDecl::Create(
1429 SemaRef.Context, Pattern->getTagKind(), DC, Pattern->getBeginLoc(),
1430 Pattern->getLocation(), Pattern->getIdentifier(), PrevDecl,
1431 /*DelayTypeCreation=*/true);
1434 RecordInst->setQualifierInfo(QualifierLoc);
1436 SemaRef.InstantiateAttrsForDecl(TemplateArgs, Pattern, RecordInst, LateAttrs,
1439 ClassTemplateDecl *Inst
1440 = ClassTemplateDecl::Create(SemaRef.Context, DC, D->getLocation(),
1441 D->getIdentifier(), InstParams, RecordInst);
1442 assert(!(isFriend && Owner->isDependentContext()));
1443 Inst->setPreviousDecl(PrevClassTemplate);
1445 RecordInst->setDescribedClassTemplate(Inst);
1448 if (PrevClassTemplate)
1449 Inst->setAccess(PrevClassTemplate->getAccess());
1451 Inst->setAccess(D->getAccess());
1453 Inst->setObjectOfFriendDecl();
1454 // TODO: do we want to track the instantiation progeny of this
1455 // friend target decl?
1457 Inst->setAccess(D->getAccess());
1458 if (!PrevClassTemplate)
1459 Inst->setInstantiatedFromMemberTemplate(D);
1462 // Trigger creation of the type for the instantiation.
1463 SemaRef.Context.getInjectedClassNameType(RecordInst,
1464 Inst->getInjectedClassNameSpecialization());
1466 // Finish handling of friends.
1468 DC->makeDeclVisibleInContext(Inst);
1469 Inst->setLexicalDeclContext(Owner);
1470 RecordInst->setLexicalDeclContext(Owner);
1474 if (D->isOutOfLine()) {
1475 Inst->setLexicalDeclContext(D->getLexicalDeclContext());
1476 RecordInst->setLexicalDeclContext(D->getLexicalDeclContext());
1479 Owner->addDecl(Inst);
1481 if (!PrevClassTemplate) {
1482 // Queue up any out-of-line partial specializations of this member
1483 // class template; the client will force their instantiation once
1484 // the enclosing class has been instantiated.
1485 SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
1486 D->getPartialSpecializations(PartialSpecs);
1487 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
1488 if (PartialSpecs[I]->getFirstDecl()->isOutOfLine())
1489 OutOfLinePartialSpecs.push_back(std::make_pair(Inst, PartialSpecs[I]));
1496 TemplateDeclInstantiator::VisitClassTemplatePartialSpecializationDecl(
1497 ClassTemplatePartialSpecializationDecl *D) {
1498 ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
1500 // Lookup the already-instantiated declaration in the instantiation
1501 // of the class template and return that.
1502 DeclContext::lookup_result Found
1503 = Owner->lookup(ClassTemplate->getDeclName());
1507 ClassTemplateDecl *InstClassTemplate
1508 = dyn_cast<ClassTemplateDecl>(Found.front());
1509 if (!InstClassTemplate)
1512 if (ClassTemplatePartialSpecializationDecl *Result
1513 = InstClassTemplate->findPartialSpecInstantiatedFromMember(D))
1516 return InstantiateClassTemplatePartialSpecialization(InstClassTemplate, D);
1519 Decl *TemplateDeclInstantiator::VisitVarTemplateDecl(VarTemplateDecl *D) {
1520 assert(D->getTemplatedDecl()->isStaticDataMember() &&
1521 "Only static data member templates are allowed.");
1523 // Create a local instantiation scope for this variable template, which
1524 // will contain the instantiations of the template parameters.
1525 LocalInstantiationScope Scope(SemaRef);
1526 TemplateParameterList *TempParams = D->getTemplateParameters();
1527 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1531 VarDecl *Pattern = D->getTemplatedDecl();
1532 VarTemplateDecl *PrevVarTemplate = nullptr;
1534 if (getPreviousDeclForInstantiation(Pattern)) {
1535 DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
1537 PrevVarTemplate = dyn_cast<VarTemplateDecl>(Found.front());
1541 cast_or_null<VarDecl>(VisitVarDecl(Pattern,
1542 /*InstantiatingVarTemplate=*/true));
1543 if (!VarInst) return nullptr;
1545 DeclContext *DC = Owner;
1547 VarTemplateDecl *Inst = VarTemplateDecl::Create(
1548 SemaRef.Context, DC, D->getLocation(), D->getIdentifier(), InstParams,
1550 VarInst->setDescribedVarTemplate(Inst);
1551 Inst->setPreviousDecl(PrevVarTemplate);
1553 Inst->setAccess(D->getAccess());
1554 if (!PrevVarTemplate)
1555 Inst->setInstantiatedFromMemberTemplate(D);
1557 if (D->isOutOfLine()) {
1558 Inst->setLexicalDeclContext(D->getLexicalDeclContext());
1559 VarInst->setLexicalDeclContext(D->getLexicalDeclContext());
1562 Owner->addDecl(Inst);
1564 if (!PrevVarTemplate) {
1565 // Queue up any out-of-line partial specializations of this member
1566 // variable template; the client will force their instantiation once
1567 // the enclosing class has been instantiated.
1568 SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs;
1569 D->getPartialSpecializations(PartialSpecs);
1570 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
1571 if (PartialSpecs[I]->getFirstDecl()->isOutOfLine())
1572 OutOfLineVarPartialSpecs.push_back(
1573 std::make_pair(Inst, PartialSpecs[I]));
1579 Decl *TemplateDeclInstantiator::VisitVarTemplatePartialSpecializationDecl(
1580 VarTemplatePartialSpecializationDecl *D) {
1581 assert(D->isStaticDataMember() &&
1582 "Only static data member templates are allowed.");
1584 VarTemplateDecl *VarTemplate = D->getSpecializedTemplate();
1586 // Lookup the already-instantiated declaration and return that.
1587 DeclContext::lookup_result Found = Owner->lookup(VarTemplate->getDeclName());
1588 assert(!Found.empty() && "Instantiation found nothing?");
1590 VarTemplateDecl *InstVarTemplate = dyn_cast<VarTemplateDecl>(Found.front());
1591 assert(InstVarTemplate && "Instantiation did not find a variable template?");
1593 if (VarTemplatePartialSpecializationDecl *Result =
1594 InstVarTemplate->findPartialSpecInstantiatedFromMember(D))
1597 return InstantiateVarTemplatePartialSpecialization(InstVarTemplate, D);
1601 TemplateDeclInstantiator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
1602 // Create a local instantiation scope for this function template, which
1603 // will contain the instantiations of the template parameters and then get
1604 // merged with the local instantiation scope for the function template
1606 LocalInstantiationScope Scope(SemaRef);
1608 TemplateParameterList *TempParams = D->getTemplateParameters();
1609 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1613 FunctionDecl *Instantiated = nullptr;
1614 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(D->getTemplatedDecl()))
1615 Instantiated = cast_or_null<FunctionDecl>(VisitCXXMethodDecl(DMethod,
1618 Instantiated = cast_or_null<FunctionDecl>(VisitFunctionDecl(
1619 D->getTemplatedDecl(),
1625 // Link the instantiated function template declaration to the function
1626 // template from which it was instantiated.
1627 FunctionTemplateDecl *InstTemplate
1628 = Instantiated->getDescribedFunctionTemplate();
1629 InstTemplate->setAccess(D->getAccess());
1630 assert(InstTemplate &&
1631 "VisitFunctionDecl/CXXMethodDecl didn't create a template!");
1633 bool isFriend = (InstTemplate->getFriendObjectKind() != Decl::FOK_None);
1635 // Link the instantiation back to the pattern *unless* this is a
1636 // non-definition friend declaration.
1637 if (!InstTemplate->getInstantiatedFromMemberTemplate() &&
1638 !(isFriend && !D->getTemplatedDecl()->isThisDeclarationADefinition()))
1639 InstTemplate->setInstantiatedFromMemberTemplate(D);
1641 // Make declarations visible in the appropriate context.
1643 Owner->addDecl(InstTemplate);
1644 } else if (InstTemplate->getDeclContext()->isRecord() &&
1645 !getPreviousDeclForInstantiation(D)) {
1646 SemaRef.CheckFriendAccess(InstTemplate);
1649 return InstTemplate;
1652 Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) {
1653 CXXRecordDecl *PrevDecl = nullptr;
1654 if (D->isInjectedClassName())
1655 PrevDecl = cast<CXXRecordDecl>(Owner);
1656 else if (CXXRecordDecl *PatternPrev = getPreviousDeclForInstantiation(D)) {
1657 NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
1660 if (!Prev) return nullptr;
1661 PrevDecl = cast<CXXRecordDecl>(Prev);
1664 CXXRecordDecl *Record = CXXRecordDecl::Create(
1665 SemaRef.Context, D->getTagKind(), Owner, D->getBeginLoc(),
1666 D->getLocation(), D->getIdentifier(), PrevDecl);
1668 // Substitute the nested name specifier, if any.
1669 if (SubstQualifier(D, Record))
1672 SemaRef.InstantiateAttrsForDecl(TemplateArgs, D, Record, LateAttrs,
1675 Record->setImplicit(D->isImplicit());
1676 // FIXME: Check against AS_none is an ugly hack to work around the issue that
1677 // the tag decls introduced by friend class declarations don't have an access
1678 // specifier. Remove once this area of the code gets sorted out.
1679 if (D->getAccess() != AS_none)
1680 Record->setAccess(D->getAccess());
1681 if (!D->isInjectedClassName())
1682 Record->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
1684 // If the original function was part of a friend declaration,
1685 // inherit its namespace state.
1686 if (D->getFriendObjectKind())
1687 Record->setObjectOfFriendDecl();
1689 // Make sure that anonymous structs and unions are recorded.
1690 if (D->isAnonymousStructOrUnion())
1691 Record->setAnonymousStructOrUnion(true);
1693 if (D->isLocalClass())
1694 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Record);
1696 // Forward the mangling number from the template to the instantiated decl.
1697 SemaRef.Context.setManglingNumber(Record,
1698 SemaRef.Context.getManglingNumber(D));
1700 // See if the old tag was defined along with a declarator.
1701 // If it did, mark the new tag as being associated with that declarator.
1702 if (DeclaratorDecl *DD = SemaRef.Context.getDeclaratorForUnnamedTagDecl(D))
1703 SemaRef.Context.addDeclaratorForUnnamedTagDecl(Record, DD);
1705 // See if the old tag was defined along with a typedef.
1706 // If it did, mark the new tag as being associated with that typedef.
1707 if (TypedefNameDecl *TND = SemaRef.Context.getTypedefNameForUnnamedTagDecl(D))
1708 SemaRef.Context.addTypedefNameForUnnamedTagDecl(Record, TND);
1710 Owner->addDecl(Record);
1712 // DR1484 clarifies that the members of a local class are instantiated as part
1713 // of the instantiation of their enclosing entity.
1714 if (D->isCompleteDefinition() && D->isLocalClass()) {
1715 Sema::LocalEagerInstantiationScope LocalInstantiations(SemaRef);
1717 SemaRef.InstantiateClass(D->getLocation(), Record, D, TemplateArgs,
1718 TSK_ImplicitInstantiation,
1721 // For nested local classes, we will instantiate the members when we
1722 // reach the end of the outermost (non-nested) local class.
1723 if (!D->isCXXClassMember())
1724 SemaRef.InstantiateClassMembers(D->getLocation(), Record, TemplateArgs,
1725 TSK_ImplicitInstantiation);
1727 // This class may have local implicit instantiations that need to be
1728 // performed within this scope.
1729 LocalInstantiations.perform();
1732 SemaRef.DiagnoseUnusedNestedTypedefs(Record);
1737 /// Adjust the given function type for an instantiation of the
1738 /// given declaration, to cope with modifications to the function's type that
1739 /// aren't reflected in the type-source information.
1741 /// \param D The declaration we're instantiating.
1742 /// \param TInfo The already-instantiated type.
1743 static QualType adjustFunctionTypeForInstantiation(ASTContext &Context,
1745 TypeSourceInfo *TInfo) {
1746 const FunctionProtoType *OrigFunc
1747 = D->getType()->castAs<FunctionProtoType>();
1748 const FunctionProtoType *NewFunc
1749 = TInfo->getType()->castAs<FunctionProtoType>();
1750 if (OrigFunc->getExtInfo() == NewFunc->getExtInfo())
1751 return TInfo->getType();
1753 FunctionProtoType::ExtProtoInfo NewEPI = NewFunc->getExtProtoInfo();
1754 NewEPI.ExtInfo = OrigFunc->getExtInfo();
1755 return Context.getFunctionType(NewFunc->getReturnType(),
1756 NewFunc->getParamTypes(), NewEPI);
1759 /// Normal class members are of more specific types and therefore
1760 /// don't make it here. This function serves three purposes:
1761 /// 1) instantiating function templates
1762 /// 2) substituting friend declarations
1763 /// 3) substituting deduction guide declarations for nested class templates
1764 Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D,
1765 TemplateParameterList *TemplateParams) {
1766 // Check whether there is already a function template specialization for
1767 // this declaration.
1768 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
1769 if (FunctionTemplate && !TemplateParams) {
1770 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
1772 void *InsertPos = nullptr;
1773 FunctionDecl *SpecFunc
1774 = FunctionTemplate->findSpecialization(Innermost, InsertPos);
1776 // If we already have a function template specialization, return it.
1782 if (FunctionTemplate)
1783 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
1785 isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
1787 bool MergeWithParentScope = (TemplateParams != nullptr) ||
1788 Owner->isFunctionOrMethod() ||
1789 !(isa<Decl>(Owner) &&
1790 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
1791 LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
1793 ExplicitSpecifier InstantiatedExplicitSpecifier;
1794 if (auto *DGuide = dyn_cast<CXXDeductionGuideDecl>(D)) {
1795 InstantiatedExplicitSpecifier = instantiateExplicitSpecifier(
1796 SemaRef, TemplateArgs, DGuide->getExplicitSpecifier(), DGuide);
1797 if (InstantiatedExplicitSpecifier.isInvalid())
1801 SmallVector<ParmVarDecl *, 4> Params;
1802 TypeSourceInfo *TInfo = SubstFunctionType(D, Params);
1805 QualType T = adjustFunctionTypeForInstantiation(SemaRef.Context, D, TInfo);
1807 NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
1809 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
1815 // If we're instantiating a local function declaration, put the result
1816 // in the enclosing namespace; otherwise we need to find the instantiated
1819 if (D->isLocalExternDecl()) {
1821 SemaRef.adjustContextForLocalExternDecl(DC);
1822 } else if (isFriend && QualifierLoc) {
1824 SS.Adopt(QualifierLoc);
1825 DC = SemaRef.computeDeclContext(SS);
1826 if (!DC) return nullptr;
1828 DC = SemaRef.FindInstantiatedContext(D->getLocation(), D->getDeclContext(),
1832 DeclarationNameInfo NameInfo
1833 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
1835 FunctionDecl *Function;
1836 if (auto *DGuide = dyn_cast<CXXDeductionGuideDecl>(D)) {
1837 Function = CXXDeductionGuideDecl::Create(
1838 SemaRef.Context, DC, D->getInnerLocStart(),
1839 InstantiatedExplicitSpecifier, NameInfo, T, TInfo,
1840 D->getSourceRange().getEnd());
1841 if (DGuide->isCopyDeductionCandidate())
1842 cast<CXXDeductionGuideDecl>(Function)->setIsCopyDeductionCandidate();
1843 Function->setAccess(D->getAccess());
1845 Function = FunctionDecl::Create(
1846 SemaRef.Context, DC, D->getInnerLocStart(), NameInfo, T, TInfo,
1847 D->getCanonicalDecl()->getStorageClass(), D->isInlineSpecified(),
1848 D->hasWrittenPrototype(), D->getConstexprKind());
1849 Function->setRangeEnd(D->getSourceRange().getEnd());
1853 Function->setImplicitlyInline();
1856 Function->setQualifierInfo(QualifierLoc);
1858 if (D->isLocalExternDecl())
1859 Function->setLocalExternDecl();
1861 DeclContext *LexicalDC = Owner;
1862 if (!isFriend && D->isOutOfLine() && !D->isLocalExternDecl()) {
1863 assert(D->getDeclContext()->isFileContext());
1864 LexicalDC = D->getDeclContext();
1867 Function->setLexicalDeclContext(LexicalDC);
1869 // Attach the parameters
1870 for (unsigned P = 0; P < Params.size(); ++P)
1872 Params[P]->setOwningFunction(Function);
1873 Function->setParams(Params);
1875 if (TemplateParams) {
1876 // Our resulting instantiation is actually a function template, since we
1877 // are substituting only the outer template parameters. For example, given
1879 // template<typename T>
1881 // template<typename U> friend void f(T, U);
1886 // We are instantiating the friend function template "f" within X<int>,
1887 // which means substituting int for T, but leaving "f" as a friend function
1889 // Build the function template itself.
1890 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, DC,
1891 Function->getLocation(),
1892 Function->getDeclName(),
1893 TemplateParams, Function);
1894 Function->setDescribedFunctionTemplate(FunctionTemplate);
1896 FunctionTemplate->setLexicalDeclContext(LexicalDC);
1898 if (isFriend && D->isThisDeclarationADefinition()) {
1899 FunctionTemplate->setInstantiatedFromMemberTemplate(
1900 D->getDescribedFunctionTemplate());
1902 } else if (FunctionTemplate) {
1903 // Record this function template specialization.
1904 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
1905 Function->setFunctionTemplateSpecialization(FunctionTemplate,
1906 TemplateArgumentList::CreateCopy(SemaRef.Context,
1908 /*InsertPos=*/nullptr);
1909 } else if (isFriend && D->isThisDeclarationADefinition()) {
1910 // Do not connect the friend to the template unless it's actually a
1911 // definition. We don't want non-template functions to be marked as being
1912 // template instantiations.
1913 Function->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
1917 Function->setObjectOfFriendDecl();
1919 if (InitFunctionInstantiation(Function, D))
1920 Function->setInvalidDecl();
1922 bool IsExplicitSpecialization = false;
1924 LookupResult Previous(
1925 SemaRef, Function->getDeclName(), SourceLocation(),
1926 D->isLocalExternDecl() ? Sema::LookupRedeclarationWithLinkage
1927 : Sema::LookupOrdinaryName,
1928 D->isLocalExternDecl() ? Sema::ForExternalRedeclaration
1929 : SemaRef.forRedeclarationInCurContext());
1931 if (DependentFunctionTemplateSpecializationInfo *Info
1932 = D->getDependentSpecializationInfo()) {
1933 assert(isFriend && "non-friend has dependent specialization info?");
1935 // Instantiate the explicit template arguments.
1936 TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(),
1937 Info->getRAngleLoc());
1938 if (SemaRef.Subst(Info->getTemplateArgs(), Info->getNumTemplateArgs(),
1939 ExplicitArgs, TemplateArgs))
1942 // Map the candidate templates to their instantiations.
1943 for (unsigned I = 0, E = Info->getNumTemplates(); I != E; ++I) {
1944 Decl *Temp = SemaRef.FindInstantiatedDecl(D->getLocation(),
1945 Info->getTemplate(I),
1947 if (!Temp) return nullptr;
1949 Previous.addDecl(cast<FunctionTemplateDecl>(Temp));
1952 if (SemaRef.CheckFunctionTemplateSpecialization(Function,
1955 Function->setInvalidDecl();
1957 IsExplicitSpecialization = true;
1958 } else if (const ASTTemplateArgumentListInfo *Info =
1959 D->getTemplateSpecializationArgsAsWritten()) {
1960 // The name of this function was written as a template-id.
1961 SemaRef.LookupQualifiedName(Previous, DC);
1963 // Instantiate the explicit template arguments.
1964 TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(),
1965 Info->getRAngleLoc());
1966 if (SemaRef.Subst(Info->getTemplateArgs(), Info->getNumTemplateArgs(),
1967 ExplicitArgs, TemplateArgs))
1970 if (SemaRef.CheckFunctionTemplateSpecialization(Function,
1973 Function->setInvalidDecl();
1975 IsExplicitSpecialization = true;
1976 } else if (TemplateParams || !FunctionTemplate) {
1977 // Look only into the namespace where the friend would be declared to
1978 // find a previous declaration. This is the innermost enclosing namespace,
1979 // as described in ActOnFriendFunctionDecl.
1980 SemaRef.LookupQualifiedName(Previous, DC);
1982 // In C++, the previous declaration we find might be a tag type
1983 // (class or enum). In this case, the new declaration will hide the
1984 // tag type. Note that this does does not apply if we're declaring a
1985 // typedef (C++ [dcl.typedef]p4).
1986 if (Previous.isSingleTagDecl())
1990 SemaRef.CheckFunctionDeclaration(/*Scope*/ nullptr, Function, Previous,
1991 IsExplicitSpecialization);
1993 NamedDecl *PrincipalDecl = (TemplateParams
1994 ? cast<NamedDecl>(FunctionTemplate)
1997 // If the original function was part of a friend declaration,
1998 // inherit its namespace state and add it to the owner.
2000 Function->setObjectOfFriendDecl();
2001 if (FunctionTemplateDecl *FT = Function->getDescribedFunctionTemplate())
2002 FT->setObjectOfFriendDecl();
2003 DC->makeDeclVisibleInContext(PrincipalDecl);
2005 bool QueuedInstantiation = false;
2007 // C++11 [temp.friend]p4 (DR329):
2008 // When a function is defined in a friend function declaration in a class
2009 // template, the function is instantiated when the function is odr-used.
2010 // The same restrictions on multiple declarations and definitions that
2011 // apply to non-template function declarations and definitions also apply
2012 // to these implicit definitions.
2013 if (D->isThisDeclarationADefinition()) {
2014 SemaRef.CheckForFunctionRedefinition(Function);
2015 if (!Function->isInvalidDecl()) {
2016 for (auto R : Function->redecls()) {
2020 // If some prior declaration of this function has been used, we need
2021 // to instantiate its definition.
2022 if (!QueuedInstantiation && R->isUsed(false)) {
2023 if (MemberSpecializationInfo *MSInfo =
2024 Function->getMemberSpecializationInfo()) {
2025 if (MSInfo->getPointOfInstantiation().isInvalid()) {
2026 SourceLocation Loc = R->getLocation(); // FIXME
2027 MSInfo->setPointOfInstantiation(Loc);
2028 SemaRef.PendingLocalImplicitInstantiations.push_back(
2029 std::make_pair(Function, Loc));
2030 QueuedInstantiation = true;
2038 // Check the template parameter list against the previous declaration. The
2039 // goal here is to pick up default arguments added since the friend was
2040 // declared; we know the template parameter lists match, since otherwise
2041 // we would not have picked this template as the previous declaration.
2042 if (TemplateParams && FunctionTemplate->getPreviousDecl()) {
2043 SemaRef.CheckTemplateParameterList(
2045 FunctionTemplate->getPreviousDecl()->getTemplateParameters(),
2046 Function->isThisDeclarationADefinition()
2047 ? Sema::TPC_FriendFunctionTemplateDefinition
2048 : Sema::TPC_FriendFunctionTemplate);
2052 if (Function->isLocalExternDecl() && !Function->getPreviousDecl())
2053 DC->makeDeclVisibleInContext(PrincipalDecl);
2055 if (Function->isOverloadedOperator() && !DC->isRecord() &&
2056 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
2057 PrincipalDecl->setNonMemberOperator();
2059 assert(!D->isDefaulted() && "only methods should be defaulted");
2063 Decl *TemplateDeclInstantiator::VisitCXXMethodDecl(
2064 CXXMethodDecl *D, TemplateParameterList *TemplateParams,
2065 Optional<const ASTTemplateArgumentListInfo *>
2066 ClassScopeSpecializationArgs) {
2067 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
2068 if (FunctionTemplate && !TemplateParams) {
2069 // We are creating a function template specialization from a function
2070 // template. Check whether there is already a function template
2071 // specialization for this particular set of template arguments.
2072 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
2074 void *InsertPos = nullptr;
2075 FunctionDecl *SpecFunc
2076 = FunctionTemplate->findSpecialization(Innermost, InsertPos);
2078 // If we already have a function template specialization, return it.
2084 if (FunctionTemplate)
2085 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
2087 isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
2089 bool MergeWithParentScope = (TemplateParams != nullptr) ||
2090 !(isa<Decl>(Owner) &&
2091 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
2092 LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
2094 // Instantiate enclosing template arguments for friends.
2095 SmallVector<TemplateParameterList *, 4> TempParamLists;
2096 unsigned NumTempParamLists = 0;
2097 if (isFriend && (NumTempParamLists = D->getNumTemplateParameterLists())) {
2098 TempParamLists.resize(NumTempParamLists);
2099 for (unsigned I = 0; I != NumTempParamLists; ++I) {
2100 TemplateParameterList *TempParams = D->getTemplateParameterList(I);
2101 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
2104 TempParamLists[I] = InstParams;
2108 ExplicitSpecifier InstantiatedExplicitSpecifier =
2109 instantiateExplicitSpecifier(SemaRef, TemplateArgs,
2110 ExplicitSpecifier::getFromDecl(D), D);
2111 if (InstantiatedExplicitSpecifier.isInvalid())
2114 SmallVector<ParmVarDecl *, 4> Params;
2115 TypeSourceInfo *TInfo = SubstFunctionType(D, Params);
2118 QualType T = adjustFunctionTypeForInstantiation(SemaRef.Context, D, TInfo);
2120 NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
2122 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
2128 DeclContext *DC = Owner;
2132 SS.Adopt(QualifierLoc);
2133 DC = SemaRef.computeDeclContext(SS);
2135 if (DC && SemaRef.RequireCompleteDeclContext(SS, DC))
2138 DC = SemaRef.FindInstantiatedContext(D->getLocation(),
2139 D->getDeclContext(),
2142 if (!DC) return nullptr;
2145 // Build the instantiated method declaration.
2146 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
2147 CXXMethodDecl *Method = nullptr;
2149 SourceLocation StartLoc = D->getInnerLocStart();
2150 DeclarationNameInfo NameInfo
2151 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
2152 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
2153 Method = CXXConstructorDecl::Create(
2154 SemaRef.Context, Record, StartLoc, NameInfo, T, TInfo,
2155 InstantiatedExplicitSpecifier, Constructor->isInlineSpecified(), false,
2156 Constructor->getConstexprKind());
2157 Method->setRangeEnd(Constructor->getEndLoc());
2158 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
2159 Method = CXXDestructorDecl::Create(
2160 SemaRef.Context, Record, StartLoc, NameInfo, T, TInfo,
2161 Destructor->isInlineSpecified(), false, Destructor->getConstexprKind());
2162 Method->setRangeEnd(Destructor->getEndLoc());
2163 } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) {
2164 Method = CXXConversionDecl::Create(
2165 SemaRef.Context, Record, StartLoc, NameInfo, T, TInfo,
2166 Conversion->isInlineSpecified(), InstantiatedExplicitSpecifier,
2167 Conversion->getConstexprKind(), Conversion->getEndLoc());
2169 StorageClass SC = D->isStatic() ? SC_Static : SC_None;
2170 Method = CXXMethodDecl::Create(SemaRef.Context, Record, StartLoc, NameInfo,
2171 T, TInfo, SC, D->isInlineSpecified(),
2172 D->getConstexprKind(), D->getEndLoc());
2176 Method->setImplicitlyInline();
2179 Method->setQualifierInfo(QualifierLoc);
2181 if (TemplateParams) {
2182 // Our resulting instantiation is actually a function template, since we
2183 // are substituting only the outer template parameters. For example, given
2185 // template<typename T>
2187 // template<typename U> void f(T, U);
2192 // We are instantiating the member template "f" within X<int>, which means
2193 // substituting int for T, but leaving "f" as a member function template.
2194 // Build the function template itself.
2195 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Record,
2196 Method->getLocation(),
2197 Method->getDeclName(),
2198 TemplateParams, Method);
2200 FunctionTemplate->setLexicalDeclContext(Owner);
2201 FunctionTemplate->setObjectOfFriendDecl();
2202 } else if (D->isOutOfLine())
2203 FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
2204 Method->setDescribedFunctionTemplate(FunctionTemplate);
2205 } else if (FunctionTemplate) {
2206 // Record this function template specialization.
2207 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
2208 Method->setFunctionTemplateSpecialization(FunctionTemplate,
2209 TemplateArgumentList::CreateCopy(SemaRef.Context,
2211 /*InsertPos=*/nullptr);
2212 } else if (!isFriend) {
2213 // Record that this is an instantiation of a member function.
2214 Method->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
2217 // If we are instantiating a member function defined
2218 // out-of-line, the instantiation will have the same lexical
2219 // context (which will be a namespace scope) as the template.
2221 if (NumTempParamLists)
2222 Method->setTemplateParameterListsInfo(
2224 llvm::makeArrayRef(TempParamLists.data(), NumTempParamLists));
2226 Method->setLexicalDeclContext(Owner);
2227 Method->setObjectOfFriendDecl();
2228 } else if (D->isOutOfLine())
2229 Method->setLexicalDeclContext(D->getLexicalDeclContext());
2231 // Attach the parameters
2232 for (unsigned P = 0; P < Params.size(); ++P)
2233 Params[P]->setOwningFunction(Method);
2234 Method->setParams(Params);
2236 if (InitMethodInstantiation(Method, D))
2237 Method->setInvalidDecl();
2239 LookupResult Previous(SemaRef, NameInfo, Sema::LookupOrdinaryName,
2240 Sema::ForExternalRedeclaration);
2242 bool IsExplicitSpecialization = false;
2244 // If the name of this function was written as a template-id, instantiate
2245 // the explicit template arguments.
2246 if (DependentFunctionTemplateSpecializationInfo *Info
2247 = D->getDependentSpecializationInfo()) {
2248 assert(isFriend && "non-friend has dependent specialization info?");
2250 // Instantiate the explicit template arguments.
2251 TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(),
2252 Info->getRAngleLoc());
2253 if (SemaRef.Subst(Info->getTemplateArgs(), Info->getNumTemplateArgs(),
2254 ExplicitArgs, TemplateArgs))
2257 // Map the candidate templates to their instantiations.
2258 for (unsigned I = 0, E = Info->getNumTemplates(); I != E; ++I) {
2259 Decl *Temp = SemaRef.FindInstantiatedDecl(D->getLocation(),
2260 Info->getTemplate(I),
2262 if (!Temp) return nullptr;
2264 Previous.addDecl(cast<FunctionTemplateDecl>(Temp));
2267 if (SemaRef.CheckFunctionTemplateSpecialization(Method,
2270 Method->setInvalidDecl();
2272 IsExplicitSpecialization = true;
2273 } else if (const ASTTemplateArgumentListInfo *Info =
2274 ClassScopeSpecializationArgs.getValueOr(
2275 D->getTemplateSpecializationArgsAsWritten())) {
2276 SemaRef.LookupQualifiedName(Previous, DC);
2278 TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(),
2279 Info->getRAngleLoc());
2280 if (SemaRef.Subst(Info->getTemplateArgs(), Info->getNumTemplateArgs(),
2281 ExplicitArgs, TemplateArgs))
2284 if (SemaRef.CheckFunctionTemplateSpecialization(Method,
2287 Method->setInvalidDecl();
2289 IsExplicitSpecialization = true;
2290 } else if (ClassScopeSpecializationArgs) {
2291 // Class-scope explicit specialization written without explicit template
2293 SemaRef.LookupQualifiedName(Previous, DC);
2294 if (SemaRef.CheckFunctionTemplateSpecialization(Method, nullptr, Previous))
2295 Method->setInvalidDecl();
2297 IsExplicitSpecialization = true;
2298 } else if (!FunctionTemplate || TemplateParams || isFriend) {
2299 SemaRef.LookupQualifiedName(Previous, Record);
2301 // In C++, the previous declaration we find might be a tag type
2302 // (class or enum). In this case, the new declaration will hide the
2303 // tag type. Note that this does does not apply if we're declaring a
2304 // typedef (C++ [dcl.typedef]p4).
2305 if (Previous.isSingleTagDecl())
2309 SemaRef.CheckFunctionDeclaration(nullptr, Method, Previous,
2310 IsExplicitSpecialization);
2313 SemaRef.CheckPureMethod(Method, SourceRange());
2315 // Propagate access. For a non-friend declaration, the access is
2316 // whatever we're propagating from. For a friend, it should be the
2317 // previous declaration we just found.
2318 if (isFriend && Method->getPreviousDecl())
2319 Method->setAccess(Method->getPreviousDecl()->getAccess());
2321 Method->setAccess(D->getAccess());
2322 if (FunctionTemplate)
2323 FunctionTemplate->setAccess(Method->getAccess());
2325 SemaRef.CheckOverrideControl(Method);
2327 // If a function is defined as defaulted or deleted, mark it as such now.
2328 if (D->isExplicitlyDefaulted())
2329 SemaRef.SetDeclDefaulted(Method, Method->getLocation());
2330 if (D->isDeletedAsWritten())
2331 SemaRef.SetDeclDeleted(Method, Method->getLocation());
2333 // If this is an explicit specialization, mark the implicitly-instantiated
2334 // template specialization as being an explicit specialization too.
2335 // FIXME: Is this necessary?
2336 if (IsExplicitSpecialization && !isFriend)
2337 SemaRef.CompleteMemberSpecialization(Method, Previous);
2339 // If there's a function template, let our caller handle it.
2340 if (FunctionTemplate) {
2343 // Don't hide a (potentially) valid declaration with an invalid one.
2344 } else if (Method->isInvalidDecl() && !Previous.empty()) {
2347 // Otherwise, check access to friends and make them visible.
2348 } else if (isFriend) {
2349 // We only need to re-check access for methods which we didn't
2350 // manage to match during parsing.
2351 if (!D->getPreviousDecl())
2352 SemaRef.CheckFriendAccess(Method);
2354 Record->makeDeclVisibleInContext(Method);
2356 // Otherwise, add the declaration. We don't need to do this for
2357 // class-scope specializations because we'll have matched them with
2358 // the appropriate template.
2360 Owner->addDecl(Method);
2363 // PR17480: Honor the used attribute to instantiate member function
2365 if (Method->hasAttr<UsedAttr>()) {
2366 if (const auto *A = dyn_cast<CXXRecordDecl>(Owner)) {
2368 if (const MemberSpecializationInfo *MSInfo =
2369 A->getMemberSpecializationInfo())
2370 Loc = MSInfo->getPointOfInstantiation();
2371 else if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(A))
2372 Loc = Spec->getPointOfInstantiation();
2373 SemaRef.MarkFunctionReferenced(Loc, Method);
2380 Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
2381 return VisitCXXMethodDecl(D);
2384 Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
2385 return VisitCXXMethodDecl(D);
2388 Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
2389 return VisitCXXMethodDecl(D);
2392 Decl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
2393 return SemaRef.SubstParmVarDecl(D, TemplateArgs, /*indexAdjustment*/ 0, None,
2394 /*ExpectParameterPack=*/ false);
2397 Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl(
2398 TemplateTypeParmDecl *D) {
2399 // TODO: don't always clone when decls are refcounted.
2400 assert(D->getTypeForDecl()->isTemplateTypeParmType());
2402 TemplateTypeParmDecl *Inst = TemplateTypeParmDecl::Create(
2403 SemaRef.Context, Owner, D->getBeginLoc(), D->getLocation(),
2404 D->getDepth() - TemplateArgs.getNumSubstitutedLevels(), D->getIndex(),
2405 D->getIdentifier(), D->wasDeclaredWithTypename(), D->isParameterPack());
2406 Inst->setAccess(AS_public);
2407 Inst->setImplicit(D->isImplicit());
2409 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited()) {
2410 TypeSourceInfo *InstantiatedDefaultArg =
2411 SemaRef.SubstType(D->getDefaultArgumentInfo(), TemplateArgs,
2412 D->getDefaultArgumentLoc(), D->getDeclName());
2413 if (InstantiatedDefaultArg)
2414 Inst->setDefaultArgument(InstantiatedDefaultArg);
2417 // Introduce this template parameter's instantiation into the instantiation
2419 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst);
2424 Decl *TemplateDeclInstantiator::VisitNonTypeTemplateParmDecl(
2425 NonTypeTemplateParmDecl *D) {
2426 // Substitute into the type of the non-type template parameter.
2427 TypeLoc TL = D->getTypeSourceInfo()->getTypeLoc();
2428 SmallVector<TypeSourceInfo *, 4> ExpandedParameterPackTypesAsWritten;
2429 SmallVector<QualType, 4> ExpandedParameterPackTypes;
2430 bool IsExpandedParameterPack = false;
2433 bool Invalid = false;
2435 if (D->isExpandedParameterPack()) {
2436 // The non-type template parameter pack is an already-expanded pack
2437 // expansion of types. Substitute into each of the expanded types.
2438 ExpandedParameterPackTypes.reserve(D->getNumExpansionTypes());
2439 ExpandedParameterPackTypesAsWritten.reserve(D->getNumExpansionTypes());
2440 for (unsigned I = 0, N = D->getNumExpansionTypes(); I != N; ++I) {
2441 TypeSourceInfo *NewDI =
2442 SemaRef.SubstType(D->getExpansionTypeSourceInfo(I), TemplateArgs,
2443 D->getLocation(), D->getDeclName());
2448 SemaRef.CheckNonTypeTemplateParameterType(NewDI, D->getLocation());
2452 ExpandedParameterPackTypesAsWritten.push_back(NewDI);
2453 ExpandedParameterPackTypes.push_back(NewT);
2456 IsExpandedParameterPack = true;
2457 DI = D->getTypeSourceInfo();
2459 } else if (D->isPackExpansion()) {
2460 // The non-type template parameter pack's type is a pack expansion of types.
2461 // Determine whether we need to expand this parameter pack into separate
2463 PackExpansionTypeLoc Expansion = TL.castAs<PackExpansionTypeLoc>();
2464 TypeLoc Pattern = Expansion.getPatternLoc();
2465 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
2466 SemaRef.collectUnexpandedParameterPacks(Pattern, Unexpanded);
2468 // Determine whether the set of unexpanded parameter packs can and should
2471 bool RetainExpansion = false;
2472 Optional<unsigned> OrigNumExpansions
2473 = Expansion.getTypePtr()->getNumExpansions();
2474 Optional<unsigned> NumExpansions = OrigNumExpansions;
2475 if (SemaRef.CheckParameterPacksForExpansion(Expansion.getEllipsisLoc(),
2476 Pattern.getSourceRange(),
2479 Expand, RetainExpansion,
2484 for (unsigned I = 0; I != *NumExpansions; ++I) {
2485 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
2486 TypeSourceInfo *NewDI = SemaRef.SubstType(Pattern, TemplateArgs,
2493 SemaRef.CheckNonTypeTemplateParameterType(NewDI, D->getLocation());
2497 ExpandedParameterPackTypesAsWritten.push_back(NewDI);
2498 ExpandedParameterPackTypes.push_back(NewT);
2501 // Note that we have an expanded parameter pack. The "type" of this
2502 // expanded parameter pack is the original expansion type, but callers
2503 // will end up using the expanded parameter pack types for type-checking.
2504 IsExpandedParameterPack = true;
2505 DI = D->getTypeSourceInfo();
2508 // We cannot fully expand the pack expansion now, so substitute into the
2509 // pattern and create a new pack expansion type.
2510 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
2511 TypeSourceInfo *NewPattern = SemaRef.SubstType(Pattern, TemplateArgs,
2517 SemaRef.CheckNonTypeTemplateParameterType(NewPattern, D->getLocation());
2518 DI = SemaRef.CheckPackExpansion(NewPattern, Expansion.getEllipsisLoc(),
2526 // Simple case: substitution into a parameter that is not a parameter pack.
2527 DI = SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs,
2528 D->getLocation(), D->getDeclName());
2532 // Check that this type is acceptable for a non-type template parameter.
2533 T = SemaRef.CheckNonTypeTemplateParameterType(DI, D->getLocation());
2535 T = SemaRef.Context.IntTy;
2540 NonTypeTemplateParmDecl *Param;
2541 if (IsExpandedParameterPack)
2542 Param = NonTypeTemplateParmDecl::Create(
2543 SemaRef.Context, Owner, D->getInnerLocStart(), D->getLocation(),
2544 D->getDepth() - TemplateArgs.getNumSubstitutedLevels(),
2545 D->getPosition(), D->getIdentifier(), T, DI, ExpandedParameterPackTypes,
2546 ExpandedParameterPackTypesAsWritten);
2548 Param = NonTypeTemplateParmDecl::Create(
2549 SemaRef.Context, Owner, D->getInnerLocStart(), D->getLocation(),
2550 D->getDepth() - TemplateArgs.getNumSubstitutedLevels(),
2551 D->getPosition(), D->getIdentifier(), T, D->isParameterPack(), DI);
2553 Param->setAccess(AS_public);
2554 Param->setImplicit(D->isImplicit());
2556 Param->setInvalidDecl();
2558 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited()) {
2559 EnterExpressionEvaluationContext ConstantEvaluated(
2560 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
2561 ExprResult Value = SemaRef.SubstExpr(D->getDefaultArgument(), TemplateArgs);
2562 if (!Value.isInvalid())
2563 Param->setDefaultArgument(Value.get());
2566 // Introduce this template parameter's instantiation into the instantiation
2568 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
2572 static void collectUnexpandedParameterPacks(
2574 TemplateParameterList *Params,
2575 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
2576 for (const auto &P : *Params) {
2577 if (P->isTemplateParameterPack())
2579 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P))
2580 S.collectUnexpandedParameterPacks(NTTP->getTypeSourceInfo()->getTypeLoc(),
2582 if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(P))
2583 collectUnexpandedParameterPacks(S, TTP->getTemplateParameters(),
2589 TemplateDeclInstantiator::VisitTemplateTemplateParmDecl(
2590 TemplateTemplateParmDecl *D) {
2591 // Instantiate the template parameter list of the template template parameter.
2592 TemplateParameterList *TempParams = D->getTemplateParameters();
2593 TemplateParameterList *InstParams;
2594 SmallVector<TemplateParameterList*, 8> ExpandedParams;
2596 bool IsExpandedParameterPack = false;
2598 if (D->isExpandedParameterPack()) {
2599 // The template template parameter pack is an already-expanded pack
2600 // expansion of template parameters. Substitute into each of the expanded
2602 ExpandedParams.reserve(D->getNumExpansionTemplateParameters());
2603 for (unsigned I = 0, N = D->getNumExpansionTemplateParameters();
2605 LocalInstantiationScope Scope(SemaRef);
2606 TemplateParameterList *Expansion =
2607 SubstTemplateParams(D->getExpansionTemplateParameters(I));
2610 ExpandedParams.push_back(Expansion);
2613 IsExpandedParameterPack = true;
2614 InstParams = TempParams;
2615 } else if (D->isPackExpansion()) {
2616 // The template template parameter pack expands to a pack of template
2617 // template parameters. Determine whether we need to expand this parameter
2618 // pack into separate parameters.
2619 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
2620 collectUnexpandedParameterPacks(SemaRef, D->getTemplateParameters(),
2623 // Determine whether the set of unexpanded parameter packs can and should
2626 bool RetainExpansion = false;
2627 Optional<unsigned> NumExpansions;
2628 if (SemaRef.CheckParameterPacksForExpansion(D->getLocation(),
2629 TempParams->getSourceRange(),
2632 Expand, RetainExpansion,
2637 for (unsigned I = 0; I != *NumExpansions; ++I) {
2638 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
2639 LocalInstantiationScope Scope(SemaRef);
2640 TemplateParameterList *Expansion = SubstTemplateParams(TempParams);
2643 ExpandedParams.push_back(Expansion);
2646 // Note that we have an expanded parameter pack. The "type" of this
2647 // expanded parameter pack is the original expansion type, but callers
2648 // will end up using the expanded parameter pack types for type-checking.
2649 IsExpandedParameterPack = true;
2650 InstParams = TempParams;
2652 // We cannot fully expand the pack expansion now, so just substitute
2653 // into the pattern.
2654 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
2656 LocalInstantiationScope Scope(SemaRef);
2657 InstParams = SubstTemplateParams(TempParams);
2662 // Perform the actual substitution of template parameters within a new,
2663 // local instantiation scope.
2664 LocalInstantiationScope Scope(SemaRef);
2665 InstParams = SubstTemplateParams(TempParams);
2670 // Build the template template parameter.
2671 TemplateTemplateParmDecl *Param;
2672 if (IsExpandedParameterPack)
2673 Param = TemplateTemplateParmDecl::Create(
2674 SemaRef.Context, Owner, D->getLocation(),
2675 D->getDepth() - TemplateArgs.getNumSubstitutedLevels(),
2676 D->getPosition(), D->getIdentifier(), InstParams, ExpandedParams);
2678 Param = TemplateTemplateParmDecl::Create(
2679 SemaRef.Context, Owner, D->getLocation(),
2680 D->getDepth() - TemplateArgs.getNumSubstitutedLevels(),
2681 D->getPosition(), D->isParameterPack(), D->getIdentifier(), InstParams);
2682 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited()) {
2683 NestedNameSpecifierLoc QualifierLoc =
2684 D->getDefaultArgument().getTemplateQualifierLoc();
2686 SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgs);
2687 TemplateName TName = SemaRef.SubstTemplateName(
2688 QualifierLoc, D->getDefaultArgument().getArgument().getAsTemplate(),
2689 D->getDefaultArgument().getTemplateNameLoc(), TemplateArgs);
2690 if (!TName.isNull())
2691 Param->setDefaultArgument(
2693 TemplateArgumentLoc(TemplateArgument(TName),
2694 D->getDefaultArgument().getTemplateQualifierLoc(),
2695 D->getDefaultArgument().getTemplateNameLoc()));
2697 Param->setAccess(AS_public);
2698 Param->setImplicit(D->isImplicit());
2700 // Introduce this template parameter's instantiation into the instantiation
2702 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
2707 Decl *TemplateDeclInstantiator::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
2708 // Using directives are never dependent (and never contain any types or
2709 // expressions), so they require no explicit instantiation work.
2711 UsingDirectiveDecl *Inst
2712 = UsingDirectiveDecl::Create(SemaRef.Context, Owner, D->getLocation(),
2713 D->getNamespaceKeyLocation(),
2714 D->getQualifierLoc(),
2715 D->getIdentLocation(),
2716 D->getNominatedNamespace(),
2717 D->getCommonAncestor());
2719 // Add the using directive to its declaration context
2720 // only if this is not a function or method.
2721 if (!Owner->isFunctionOrMethod())
2722 Owner->addDecl(Inst);
2727 Decl *TemplateDeclInstantiator::VisitUsingDecl(UsingDecl *D) {
2729 // The nested name specifier may be dependent, for example
2730 // template <typename T> struct t {
2731 // struct s1 { T f1(); };
2732 // struct s2 : s1 { using s1::f1; };
2734 // template struct t<int>;
2735 // Here, in using s1::f1, s1 refers to t<T>::s1;
2736 // we need to substitute for t<int>::s1.
2737 NestedNameSpecifierLoc QualifierLoc
2738 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
2743 // For an inheriting constructor declaration, the name of the using
2744 // declaration is the name of a constructor in this class, not in the
2746 DeclarationNameInfo NameInfo = D->getNameInfo();
2747 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName)
2748 if (auto *RD = dyn_cast<CXXRecordDecl>(SemaRef.CurContext))
2749 NameInfo.setName(SemaRef.Context.DeclarationNames.getCXXConstructorName(
2750 SemaRef.Context.getCanonicalType(SemaRef.Context.getRecordType(RD))));
2752 // We only need to do redeclaration lookups if we're in a class
2753 // scope (in fact, it's not really even possible in non-class
2755 bool CheckRedeclaration = Owner->isRecord();
2757 LookupResult Prev(SemaRef, NameInfo, Sema::LookupUsingDeclName,
2758 Sema::ForVisibleRedeclaration);
2760 UsingDecl *NewUD = UsingDecl::Create(SemaRef.Context, Owner,
2767 SS.Adopt(QualifierLoc);
2768 if (CheckRedeclaration) {
2769 Prev.setHideTags(false);
2770 SemaRef.LookupQualifiedName(Prev, Owner);
2772 // Check for invalid redeclarations.
2773 if (SemaRef.CheckUsingDeclRedeclaration(D->getUsingLoc(),
2774 D->hasTypename(), SS,
2775 D->getLocation(), Prev))
2776 NewUD->setInvalidDecl();
2780 if (!NewUD->isInvalidDecl() &&
2781 SemaRef.CheckUsingDeclQualifier(D->getUsingLoc(), D->hasTypename(),
2782 SS, NameInfo, D->getLocation()))
2783 NewUD->setInvalidDecl();
2785 SemaRef.Context.setInstantiatedFromUsingDecl(NewUD, D);
2786 NewUD->setAccess(D->getAccess());
2787 Owner->addDecl(NewUD);
2789 // Don't process the shadow decls for an invalid decl.
2790 if (NewUD->isInvalidDecl())
2793 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName)
2794 SemaRef.CheckInheritingConstructorUsingDecl(NewUD);
2796 bool isFunctionScope = Owner->isFunctionOrMethod();
2798 // Process the shadow decls.
2799 for (auto *Shadow : D->shadows()) {
2800 // FIXME: UsingShadowDecl doesn't preserve its immediate target, so
2801 // reconstruct it in the case where it matters.
2802 NamedDecl *OldTarget = Shadow->getTargetDecl();
2803 if (auto *CUSD = dyn_cast<ConstructorUsingShadowDecl>(Shadow))
2804 if (auto *BaseShadow = CUSD->getNominatedBaseClassShadowDecl())
2805 OldTarget = BaseShadow;
2807 NamedDecl *InstTarget =
2808 cast_or_null<NamedDecl>(SemaRef.FindInstantiatedDecl(
2809 Shadow->getLocation(), OldTarget, TemplateArgs));
2813 UsingShadowDecl *PrevDecl = nullptr;
2814 if (CheckRedeclaration) {
2815 if (SemaRef.CheckUsingShadowDecl(NewUD, InstTarget, Prev, PrevDecl))
2817 } else if (UsingShadowDecl *OldPrev =
2818 getPreviousDeclForInstantiation(Shadow)) {
2819 PrevDecl = cast_or_null<UsingShadowDecl>(SemaRef.FindInstantiatedDecl(
2820 Shadow->getLocation(), OldPrev, TemplateArgs));
2823 UsingShadowDecl *InstShadow =
2824 SemaRef.BuildUsingShadowDecl(/*Scope*/nullptr, NewUD, InstTarget,
2826 SemaRef.Context.setInstantiatedFromUsingShadowDecl(InstShadow, Shadow);
2828 if (isFunctionScope)
2829 SemaRef.CurrentInstantiationScope->InstantiatedLocal(Shadow, InstShadow);
2835 Decl *TemplateDeclInstantiator::VisitUsingShadowDecl(UsingShadowDecl *D) {
2836 // Ignore these; we handle them in bulk when processing the UsingDecl.
2840 Decl *TemplateDeclInstantiator::VisitConstructorUsingShadowDecl(
2841 ConstructorUsingShadowDecl *D) {
2842 // Ignore these; we handle them in bulk when processing the UsingDecl.
2846 template <typename T>
2847 Decl *TemplateDeclInstantiator::instantiateUnresolvedUsingDecl(
2848 T *D, bool InstantiatingPackElement) {
2849 // If this is a pack expansion, expand it now.
2850 if (D->isPackExpansion() && !InstantiatingPackElement) {
2851 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
2852 SemaRef.collectUnexpandedParameterPacks(D->getQualifierLoc(), Unexpanded);
2853 SemaRef.collectUnexpandedParameterPacks(D->getNameInfo(), Unexpanded);
2855 // Determine whether the set of unexpanded parameter packs can and should
2858 bool RetainExpansion = false;
2859 Optional<unsigned> NumExpansions;
2860 if (SemaRef.CheckParameterPacksForExpansion(
2861 D->getEllipsisLoc(), D->getSourceRange(), Unexpanded, TemplateArgs,
2862 Expand, RetainExpansion, NumExpansions))
2865 // This declaration cannot appear within a function template signature,
2866 // so we can't have a partial argument list for a parameter pack.
2867 assert(!RetainExpansion &&
2868 "should never need to retain an expansion for UsingPackDecl");
2871 // We cannot fully expand the pack expansion now, so substitute into the
2872 // pattern and create a new pack expansion.
2873 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
2874 return instantiateUnresolvedUsingDecl(D, true);
2877 // Within a function, we don't have any normal way to check for conflicts
2878 // between shadow declarations from different using declarations in the
2879 // same pack expansion, but this is always ill-formed because all expansions
2880 // must produce (conflicting) enumerators.
2882 // Sadly we can't just reject this in the template definition because it
2883 // could be valid if the pack is empty or has exactly one expansion.
2884 if (D->getDeclContext()->isFunctionOrMethod() && *NumExpansions > 1) {
2885 SemaRef.Diag(D->getEllipsisLoc(),
2886 diag::err_using_decl_redeclaration_expansion);
2890 // Instantiate the slices of this pack and build a UsingPackDecl.
2891 SmallVector<NamedDecl*, 8> Expansions;
2892 for (unsigned I = 0; I != *NumExpansions; ++I) {
2893 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
2894 Decl *Slice = instantiateUnresolvedUsingDecl(D, true);
2897 // Note that we can still get unresolved using declarations here, if we
2898 // had arguments for all packs but the pattern also contained other
2899 // template arguments (this only happens during partial substitution, eg
2900 // into the body of a generic lambda in a function template).
2901 Expansions.push_back(cast<NamedDecl>(Slice));
2904 auto *NewD = SemaRef.BuildUsingPackDecl(D, Expansions);
2905 if (isDeclWithinFunction(D))
2906 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewD);
2910 UnresolvedUsingTypenameDecl *TD = dyn_cast<UnresolvedUsingTypenameDecl>(D);
2911 SourceLocation TypenameLoc = TD ? TD->getTypenameLoc() : SourceLocation();
2913 NestedNameSpecifierLoc QualifierLoc
2914 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
2920 SS.Adopt(QualifierLoc);
2922 DeclarationNameInfo NameInfo
2923 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
2925 // Produce a pack expansion only if we're not instantiating a particular
2926 // slice of a pack expansion.
2927 bool InstantiatingSlice = D->getEllipsisLoc().isValid() &&
2928 SemaRef.ArgumentPackSubstitutionIndex != -1;
2929 SourceLocation EllipsisLoc =
2930 InstantiatingSlice ? SourceLocation() : D->getEllipsisLoc();
2932 NamedDecl *UD = SemaRef.BuildUsingDeclaration(
2933 /*Scope*/ nullptr, D->getAccess(), D->getUsingLoc(),
2934 /*HasTypename*/ TD, TypenameLoc, SS, NameInfo, EllipsisLoc,
2935 ParsedAttributesView(),
2936 /*IsInstantiation*/ true);
2938 SemaRef.Context.setInstantiatedFromUsingDecl(UD, D);
2943 Decl *TemplateDeclInstantiator::VisitUnresolvedUsingTypenameDecl(
2944 UnresolvedUsingTypenameDecl *D) {
2945 return instantiateUnresolvedUsingDecl(D);
2948 Decl *TemplateDeclInstantiator::VisitUnresolvedUsingValueDecl(
2949 UnresolvedUsingValueDecl *D) {
2950 return instantiateUnresolvedUsingDecl(D);
2953 Decl *TemplateDeclInstantiator::VisitUsingPackDecl(UsingPackDecl *D) {
2954 SmallVector<NamedDecl*, 8> Expansions;
2955 for (auto *UD : D->expansions()) {
2956 if (NamedDecl *NewUD =
2957 SemaRef.FindInstantiatedDecl(D->getLocation(), UD, TemplateArgs))
2958 Expansions.push_back(NewUD);
2963 auto *NewD = SemaRef.BuildUsingPackDecl(D, Expansions);
2964 if (isDeclWithinFunction(D))
2965 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewD);
2969 Decl *TemplateDeclInstantiator::VisitClassScopeFunctionSpecializationDecl(
2970 ClassScopeFunctionSpecializationDecl *Decl) {
2971 CXXMethodDecl *OldFD = Decl->getSpecialization();
2972 return cast_or_null<CXXMethodDecl>(
2973 VisitCXXMethodDecl(OldFD, nullptr, Decl->getTemplateArgsAsWritten()));
2976 Decl *TemplateDeclInstantiator::VisitOMPThreadPrivateDecl(
2977 OMPThreadPrivateDecl *D) {
2978 SmallVector<Expr *, 5> Vars;
2979 for (auto *I : D->varlists()) {
2980 Expr *Var = SemaRef.SubstExpr(I, TemplateArgs).get();
2981 assert(isa<DeclRefExpr>(Var) && "threadprivate arg is not a DeclRefExpr");
2982 Vars.push_back(Var);
2985 OMPThreadPrivateDecl *TD =
2986 SemaRef.CheckOMPThreadPrivateDecl(D->getLocation(), Vars);
2988 TD->setAccess(AS_public);
2994 Decl *TemplateDeclInstantiator::VisitOMPAllocateDecl(OMPAllocateDecl *D) {
2995 SmallVector<Expr *, 5> Vars;
2996 for (auto *I : D->varlists()) {
2997 Expr *Var = SemaRef.SubstExpr(I, TemplateArgs).get();
2998 assert(isa<DeclRefExpr>(Var) && "allocate arg is not a DeclRefExpr");
2999 Vars.push_back(Var);
3001 SmallVector<OMPClause *, 4> Clauses;
3002 // Copy map clauses from the original mapper.
3003 for (OMPClause *C : D->clauselists()) {
3004 auto *AC = cast<OMPAllocatorClause>(C);
3005 ExprResult NewE = SemaRef.SubstExpr(AC->getAllocator(), TemplateArgs);
3006 if (!NewE.isUsable())
3008 OMPClause *IC = SemaRef.ActOnOpenMPAllocatorClause(
3009 NewE.get(), AC->getBeginLoc(), AC->getLParenLoc(), AC->getEndLoc());
3010 Clauses.push_back(IC);
3013 Sema::DeclGroupPtrTy Res = SemaRef.ActOnOpenMPAllocateDirective(
3014 D->getLocation(), Vars, Clauses, Owner);
3015 if (Res.get().isNull())
3017 return Res.get().getSingleDecl();
3020 Decl *TemplateDeclInstantiator::VisitOMPRequiresDecl(OMPRequiresDecl *D) {
3022 "Requires directive cannot be instantiated within a dependent context");
3025 Decl *TemplateDeclInstantiator::VisitOMPDeclareReductionDecl(
3026 OMPDeclareReductionDecl *D) {
3027 // Instantiate type and check if it is allowed.
3028 const bool RequiresInstantiation =
3029 D->getType()->isDependentType() ||
3030 D->getType()->isInstantiationDependentType() ||
3031 D->getType()->containsUnexpandedParameterPack();
3032 QualType SubstReductionType;
3033 if (RequiresInstantiation) {
3034 SubstReductionType = SemaRef.ActOnOpenMPDeclareReductionType(
3036 ParsedType::make(SemaRef.SubstType(
3037 D->getType(), TemplateArgs, D->getLocation(), DeclarationName())));
3039 SubstReductionType = D->getType();
3041 if (SubstReductionType.isNull())
3043 bool IsCorrect = !SubstReductionType.isNull();
3044 // Create instantiated copy.
3045 std::pair<QualType, SourceLocation> ReductionTypes[] = {
3046 std::make_pair(SubstReductionType, D->getLocation())};
3047 auto *PrevDeclInScope = D->getPrevDeclInScope();
3048 if (PrevDeclInScope && !PrevDeclInScope->isInvalidDecl()) {
3049 PrevDeclInScope = cast<OMPDeclareReductionDecl>(
3050 SemaRef.CurrentInstantiationScope->findInstantiationOf(PrevDeclInScope)
3053 auto DRD = SemaRef.ActOnOpenMPDeclareReductionDirectiveStart(
3054 /*S=*/nullptr, Owner, D->getDeclName(), ReductionTypes, D->getAccess(),
3056 auto *NewDRD = cast<OMPDeclareReductionDecl>(DRD.get().getSingleDecl());
3057 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewDRD);
3058 if (!RequiresInstantiation) {
3059 if (Expr *Combiner = D->getCombiner()) {
3060 NewDRD->setCombinerData(D->getCombinerIn(), D->getCombinerOut());
3061 NewDRD->setCombiner(Combiner);
3062 if (Expr *Init = D->getInitializer()) {
3063 NewDRD->setInitializerData(D->getInitOrig(), D->getInitPriv());
3064 NewDRD->setInitializer(Init, D->getInitializerKind());
3067 (void)SemaRef.ActOnOpenMPDeclareReductionDirectiveEnd(
3068 /*S=*/nullptr, DRD, IsCorrect && !D->isInvalidDecl());
3071 Expr *SubstCombiner = nullptr;
3072 Expr *SubstInitializer = nullptr;
3073 // Combiners instantiation sequence.
3074 if (D->getCombiner()) {
3075 SemaRef.ActOnOpenMPDeclareReductionCombinerStart(
3076 /*S=*/nullptr, NewDRD);
3077 SemaRef.CurrentInstantiationScope->InstantiatedLocal(
3078 cast<DeclRefExpr>(D->getCombinerIn())->getDecl(),
3079 cast<DeclRefExpr>(NewDRD->getCombinerIn())->getDecl());
3080 SemaRef.CurrentInstantiationScope->InstantiatedLocal(
3081 cast<DeclRefExpr>(D->getCombinerOut())->getDecl(),
3082 cast<DeclRefExpr>(NewDRD->getCombinerOut())->getDecl());
3083 auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(Owner);
3084 Sema::CXXThisScopeRAII ThisScope(SemaRef, ThisContext, Qualifiers(),
3086 SubstCombiner = SemaRef.SubstExpr(D->getCombiner(), TemplateArgs).get();
3087 SemaRef.ActOnOpenMPDeclareReductionCombinerEnd(NewDRD, SubstCombiner);
3088 // Initializers instantiation sequence.
3089 if (D->getInitializer()) {
3090 VarDecl *OmpPrivParm =
3091 SemaRef.ActOnOpenMPDeclareReductionInitializerStart(
3092 /*S=*/nullptr, NewDRD);
3093 SemaRef.CurrentInstantiationScope->InstantiatedLocal(
3094 cast<DeclRefExpr>(D->getInitOrig())->getDecl(),
3095 cast<DeclRefExpr>(NewDRD->getInitOrig())->getDecl());
3096 SemaRef.CurrentInstantiationScope->InstantiatedLocal(
3097 cast<DeclRefExpr>(D->getInitPriv())->getDecl(),
3098 cast<DeclRefExpr>(NewDRD->getInitPriv())->getDecl());
3099 if (D->getInitializerKind() == OMPDeclareReductionDecl::CallInit) {
3101 SemaRef.SubstExpr(D->getInitializer(), TemplateArgs).get();
3103 IsCorrect = IsCorrect && OmpPrivParm->hasInit();
3105 SemaRef.ActOnOpenMPDeclareReductionInitializerEnd(
3106 NewDRD, SubstInitializer, OmpPrivParm);
3109 IsCorrect && SubstCombiner &&
3110 (!D->getInitializer() ||
3111 (D->getInitializerKind() == OMPDeclareReductionDecl::CallInit &&
3112 SubstInitializer) ||
3113 (D->getInitializerKind() != OMPDeclareReductionDecl::CallInit &&
3114 !SubstInitializer && !SubstInitializer));
3119 (void)SemaRef.ActOnOpenMPDeclareReductionDirectiveEnd(/*S=*/nullptr, DRD,
3126 TemplateDeclInstantiator::VisitOMPDeclareMapperDecl(OMPDeclareMapperDecl *D) {
3127 // Instantiate type and check if it is allowed.
3128 const bool RequiresInstantiation =
3129 D->getType()->isDependentType() ||
3130 D->getType()->isInstantiationDependentType() ||
3131 D->getType()->containsUnexpandedParameterPack();
3132 QualType SubstMapperTy;
3133 DeclarationName VN = D->getVarName();
3134 if (RequiresInstantiation) {
3135 SubstMapperTy = SemaRef.ActOnOpenMPDeclareMapperType(
3137 ParsedType::make(SemaRef.SubstType(D->getType(), TemplateArgs,
3138 D->getLocation(), VN)));
3140 SubstMapperTy = D->getType();
3142 if (SubstMapperTy.isNull())
3144 // Create an instantiated copy of mapper.
3145 auto *PrevDeclInScope = D->getPrevDeclInScope();
3146 if (PrevDeclInScope && !PrevDeclInScope->isInvalidDecl()) {
3147 PrevDeclInScope = cast<OMPDeclareMapperDecl>(
3148 SemaRef.CurrentInstantiationScope->findInstantiationOf(PrevDeclInScope)
3151 OMPDeclareMapperDecl *NewDMD = SemaRef.ActOnOpenMPDeclareMapperDirectiveStart(
3152 /*S=*/nullptr, Owner, D->getDeclName(), SubstMapperTy, D->getLocation(),
3153 VN, D->getAccess(), PrevDeclInScope);
3154 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewDMD);
3155 SmallVector<OMPClause *, 6> Clauses;
3156 bool IsCorrect = true;
3157 if (!RequiresInstantiation) {
3158 // Copy the mapper variable.
3159 NewDMD->setMapperVarRef(D->getMapperVarRef());
3160 // Copy map clauses from the original mapper.
3161 for (OMPClause *C : D->clauselists())
3162 Clauses.push_back(C);
3164 // Instantiate the mapper variable.
3165 DeclarationNameInfo DirName;
3166 SemaRef.StartOpenMPDSABlock(OMPD_declare_mapper, DirName, /*S=*/nullptr,
3167 (*D->clauselist_begin())->getBeginLoc());
3168 SemaRef.ActOnOpenMPDeclareMapperDirectiveVarDecl(
3169 NewDMD, /*S=*/nullptr, SubstMapperTy, D->getLocation(), VN);
3170 SemaRef.CurrentInstantiationScope->InstantiatedLocal(
3171 cast<DeclRefExpr>(D->getMapperVarRef())->getDecl(),
3172 cast<DeclRefExpr>(NewDMD->getMapperVarRef())->getDecl());
3173 auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(Owner);
3174 Sema::CXXThisScopeRAII ThisScope(SemaRef, ThisContext, Qualifiers(),
3176 // Instantiate map clauses.
3177 for (OMPClause *C : D->clauselists()) {
3178 auto *OldC = cast<OMPMapClause>(C);
3179 SmallVector<Expr *, 4> NewVars;
3180 for (Expr *OE : OldC->varlists()) {
3181 Expr *NE = SemaRef.SubstExpr(OE, TemplateArgs).get();
3186 NewVars.push_back(NE);
3190 NestedNameSpecifierLoc NewQualifierLoc =
3191 SemaRef.SubstNestedNameSpecifierLoc(OldC->getMapperQualifierLoc(),
3194 SS.Adopt(NewQualifierLoc);
3195 DeclarationNameInfo NewNameInfo = SemaRef.SubstDeclarationNameInfo(
3196 OldC->getMapperIdInfo(), TemplateArgs);
3197 OMPVarListLocTy Locs(OldC->getBeginLoc(), OldC->getLParenLoc(),
3199 OMPClause *NewC = SemaRef.ActOnOpenMPMapClause(
3200 OldC->getMapTypeModifiers(), OldC->getMapTypeModifiersLoc(), SS,
3201 NewNameInfo, OldC->getMapType(), OldC->isImplicitMapType(),
3202 OldC->getMapLoc(), OldC->getColonLoc(), NewVars, Locs);
3203 Clauses.push_back(NewC);
3205 SemaRef.EndOpenMPDSABlock(nullptr);
3207 (void)SemaRef.ActOnOpenMPDeclareMapperDirectiveEnd(NewDMD, /*S=*/nullptr,
3214 Decl *TemplateDeclInstantiator::VisitOMPCapturedExprDecl(
3215 OMPCapturedExprDecl * /*D*/) {
3216 llvm_unreachable("Should not be met in templates");
3219 Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D) {
3220 return VisitFunctionDecl(D, nullptr);
3224 TemplateDeclInstantiator::VisitCXXDeductionGuideDecl(CXXDeductionGuideDecl *D) {
3225 Decl *Inst = VisitFunctionDecl(D, nullptr);
3226 if (Inst && !D->getDescribedFunctionTemplate())
3227 Owner->addDecl(Inst);
3231 Decl *TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D) {
3232 return VisitCXXMethodDecl(D, nullptr);
3235 Decl *TemplateDeclInstantiator::VisitRecordDecl(RecordDecl *D) {
3236 llvm_unreachable("There are only CXXRecordDecls in C++");
3240 TemplateDeclInstantiator::VisitClassTemplateSpecializationDecl(
3241 ClassTemplateSpecializationDecl *D) {
3242 // As a MS extension, we permit class-scope explicit specialization
3243 // of member class templates.
3244 ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
3245 assert(ClassTemplate->getDeclContext()->isRecord() &&
3246 D->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
3247 "can only instantiate an explicit specialization "
3248 "for a member class template");
3250 // Lookup the already-instantiated declaration in the instantiation
3251 // of the class template.
3252 ClassTemplateDecl *InstClassTemplate =
3253 cast_or_null<ClassTemplateDecl>(SemaRef.FindInstantiatedDecl(
3254 D->getLocation(), ClassTemplate, TemplateArgs));
3255 if (!InstClassTemplate)
3258 // Substitute into the template arguments of the class template explicit
3260 TemplateSpecializationTypeLoc Loc = D->getTypeAsWritten()->getTypeLoc().
3261 castAs<TemplateSpecializationTypeLoc>();
3262 TemplateArgumentListInfo InstTemplateArgs(Loc.getLAngleLoc(),
3263 Loc.getRAngleLoc());
3264 SmallVector<TemplateArgumentLoc, 4> ArgLocs;
3265 for (unsigned I = 0; I != Loc.getNumArgs(); ++I)
3266 ArgLocs.push_back(Loc.getArgLoc(I));
3267 if (SemaRef.Subst(ArgLocs.data(), ArgLocs.size(),
3268 InstTemplateArgs, TemplateArgs))
3271 // Check that the template argument list is well-formed for this
3273 SmallVector<TemplateArgument, 4> Converted;
3274 if (SemaRef.CheckTemplateArgumentList(InstClassTemplate,
3281 // Figure out where to insert this class template explicit specialization
3282 // in the member template's set of class template explicit specializations.
3283 void *InsertPos = nullptr;
3284 ClassTemplateSpecializationDecl *PrevDecl =
3285 InstClassTemplate->findSpecialization(Converted, InsertPos);
3287 // Check whether we've already seen a conflicting instantiation of this
3288 // declaration (for instance, if there was a prior implicit instantiation).
3291 SemaRef.CheckSpecializationInstantiationRedecl(D->getLocation(),
3292 D->getSpecializationKind(),
3294 PrevDecl->getSpecializationKind(),
3295 PrevDecl->getPointOfInstantiation(),
3299 // If PrevDecl was a definition and D is also a definition, diagnose.
3300 // This happens in cases like:
3302 // template<typename T, typename U>
3304 // template<typename X> struct Inner;
3305 // template<> struct Inner<T> {};
3306 // template<> struct Inner<U> {};
3309 // Outer<int, int> outer; // error: the explicit specializations of Inner
3310 // // have the same signature.
3311 if (PrevDecl && PrevDecl->getDefinition() &&
3312 D->isThisDeclarationADefinition()) {
3313 SemaRef.Diag(D->getLocation(), diag::err_redefinition) << PrevDecl;
3314 SemaRef.Diag(PrevDecl->getDefinition()->getLocation(),
3315 diag::note_previous_definition);
3319 // Create the class template partial specialization declaration.
3320 ClassTemplateSpecializationDecl *InstD =
3321 ClassTemplateSpecializationDecl::Create(
3322 SemaRef.Context, D->getTagKind(), Owner, D->getBeginLoc(),
3323 D->getLocation(), InstClassTemplate, Converted, PrevDecl);
3325 // Add this partial specialization to the set of class template partial
3328 InstClassTemplate->AddSpecialization(InstD, InsertPos);
3330 // Substitute the nested name specifier, if any.
3331 if (SubstQualifier(D, InstD))
3334 // Build the canonical type that describes the converted template
3335 // arguments of the class template explicit specialization.
3336 QualType CanonType = SemaRef.Context.getTemplateSpecializationType(
3337 TemplateName(InstClassTemplate), Converted,
3338 SemaRef.Context.getRecordType(InstD));
3340 // Build the fully-sugared type for this class template
3341 // specialization as the user wrote in the specialization
3342 // itself. This means that we'll pretty-print the type retrieved
3343 // from the specialization's declaration the way that the user
3344 // actually wrote the specialization, rather than formatting the
3345 // name based on the "canonical" representation used to store the
3346 // template arguments in the specialization.
3347 TypeSourceInfo *WrittenTy = SemaRef.Context.getTemplateSpecializationTypeInfo(
3348 TemplateName(InstClassTemplate), D->getLocation(), InstTemplateArgs,
3351 InstD->setAccess(D->getAccess());
3352 InstD->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
3353 InstD->setSpecializationKind(D->getSpecializationKind());
3354 InstD->setTypeAsWritten(WrittenTy);
3355 InstD->setExternLoc(D->getExternLoc());
3356 InstD->setTemplateKeywordLoc(D->getTemplateKeywordLoc());
3358 Owner->addDecl(InstD);
3360 // Instantiate the members of the class-scope explicit specialization eagerly.
3361 // We don't have support for lazy instantiation of an explicit specialization
3362 // yet, and MSVC eagerly instantiates in this case.
3363 // FIXME: This is wrong in standard C++.
3364 if (D->isThisDeclarationADefinition() &&
3365 SemaRef.InstantiateClass(D->getLocation(), InstD, D, TemplateArgs,
3366 TSK_ImplicitInstantiation,
3373 Decl *TemplateDeclInstantiator::VisitVarTemplateSpecializationDecl(
3374 VarTemplateSpecializationDecl *D) {
3376 TemplateArgumentListInfo VarTemplateArgsInfo;
3377 VarTemplateDecl *VarTemplate = D->getSpecializedTemplate();
3378 assert(VarTemplate &&
3379 "A template specialization without specialized template?");
3381 VarTemplateDecl *InstVarTemplate =
3382 cast_or_null<VarTemplateDecl>(SemaRef.FindInstantiatedDecl(
3383 D->getLocation(), VarTemplate, TemplateArgs));
3384 if (!InstVarTemplate)
3387 // Substitute the current template arguments.
3388 const TemplateArgumentListInfo &TemplateArgsInfo = D->getTemplateArgsInfo();
3389 VarTemplateArgsInfo.setLAngleLoc(TemplateArgsInfo.getLAngleLoc());
3390 VarTemplateArgsInfo.setRAngleLoc(TemplateArgsInfo.getRAngleLoc());
3392 if (SemaRef.Subst(TemplateArgsInfo.getArgumentArray(),
3393 TemplateArgsInfo.size(), VarTemplateArgsInfo, TemplateArgs))
3396 // Check that the template argument list is well-formed for this template.
3397 SmallVector<TemplateArgument, 4> Converted;
3398 if (SemaRef.CheckTemplateArgumentList(InstVarTemplate, D->getLocation(),
3399 VarTemplateArgsInfo, false, Converted))
3402 // Check whether we've already seen a declaration of this specialization.
3403 void *InsertPos = nullptr;
3404 VarTemplateSpecializationDecl *PrevDecl =
3405 InstVarTemplate->findSpecialization(Converted, InsertPos);
3407 // Check whether we've already seen a conflicting instantiation of this
3408 // declaration (for instance, if there was a prior implicit instantiation).
3410 if (PrevDecl && SemaRef.CheckSpecializationInstantiationRedecl(
3411 D->getLocation(), D->getSpecializationKind(), PrevDecl,
3412 PrevDecl->getSpecializationKind(),
3413 PrevDecl->getPointOfInstantiation(), Ignored))
3416 return VisitVarTemplateSpecializationDecl(
3417 InstVarTemplate, D, InsertPos, VarTemplateArgsInfo, Converted, PrevDecl);
3420 Decl *TemplateDeclInstantiator::VisitVarTemplateSpecializationDecl(
3421 VarTemplateDecl *VarTemplate, VarDecl *D, void *InsertPos,
3422 const TemplateArgumentListInfo &TemplateArgsInfo,
3423 ArrayRef<TemplateArgument> Converted,
3424 VarTemplateSpecializationDecl *PrevDecl) {
3426 // Do substitution on the type of the declaration
3427 TypeSourceInfo *DI =
3428 SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs,
3429 D->getTypeSpecStartLoc(), D->getDeclName());
3433 if (DI->getType()->isFunctionType()) {
3434 SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function)
3435 << D->isStaticDataMember() << DI->getType();
3439 // Build the instantiated declaration
3440 VarTemplateSpecializationDecl *Var = VarTemplateSpecializationDecl::Create(
3441 SemaRef.Context, Owner, D->getInnerLocStart(), D->getLocation(),
3442 VarTemplate, DI->getType(), DI, D->getStorageClass(), Converted);
3443 Var->setTemplateArgsInfo(TemplateArgsInfo);
3445 VarTemplate->AddSpecialization(Var, InsertPos);
3447 // Substitute the nested name specifier, if any.
3448 if (SubstQualifier(D, Var))
3451 SemaRef.BuildVariableInstantiation(Var, D, TemplateArgs, LateAttrs, Owner,
3452 StartingScope, false, PrevDecl);
3457 Decl *TemplateDeclInstantiator::VisitObjCAtDefsFieldDecl(ObjCAtDefsFieldDecl *D) {
3458 llvm_unreachable("@defs is not supported in Objective-C++");
3461 Decl *TemplateDeclInstantiator::VisitFriendTemplateDecl(FriendTemplateDecl *D) {
3462 // FIXME: We need to be able to instantiate FriendTemplateDecls.
3463 unsigned DiagID = SemaRef.getDiagnostics().getCustomDiagID(
3464 DiagnosticsEngine::Error,
3465 "cannot instantiate %0 yet");
3466 SemaRef.Diag(D->getLocation(), DiagID)
3467 << D->getDeclKindName();
3472 Decl *TemplateDeclInstantiator::VisitConceptDecl(ConceptDecl *D) {
3473 llvm_unreachable("Concept definitions cannot reside inside a template");
3476 Decl *TemplateDeclInstantiator::VisitDecl(Decl *D) {
3477 llvm_unreachable("Unexpected decl");
3480 Decl *Sema::SubstDecl(Decl *D, DeclContext *Owner,
3481 const MultiLevelTemplateArgumentList &TemplateArgs) {
3482 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
3483 if (D->isInvalidDecl())
3487 runWithSufficientStackSpace(D->getLocation(), [&] {
3488 SubstD = Instantiator.Visit(D);
3493 /// Instantiates a nested template parameter list in the current
3494 /// instantiation context.
3496 /// \param L The parameter list to instantiate
3498 /// \returns NULL if there was an error
3499 TemplateParameterList *
3500 TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList *L) {
3501 // Get errors for all the parameters before bailing out.
3502 bool Invalid = false;
3504 unsigned N = L->size();
3505 typedef SmallVector<NamedDecl *, 8> ParamVector;
3508 for (auto &P : *L) {
3509 NamedDecl *D = cast_or_null<NamedDecl>(Visit(P));
3510 Params.push_back(D);
3511 Invalid = Invalid || !D || D->isInvalidDecl();
3514 // Clean up if we had an error.
3518 // FIXME: Concepts: Substitution into requires clause should only happen when
3519 // checking satisfaction.
3520 Expr *InstRequiresClause = nullptr;
3521 if (Expr *E = L->getRequiresClause()) {
3522 ExprResult Res = SemaRef.SubstExpr(E, TemplateArgs);
3523 if (Res.isInvalid() || !Res.isUsable()) {
3526 InstRequiresClause = Res.get();
3529 TemplateParameterList *InstL
3530 = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(),
3531 L->getLAngleLoc(), Params,
3532 L->getRAngleLoc(), InstRequiresClause);
3536 TemplateParameterList *
3537 Sema::SubstTemplateParams(TemplateParameterList *Params, DeclContext *Owner,
3538 const MultiLevelTemplateArgumentList &TemplateArgs) {
3539 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
3540 return Instantiator.SubstTemplateParams(Params);
3543 /// Instantiate the declaration of a class template partial
3546 /// \param ClassTemplate the (instantiated) class template that is partially
3547 // specialized by the instantiation of \p PartialSpec.
3549 /// \param PartialSpec the (uninstantiated) class template partial
3550 /// specialization that we are instantiating.
3552 /// \returns The instantiated partial specialization, if successful; otherwise,
3553 /// NULL to indicate an error.
3554 ClassTemplatePartialSpecializationDecl *
3555 TemplateDeclInstantiator::InstantiateClassTemplatePartialSpecialization(
3556 ClassTemplateDecl *ClassTemplate,
3557 ClassTemplatePartialSpecializationDecl *PartialSpec) {
3558 // Create a local instantiation scope for this class template partial
3559 // specialization, which will contain the instantiations of the template
3561 LocalInstantiationScope Scope(SemaRef);
3563 // Substitute into the template parameters of the class template partial
3565 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
3566 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
3570 // Substitute into the template arguments of the class template partial
3572 const ASTTemplateArgumentListInfo *TemplArgInfo
3573 = PartialSpec->getTemplateArgsAsWritten();
3574 TemplateArgumentListInfo InstTemplateArgs(TemplArgInfo->LAngleLoc,
3575 TemplArgInfo->RAngleLoc);
3576 if (SemaRef.Subst(TemplArgInfo->getTemplateArgs(),
3577 TemplArgInfo->NumTemplateArgs,
3578 InstTemplateArgs, TemplateArgs))
3581 // Check that the template argument list is well-formed for this
3583 SmallVector<TemplateArgument, 4> Converted;
3584 if (SemaRef.CheckTemplateArgumentList(ClassTemplate,
3585 PartialSpec->getLocation(),
3591 // Check these arguments are valid for a template partial specialization.
3592 if (SemaRef.CheckTemplatePartialSpecializationArgs(
3593 PartialSpec->getLocation(), ClassTemplate, InstTemplateArgs.size(),
3597 // Figure out where to insert this class template partial specialization
3598 // in the member template's set of class template partial specializations.
3599 void *InsertPos = nullptr;
3600 ClassTemplateSpecializationDecl *PrevDecl
3601 = ClassTemplate->findPartialSpecialization(Converted, InsertPos);
3603 // Build the canonical type that describes the converted template
3604 // arguments of the class template partial specialization.
3606 = SemaRef.Context.getTemplateSpecializationType(TemplateName(ClassTemplate),
3609 // Build the fully-sugared type for this class template
3610 // specialization as the user wrote in the specialization
3611 // itself. This means that we'll pretty-print the type retrieved
3612 // from the specialization's declaration the way that the user
3613 // actually wrote the specialization, rather than formatting the
3614 // name based on the "canonical" representation used to store the
3615 // template arguments in the specialization.
3616 TypeSourceInfo *WrittenTy
3617 = SemaRef.Context.getTemplateSpecializationTypeInfo(
3618 TemplateName(ClassTemplate),
3619 PartialSpec->getLocation(),
3624 // We've already seen a partial specialization with the same template
3625 // parameters and template arguments. This can happen, for example, when
3626 // substituting the outer template arguments ends up causing two
3627 // class template partial specializations of a member class template
3628 // to have identical forms, e.g.,
3630 // template<typename T, typename U>
3632 // template<typename X, typename Y> struct Inner;
3633 // template<typename Y> struct Inner<T, Y>;
3634 // template<typename Y> struct Inner<U, Y>;
3637 // Outer<int, int> outer; // error: the partial specializations of Inner
3638 // // have the same signature.
3639 SemaRef.Diag(PartialSpec->getLocation(), diag::err_partial_spec_redeclared)
3640 << WrittenTy->getType();
3641 SemaRef.Diag(PrevDecl->getLocation(), diag::note_prev_partial_spec_here)
3642 << SemaRef.Context.getTypeDeclType(PrevDecl);
3647 // Create the class template partial specialization declaration.
3648 ClassTemplatePartialSpecializationDecl *InstPartialSpec =
3649 ClassTemplatePartialSpecializationDecl::Create(
3650 SemaRef.Context, PartialSpec->getTagKind(), Owner,
3651 PartialSpec->getBeginLoc(), PartialSpec->getLocation(), InstParams,
3652 ClassTemplate, Converted, InstTemplateArgs, CanonType, nullptr);
3653 // Substitute the nested name specifier, if any.
3654 if (SubstQualifier(PartialSpec, InstPartialSpec))
3657 InstPartialSpec->setInstantiatedFromMember(PartialSpec);
3658 InstPartialSpec->setTypeAsWritten(WrittenTy);
3660 // Check the completed partial specialization.
3661 SemaRef.CheckTemplatePartialSpecialization(InstPartialSpec);
3663 // Add this partial specialization to the set of class template partial
3665 ClassTemplate->AddPartialSpecialization(InstPartialSpec,
3666 /*InsertPos=*/nullptr);
3667 return InstPartialSpec;
3670 /// Instantiate the declaration of a variable template partial
3673 /// \param VarTemplate the (instantiated) variable template that is partially
3674 /// specialized by the instantiation of \p PartialSpec.
3676 /// \param PartialSpec the (uninstantiated) variable template partial
3677 /// specialization that we are instantiating.
3679 /// \returns The instantiated partial specialization, if successful; otherwise,
3680 /// NULL to indicate an error.
3681 VarTemplatePartialSpecializationDecl *
3682 TemplateDeclInstantiator::InstantiateVarTemplatePartialSpecialization(
3683 VarTemplateDecl *VarTemplate,
3684 VarTemplatePartialSpecializationDecl *PartialSpec) {
3685 // Create a local instantiation scope for this variable template partial
3686 // specialization, which will contain the instantiations of the template
3688 LocalInstantiationScope Scope(SemaRef);
3690 // Substitute into the template parameters of the variable template partial
3692 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
3693 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
3697 // Substitute into the template arguments of the variable template partial
3699 const ASTTemplateArgumentListInfo *TemplArgInfo
3700 = PartialSpec->getTemplateArgsAsWritten();
3701 TemplateArgumentListInfo InstTemplateArgs(TemplArgInfo->LAngleLoc,
3702 TemplArgInfo->RAngleLoc);
3703 if (SemaRef.Subst(TemplArgInfo->getTemplateArgs(),
3704 TemplArgInfo->NumTemplateArgs,
3705 InstTemplateArgs, TemplateArgs))
3708 // Check that the template argument list is well-formed for this
3710 SmallVector<TemplateArgument, 4> Converted;
3711 if (SemaRef.CheckTemplateArgumentList(VarTemplate, PartialSpec->getLocation(),
3712 InstTemplateArgs, false, Converted))
3715 // Check these arguments are valid for a template partial specialization.
3716 if (SemaRef.CheckTemplatePartialSpecializationArgs(
3717 PartialSpec->getLocation(), VarTemplate, InstTemplateArgs.size(),
3721 // Figure out where to insert this variable template partial specialization
3722 // in the member template's set of variable template partial specializations.
3723 void *InsertPos = nullptr;
3724 VarTemplateSpecializationDecl *PrevDecl =
3725 VarTemplate->findPartialSpecialization(Converted, InsertPos);
3727 // Build the canonical type that describes the converted template
3728 // arguments of the variable template partial specialization.
3729 QualType CanonType = SemaRef.Context.getTemplateSpecializationType(
3730 TemplateName(VarTemplate), Converted);
3732 // Build the fully-sugared type for this variable template
3733 // specialization as the user wrote in the specialization
3734 // itself. This means that we'll pretty-print the type retrieved
3735 // from the specialization's declaration the way that the user
3736 // actually wrote the specialization, rather than formatting the
3737 // name based on the "canonical" representation used to store the
3738 // template arguments in the specialization.
3739 TypeSourceInfo *WrittenTy = SemaRef.Context.getTemplateSpecializationTypeInfo(
3740 TemplateName(VarTemplate), PartialSpec->getLocation(), InstTemplateArgs,
3744 // We've already seen a partial specialization with the same template
3745 // parameters and template arguments. This can happen, for example, when
3746 // substituting the outer template arguments ends up causing two
3747 // variable template partial specializations of a member variable template
3748 // to have identical forms, e.g.,
3750 // template<typename T, typename U>
3752 // template<typename X, typename Y> pair<X,Y> p;
3753 // template<typename Y> pair<T, Y> p;
3754 // template<typename Y> pair<U, Y> p;
3757 // Outer<int, int> outer; // error: the partial specializations of Inner
3758 // // have the same signature.
3759 SemaRef.Diag(PartialSpec->getLocation(),
3760 diag::err_var_partial_spec_redeclared)
3761 << WrittenTy->getType();
3762 SemaRef.Diag(PrevDecl->getLocation(),
3763 diag::note_var_prev_partial_spec_here);
3767 // Do substitution on the type of the declaration
3768 TypeSourceInfo *DI = SemaRef.SubstType(
3769 PartialSpec->getTypeSourceInfo(), TemplateArgs,
3770 PartialSpec->getTypeSpecStartLoc(), PartialSpec->getDeclName());
3774 if (DI->getType()->isFunctionType()) {
3775 SemaRef.Diag(PartialSpec->getLocation(),
3776 diag::err_variable_instantiates_to_function)
3777 << PartialSpec->isStaticDataMember() << DI->getType();
3781 // Create the variable template partial specialization declaration.
3782 VarTemplatePartialSpecializationDecl *InstPartialSpec =
3783 VarTemplatePartialSpecializationDecl::Create(
3784 SemaRef.Context, Owner, PartialSpec->getInnerLocStart(),
3785 PartialSpec->getLocation(), InstParams, VarTemplate, DI->getType(),
3786 DI, PartialSpec->getStorageClass(), Converted, InstTemplateArgs);
3788 // Substitute the nested name specifier, if any.
3789 if (SubstQualifier(PartialSpec, InstPartialSpec))
3792 InstPartialSpec->setInstantiatedFromMember(PartialSpec);
3793 InstPartialSpec->setTypeAsWritten(WrittenTy);
3795 // Check the completed partial specialization.
3796 SemaRef.CheckTemplatePartialSpecialization(InstPartialSpec);
3798 // Add this partial specialization to the set of variable template partial
3799 // specializations. The instantiation of the initializer is not necessary.
3800 VarTemplate->AddPartialSpecialization(InstPartialSpec, /*InsertPos=*/nullptr);
3802 SemaRef.BuildVariableInstantiation(InstPartialSpec, PartialSpec, TemplateArgs,
3803 LateAttrs, Owner, StartingScope);
3805 return InstPartialSpec;
3809 TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D,
3810 SmallVectorImpl<ParmVarDecl *> &Params) {
3811 TypeSourceInfo *OldTInfo = D->getTypeSourceInfo();
3812 assert(OldTInfo && "substituting function without type source info");
3813 assert(Params.empty() && "parameter vector is non-empty at start");
3815 CXXRecordDecl *ThisContext = nullptr;
3816 Qualifiers ThisTypeQuals;
3817 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
3818 ThisContext = cast<CXXRecordDecl>(Owner);
3819 ThisTypeQuals = Method->getMethodQualifiers();
3822 TypeSourceInfo *NewTInfo
3823 = SemaRef.SubstFunctionDeclType(OldTInfo, TemplateArgs,
3824 D->getTypeSpecStartLoc(),
3826 ThisContext, ThisTypeQuals);
3830 TypeLoc OldTL = OldTInfo->getTypeLoc().IgnoreParens();
3831 if (FunctionProtoTypeLoc OldProtoLoc = OldTL.getAs<FunctionProtoTypeLoc>()) {
3832 if (NewTInfo != OldTInfo) {
3833 // Get parameters from the new type info.
3834 TypeLoc NewTL = NewTInfo->getTypeLoc().IgnoreParens();
3835 FunctionProtoTypeLoc NewProtoLoc = NewTL.castAs<FunctionProtoTypeLoc>();
3836 unsigned NewIdx = 0;
3837 for (unsigned OldIdx = 0, NumOldParams = OldProtoLoc.getNumParams();
3838 OldIdx != NumOldParams; ++OldIdx) {
3839 ParmVarDecl *OldParam = OldProtoLoc.getParam(OldIdx);
3840 LocalInstantiationScope *Scope = SemaRef.CurrentInstantiationScope;
3842 Optional<unsigned> NumArgumentsInExpansion;
3843 if (OldParam->isParameterPack())
3844 NumArgumentsInExpansion =
3845 SemaRef.getNumArgumentsInExpansion(OldParam->getType(),
3847 if (!NumArgumentsInExpansion) {
3848 // Simple case: normal parameter, or a parameter pack that's
3849 // instantiated to a (still-dependent) parameter pack.
3850 ParmVarDecl *NewParam = NewProtoLoc.getParam(NewIdx++);
3851 Params.push_back(NewParam);
3852 Scope->InstantiatedLocal(OldParam, NewParam);
3854 // Parameter pack expansion: make the instantiation an argument pack.
3855 Scope->MakeInstantiatedLocalArgPack(OldParam);
3856 for (unsigned I = 0; I != *NumArgumentsInExpansion; ++I) {
3857 ParmVarDecl *NewParam = NewProtoLoc.getParam(NewIdx++);
3858 Params.push_back(NewParam);
3859 Scope->InstantiatedLocalPackArg(OldParam, NewParam);
3864 // The function type itself was not dependent and therefore no
3865 // substitution occurred. However, we still need to instantiate
3866 // the function parameters themselves.
3867 const FunctionProtoType *OldProto =
3868 cast<FunctionProtoType>(OldProtoLoc.getType());
3869 for (unsigned i = 0, i_end = OldProtoLoc.getNumParams(); i != i_end;
3871 ParmVarDecl *OldParam = OldProtoLoc.getParam(i);
3873 Params.push_back(SemaRef.BuildParmVarDeclForTypedef(
3874 D, D->getLocation(), OldProto->getParamType(i)));
3879 cast_or_null<ParmVarDecl>(VisitParmVarDecl(OldParam));
3882 Params.push_back(Parm);
3886 // If the type of this function, after ignoring parentheses, is not
3887 // *directly* a function type, then we're instantiating a function that
3888 // was declared via a typedef or with attributes, e.g.,
3890 // typedef int functype(int, int);
3892 // int __cdecl meth(int, int);
3894 // In this case, we'll just go instantiate the ParmVarDecls that we
3895 // synthesized in the method declaration.
3896 SmallVector<QualType, 4> ParamTypes;
3897 Sema::ExtParameterInfoBuilder ExtParamInfos;
3898 if (SemaRef.SubstParmTypes(D->getLocation(), D->parameters(), nullptr,
3899 TemplateArgs, ParamTypes, &Params,
3907 /// Introduce the instantiated function parameters into the local
3908 /// instantiation scope, and set the parameter names to those used
3909 /// in the template.
3910 static bool addInstantiatedParametersToScope(Sema &S, FunctionDecl *Function,
3911 const FunctionDecl *PatternDecl,
3912 LocalInstantiationScope &Scope,
3913 const MultiLevelTemplateArgumentList &TemplateArgs) {
3914 unsigned FParamIdx = 0;
3915 for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I) {
3916 const ParmVarDecl *PatternParam = PatternDecl->getParamDecl(I);
3917 if (!PatternParam->isParameterPack()) {
3918 // Simple case: not a parameter pack.
3919 assert(FParamIdx < Function->getNumParams());
3920 ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
3921 FunctionParam->setDeclName(PatternParam->getDeclName());
3922 // If the parameter's type is not dependent, update it to match the type
3923 // in the pattern. They can differ in top-level cv-qualifiers, and we want
3924 // the pattern's type here. If the type is dependent, they can't differ,
3925 // per core issue 1668. Substitute into the type from the pattern, in case
3926 // it's instantiation-dependent.
3927 // FIXME: Updating the type to work around this is at best fragile.
3928 if (!PatternDecl->getType()->isDependentType()) {
3929 QualType T = S.SubstType(PatternParam->getType(), TemplateArgs,
3930 FunctionParam->getLocation(),
3931 FunctionParam->getDeclName());
3934 FunctionParam->setType(T);
3937 Scope.InstantiatedLocal(PatternParam, FunctionParam);
3942 // Expand the parameter pack.
3943 Scope.MakeInstantiatedLocalArgPack(PatternParam);
3944 Optional<unsigned> NumArgumentsInExpansion
3945 = S.getNumArgumentsInExpansion(PatternParam->getType(), TemplateArgs);
3946 if (NumArgumentsInExpansion) {
3947 QualType PatternType =
3948 PatternParam->getType()->castAs<PackExpansionType>()->getPattern();
3949 for (unsigned Arg = 0; Arg < *NumArgumentsInExpansion; ++Arg) {
3950 ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
3951 FunctionParam->setDeclName(PatternParam->getDeclName());
3952 if (!PatternDecl->getType()->isDependentType()) {
3953 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(S, Arg);
3954 QualType T = S.SubstType(PatternType, TemplateArgs,
3955 FunctionParam->getLocation(),
3956 FunctionParam->getDeclName());
3959 FunctionParam->setType(T);
3962 Scope.InstantiatedLocalPackArg(PatternParam, FunctionParam);
3971 void Sema::InstantiateExceptionSpec(SourceLocation PointOfInstantiation,
3972 FunctionDecl *Decl) {
3973 const FunctionProtoType *Proto = Decl->getType()->castAs<FunctionProtoType>();
3974 if (Proto->getExceptionSpecType() != EST_Uninstantiated)
3977 InstantiatingTemplate Inst(*this, PointOfInstantiation, Decl,
3978 InstantiatingTemplate::ExceptionSpecification());
3979 if (Inst.isInvalid()) {
3980 // We hit the instantiation depth limit. Clear the exception specification
3981 // so that our callers don't have to cope with EST_Uninstantiated.
3982 UpdateExceptionSpec(Decl, EST_None);
3985 if (Inst.isAlreadyInstantiating()) {
3986 // This exception specification indirectly depends on itself. Reject.
3987 // FIXME: Corresponding rule in the standard?
3988 Diag(PointOfInstantiation, diag::err_exception_spec_cycle) << Decl;
3989 UpdateExceptionSpec(Decl, EST_None);
3993 // Enter the scope of this instantiation. We don't use
3994 // PushDeclContext because we don't have a scope.
3995 Sema::ContextRAII savedContext(*this, Decl);
3996 LocalInstantiationScope Scope(*this);
3998 MultiLevelTemplateArgumentList TemplateArgs =
3999 getTemplateInstantiationArgs(Decl, nullptr, /*RelativeToPrimary*/true);
4001 FunctionDecl *Template = Proto->getExceptionSpecTemplate();
4002 if (addInstantiatedParametersToScope(*this, Decl, Template, Scope,
4004 UpdateExceptionSpec(Decl, EST_None);
4008 SubstExceptionSpec(Decl, Template->getType()->castAs<FunctionProtoType>(),
4012 /// Initializes the common fields of an instantiation function
4013 /// declaration (New) from the corresponding fields of its template (Tmpl).
4015 /// \returns true if there was an error
4017 TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New,
4018 FunctionDecl *Tmpl) {
4019 if (Tmpl->isDeleted())
4020 New->setDeletedAsWritten();
4022 New->setImplicit(Tmpl->isImplicit());
4024 // Forward the mangling number from the template to the instantiated decl.
4025 SemaRef.Context.setManglingNumber(New,
4026 SemaRef.Context.getManglingNumber(Tmpl));
4028 // If we are performing substituting explicitly-specified template arguments
4029 // or deduced template arguments into a function template and we reach this
4030 // point, we are now past the point where SFINAE applies and have committed
4031 // to keeping the new function template specialization. We therefore
4032 // convert the active template instantiation for the function template
4033 // into a template instantiation for this specific function template
4034 // specialization, which is not a SFINAE context, so that we diagnose any
4035 // further errors in the declaration itself.
4036 typedef Sema::CodeSynthesisContext ActiveInstType;
4037 ActiveInstType &ActiveInst = SemaRef.CodeSynthesisContexts.back();
4038 if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution ||
4039 ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) {
4040 if (FunctionTemplateDecl *FunTmpl
4041 = dyn_cast<FunctionTemplateDecl>(ActiveInst.Entity)) {
4042 assert(FunTmpl->getTemplatedDecl() == Tmpl &&
4043 "Deduction from the wrong function template?");
4045 atTemplateEnd(SemaRef.TemplateInstCallbacks, SemaRef, ActiveInst);
4046 ActiveInst.Kind = ActiveInstType::TemplateInstantiation;
4047 ActiveInst.Entity = New;
4048 atTemplateBegin(SemaRef.TemplateInstCallbacks, SemaRef, ActiveInst);
4052 const FunctionProtoType *Proto = Tmpl->getType()->getAs<FunctionProtoType>();
4053 assert(Proto && "Function template without prototype?");
4055 if (Proto->hasExceptionSpec() || Proto->getNoReturnAttr()) {
4056 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
4058 // DR1330: In C++11, defer instantiation of a non-trivial
4059 // exception specification.
4060 // DR1484: Local classes and their members are instantiated along with the
4061 // containing function.
4062 if (SemaRef.getLangOpts().CPlusPlus11 &&
4063 EPI.ExceptionSpec.Type != EST_None &&
4064 EPI.ExceptionSpec.Type != EST_DynamicNone &&
4065 EPI.ExceptionSpec.Type != EST_BasicNoexcept &&
4066 !Tmpl->isLexicallyWithinFunctionOrMethod()) {
4067 FunctionDecl *ExceptionSpecTemplate = Tmpl;
4068 if (EPI.ExceptionSpec.Type == EST_Uninstantiated)
4069 ExceptionSpecTemplate = EPI.ExceptionSpec.SourceTemplate;
4070 ExceptionSpecificationType NewEST = EST_Uninstantiated;
4071 if (EPI.ExceptionSpec.Type == EST_Unevaluated)
4072 NewEST = EST_Unevaluated;
4074 // Mark the function has having an uninstantiated exception specification.
4075 const FunctionProtoType *NewProto
4076 = New->getType()->getAs<FunctionProtoType>();
4077 assert(NewProto && "Template instantiation without function prototype?");
4078 EPI = NewProto->getExtProtoInfo();
4079 EPI.ExceptionSpec.Type = NewEST;
4080 EPI.ExceptionSpec.SourceDecl = New;
4081 EPI.ExceptionSpec.SourceTemplate = ExceptionSpecTemplate;
4082 New->setType(SemaRef.Context.getFunctionType(
4083 NewProto->getReturnType(), NewProto->getParamTypes(), EPI));
4085 Sema::ContextRAII SwitchContext(SemaRef, New);
4086 SemaRef.SubstExceptionSpec(New, Proto, TemplateArgs);
4090 // Get the definition. Leaves the variable unchanged if undefined.
4091 const FunctionDecl *Definition = Tmpl;
4092 Tmpl->isDefined(Definition);
4094 SemaRef.InstantiateAttrs(TemplateArgs, Definition, New,
4095 LateAttrs, StartingScope);
4100 /// Initializes common fields of an instantiated method
4101 /// declaration (New) from the corresponding fields of its template
4104 /// \returns true if there was an error
4106 TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New,
4107 CXXMethodDecl *Tmpl) {
4108 if (InitFunctionInstantiation(New, Tmpl))
4111 if (isa<CXXDestructorDecl>(New) && SemaRef.getLangOpts().CPlusPlus11)
4112 SemaRef.AdjustDestructorExceptionSpec(cast<CXXDestructorDecl>(New));
4114 New->setAccess(Tmpl->getAccess());
4115 if (Tmpl->isVirtualAsWritten())
4116 New->setVirtualAsWritten(true);
4118 // FIXME: New needs a pointer to Tmpl
4122 /// Instantiate (or find existing instantiation of) a function template with a
4123 /// given set of template arguments.
4125 /// Usually this should not be used, and template argument deduction should be
4126 /// used in its place.
4128 Sema::InstantiateFunctionDeclaration(FunctionTemplateDecl *FTD,
4129 const TemplateArgumentList *Args,
4130 SourceLocation Loc) {
4131 FunctionDecl *FD = FTD->getTemplatedDecl();
4133 sema::TemplateDeductionInfo Info(Loc);
4134 InstantiatingTemplate Inst(
4135 *this, Loc, FTD, Args->asArray(),
4136 CodeSynthesisContext::ExplicitTemplateArgumentSubstitution, Info);
4137 if (Inst.isInvalid())
4140 ContextRAII SavedContext(*this, FD);
4141 MultiLevelTemplateArgumentList MArgs(*Args);
4143 return cast_or_null<FunctionDecl>(SubstDecl(FD, FD->getParent(), MArgs));
4146 /// In the MS ABI, we need to instantiate default arguments of dllexported
4147 /// default constructors along with the constructor definition. This allows IR
4148 /// gen to emit a constructor closure which calls the default constructor with
4149 /// its default arguments.
4150 static void InstantiateDefaultCtorDefaultArgs(Sema &S,
4151 CXXConstructorDecl *Ctor) {
4152 assert(S.Context.getTargetInfo().getCXXABI().isMicrosoft() &&
4153 Ctor->isDefaultConstructor());
4154 unsigned NumParams = Ctor->getNumParams();
4157 DLLExportAttr *Attr = Ctor->getAttr<DLLExportAttr>();
4160 for (unsigned I = 0; I != NumParams; ++I) {
4161 (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), Ctor,
4162 Ctor->getParamDecl(I));
4163 S.DiscardCleanupsInEvaluationContext();
4167 /// Instantiate the definition of the given function from its
4170 /// \param PointOfInstantiation the point at which the instantiation was
4171 /// required. Note that this is not precisely a "point of instantiation"
4172 /// for the function, but it's close.
4174 /// \param Function the already-instantiated declaration of a
4175 /// function template specialization or member function of a class template
4178 /// \param Recursive if true, recursively instantiates any functions that
4179 /// are required by this instantiation.
4181 /// \param DefinitionRequired if true, then we are performing an explicit
4182 /// instantiation where the body of the function is required. Complain if
4183 /// there is no such body.
4184 void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
4185 FunctionDecl *Function,
4187 bool DefinitionRequired,
4189 if (Function->isInvalidDecl() || Function->isDefined() ||
4190 isa<CXXDeductionGuideDecl>(Function))
4193 // Never instantiate an explicit specialization except if it is a class scope
4194 // explicit specialization.
4195 TemplateSpecializationKind TSK =
4196 Function->getTemplateSpecializationKindForInstantiation();
4197 if (TSK == TSK_ExplicitSpecialization)
4200 // Find the function body that we'll be substituting.
4201 const FunctionDecl *PatternDecl = Function->getTemplateInstantiationPattern();
4202 assert(PatternDecl && "instantiating a non-template");
4204 const FunctionDecl *PatternDef = PatternDecl->getDefinition();
4205 Stmt *Pattern = nullptr;
4207 Pattern = PatternDef->getBody(PatternDef);
4208 PatternDecl = PatternDef;
4209 if (PatternDef->willHaveBody())
4210 PatternDef = nullptr;
4213 // FIXME: We need to track the instantiation stack in order to know which
4214 // definitions should be visible within this instantiation.
4215 if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Function,
4216 Function->getInstantiatedFromMemberFunction(),
4217 PatternDecl, PatternDef, TSK,
4218 /*Complain*/DefinitionRequired)) {
4219 if (DefinitionRequired)
4220 Function->setInvalidDecl();
4221 else if (TSK == TSK_ExplicitInstantiationDefinition) {
4222 // Try again at the end of the translation unit (at which point a
4223 // definition will be required).
4225 Function->setInstantiationIsPending(true);
4226 PendingInstantiations.push_back(
4227 std::make_pair(Function, PointOfInstantiation));
4228 } else if (TSK == TSK_ImplicitInstantiation) {
4229 if (AtEndOfTU && !getDiagnostics().hasErrorOccurred() &&
4230 !getSourceManager().isInSystemHeader(PatternDecl->getBeginLoc())) {
4231 Diag(PointOfInstantiation, diag::warn_func_template_missing)
4233 Diag(PatternDecl->getLocation(), diag::note_forward_template_decl);
4234 if (getLangOpts().CPlusPlus11)
4235 Diag(PointOfInstantiation, diag::note_inst_declaration_hint)
4243 // Postpone late parsed template instantiations.
4244 if (PatternDecl->isLateTemplateParsed() &&
4245 !LateTemplateParser) {
4246 Function->setInstantiationIsPending(true);
4247 LateParsedInstantiations.push_back(
4248 std::make_pair(Function, PointOfInstantiation));
4252 llvm::TimeTraceScope TimeScope("InstantiateFunction", [&]() {
4254 llvm::raw_string_ostream OS(Name);
4255 Function->getNameForDiagnostic(OS, getPrintingPolicy(),
4256 /*Qualified=*/true);
4260 // If we're performing recursive template instantiation, create our own
4261 // queue of pending implicit instantiations that we will instantiate later,
4262 // while we're still within our own instantiation context.
4263 // This has to happen before LateTemplateParser below is called, so that
4264 // it marks vtables used in late parsed templates as used.
4265 GlobalEagerInstantiationScope GlobalInstantiations(*this,
4266 /*Enabled=*/Recursive);
4267 LocalEagerInstantiationScope LocalInstantiations(*this);
4269 // Call the LateTemplateParser callback if there is a need to late parse
4270 // a templated function definition.
4271 if (!Pattern && PatternDecl->isLateTemplateParsed() &&
4272 LateTemplateParser) {
4273 // FIXME: Optimize to allow individual templates to be deserialized.
4274 if (PatternDecl->isFromASTFile())
4275 ExternalSource->ReadLateParsedTemplates(LateParsedTemplateMap);
4277 auto LPTIter = LateParsedTemplateMap.find(PatternDecl);
4278 assert(LPTIter != LateParsedTemplateMap.end() &&
4279 "missing LateParsedTemplate");
4280 LateTemplateParser(OpaqueParser, *LPTIter->second);
4281 Pattern = PatternDecl->getBody(PatternDecl);
4284 // Note, we should never try to instantiate a deleted function template.
4285 assert((Pattern || PatternDecl->isDefaulted() ||
4286 PatternDecl->hasSkippedBody()) &&
4287 "unexpected kind of function template definition");
4289 // C++1y [temp.explicit]p10:
4290 // Except for inline functions, declarations with types deduced from their
4291 // initializer or return value, and class template specializations, other
4292 // explicit instantiation declarations have the effect of suppressing the
4293 // implicit instantiation of the entity to which they refer.
4294 if (TSK == TSK_ExplicitInstantiationDeclaration &&
4295 !PatternDecl->isInlined() &&
4296 !PatternDecl->getReturnType()->getContainedAutoType())
4299 if (PatternDecl->isInlined()) {
4300 // Function, and all later redeclarations of it (from imported modules,
4301 // for instance), are now implicitly inline.
4302 for (auto *D = Function->getMostRecentDecl(); /**/;
4303 D = D->getPreviousDecl()) {
4304 D->setImplicitlyInline();
4310 InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
4311 if (Inst.isInvalid() || Inst.isAlreadyInstantiating())
4313 PrettyDeclStackTraceEntry CrashInfo(Context, Function, SourceLocation(),
4314 "instantiating function definition");
4316 // The instantiation is visible here, even if it was first declared in an
4317 // unimported module.
4318 Function->setVisibleDespiteOwningModule();
4320 // Copy the inner loc start from the pattern.
4321 Function->setInnerLocStart(PatternDecl->getInnerLocStart());
4323 EnterExpressionEvaluationContext EvalContext(
4324 *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
4326 // Introduce a new scope where local variable instantiations will be
4327 // recorded, unless we're actually a member function within a local
4328 // class, in which case we need to merge our results with the parent
4329 // scope (of the enclosing function).
4330 bool MergeWithParentScope = false;
4331 if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Function->getDeclContext()))
4332 MergeWithParentScope = Rec->isLocalClass();
4334 LocalInstantiationScope Scope(*this, MergeWithParentScope);
4336 if (PatternDecl->isDefaulted())
4337 SetDeclDefaulted(Function, PatternDecl->getLocation());
4339 MultiLevelTemplateArgumentList TemplateArgs =
4340 getTemplateInstantiationArgs(Function, nullptr, false, PatternDecl);
4342 // Substitute into the qualifier; we can get a substitution failure here
4343 // through evil use of alias templates.
4344 // FIXME: Is CurContext correct for this? Should we go to the (instantiation
4345 // of the) lexical context of the pattern?
4346 SubstQualifier(*this, PatternDecl, Function, TemplateArgs);
4348 ActOnStartOfFunctionDef(nullptr, Function);
4350 // Enter the scope of this instantiation. We don't use
4351 // PushDeclContext because we don't have a scope.
4352 Sema::ContextRAII savedContext(*this, Function);
4354 if (addInstantiatedParametersToScope(*this, Function, PatternDecl, Scope,
4359 if (PatternDecl->hasSkippedBody()) {
4360 ActOnSkippedFunctionBody(Function);
4363 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Function)) {
4364 // If this is a constructor, instantiate the member initializers.
4365 InstantiateMemInitializers(Ctor, cast<CXXConstructorDecl>(PatternDecl),
4368 // If this is an MS ABI dllexport default constructor, instantiate any
4369 // default arguments.
4370 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
4371 Ctor->isDefaultConstructor()) {
4372 InstantiateDefaultCtorDefaultArgs(*this, Ctor);
4376 // Instantiate the function body.
4377 Body = SubstStmt(Pattern, TemplateArgs);
4379 if (Body.isInvalid())
4380 Function->setInvalidDecl();
4382 // FIXME: finishing the function body while in an expression evaluation
4383 // context seems wrong. Investigate more.
4384 ActOnFinishFunctionBody(Function, Body.get(), /*IsInstantiation=*/true);
4386 PerformDependentDiagnostics(PatternDecl, TemplateArgs);
4388 if (auto *Listener = getASTMutationListener())
4389 Listener->FunctionDefinitionInstantiated(Function);
4394 DeclGroupRef DG(Function);
4395 Consumer.HandleTopLevelDecl(DG);
4397 // This class may have local implicit instantiations that need to be
4398 // instantiation within this scope.
4399 LocalInstantiations.perform();
4401 GlobalInstantiations.perform();
4404 VarTemplateSpecializationDecl *Sema::BuildVarTemplateInstantiation(
4405 VarTemplateDecl *VarTemplate, VarDecl *FromVar,
4406 const TemplateArgumentList &TemplateArgList,
4407 const TemplateArgumentListInfo &TemplateArgsInfo,
4408 SmallVectorImpl<TemplateArgument> &Converted,
4409 SourceLocation PointOfInstantiation, void *InsertPos,
4410 LateInstantiatedAttrVec *LateAttrs,
4411 LocalInstantiationScope *StartingScope) {
4412 if (FromVar->isInvalidDecl())
4415 InstantiatingTemplate Inst(*this, PointOfInstantiation, FromVar);
4416 if (Inst.isInvalid())
4419 MultiLevelTemplateArgumentList TemplateArgLists;
4420 TemplateArgLists.addOuterTemplateArguments(&TemplateArgList);
4422 // Instantiate the first declaration of the variable template: for a partial
4423 // specialization of a static data member template, the first declaration may
4424 // or may not be the declaration in the class; if it's in the class, we want
4425 // to instantiate a member in the class (a declaration), and if it's outside,
4426 // we want to instantiate a definition.
4428 // If we're instantiating an explicitly-specialized member template or member
4429 // partial specialization, don't do this. The member specialization completely
4430 // replaces the original declaration in this case.
4431 bool IsMemberSpec = false;
4432 if (VarTemplatePartialSpecializationDecl *PartialSpec =
4433 dyn_cast<VarTemplatePartialSpecializationDecl>(FromVar))
4434 IsMemberSpec = PartialSpec->isMemberSpecialization();
4435 else if (VarTemplateDecl *FromTemplate = FromVar->getDescribedVarTemplate())
4436 IsMemberSpec = FromTemplate->isMemberSpecialization();
4438 FromVar = FromVar->getFirstDecl();
4440 MultiLevelTemplateArgumentList MultiLevelList(TemplateArgList);
4441 TemplateDeclInstantiator Instantiator(*this, FromVar->getDeclContext(),
4444 // TODO: Set LateAttrs and StartingScope ...
4446 return cast_or_null<VarTemplateSpecializationDecl>(
4447 Instantiator.VisitVarTemplateSpecializationDecl(
4448 VarTemplate, FromVar, InsertPos, TemplateArgsInfo, Converted));
4451 /// Instantiates a variable template specialization by completing it
4452 /// with appropriate type information and initializer.
4453 VarTemplateSpecializationDecl *Sema::CompleteVarTemplateSpecializationDecl(
4454 VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl,
4455 const MultiLevelTemplateArgumentList &TemplateArgs) {
4456 assert(PatternDecl->isThisDeclarationADefinition() &&
4457 "don't have a definition to instantiate from");
4459 // Do substitution on the type of the declaration
4460 TypeSourceInfo *DI =
4461 SubstType(PatternDecl->getTypeSourceInfo(), TemplateArgs,
4462 PatternDecl->getTypeSpecStartLoc(), PatternDecl->getDeclName());
4466 // Update the type of this variable template specialization.
4467 VarSpec->setType(DI->getType());
4469 // Convert the declaration into a definition now.
4470 VarSpec->setCompleteDefinition();
4472 // Instantiate the initializer.
4473 InstantiateVariableInitializer(VarSpec, PatternDecl, TemplateArgs);
4478 /// BuildVariableInstantiation - Used after a new variable has been created.
4479 /// Sets basic variable data and decides whether to postpone the
4480 /// variable instantiation.
4481 void Sema::BuildVariableInstantiation(
4482 VarDecl *NewVar, VarDecl *OldVar,
4483 const MultiLevelTemplateArgumentList &TemplateArgs,
4484 LateInstantiatedAttrVec *LateAttrs, DeclContext *Owner,
4485 LocalInstantiationScope *StartingScope,
4486 bool InstantiatingVarTemplate,
4487 VarTemplateSpecializationDecl *PrevDeclForVarTemplateSpecialization) {
4488 // Instantiating a partial specialization to produce a partial
4490 bool InstantiatingVarTemplatePartialSpec =
4491 isa<VarTemplatePartialSpecializationDecl>(OldVar) &&
4492 isa<VarTemplatePartialSpecializationDecl>(NewVar);
4493 // Instantiating from a variable template (or partial specialization) to
4494 // produce a variable template specialization.
4495 bool InstantiatingSpecFromTemplate =
4496 isa<VarTemplateSpecializationDecl>(NewVar) &&
4497 (OldVar->getDescribedVarTemplate() ||
4498 isa<VarTemplatePartialSpecializationDecl>(OldVar));
4500 // If we are instantiating a local extern declaration, the
4501 // instantiation belongs lexically to the containing function.
4502 // If we are instantiating a static data member defined
4503 // out-of-line, the instantiation will have the same lexical
4504 // context (which will be a namespace scope) as the template.
4505 if (OldVar->isLocalExternDecl()) {
4506 NewVar->setLocalExternDecl();
4507 NewVar->setLexicalDeclContext(Owner);
4508 } else if (OldVar->isOutOfLine())
4509 NewVar->setLexicalDeclContext(OldVar->getLexicalDeclContext());
4510 NewVar->setTSCSpec(OldVar->getTSCSpec());
4511 NewVar->setInitStyle(OldVar->getInitStyle());
4512 NewVar->setCXXForRangeDecl(OldVar->isCXXForRangeDecl());
4513 NewVar->setObjCForDecl(OldVar->isObjCForDecl());
4514 NewVar->setConstexpr(OldVar->isConstexpr());
4515 NewVar->setInitCapture(OldVar->isInitCapture());
4516 NewVar->setPreviousDeclInSameBlockScope(
4517 OldVar->isPreviousDeclInSameBlockScope());
4518 NewVar->setAccess(OldVar->getAccess());
4520 if (!OldVar->isStaticDataMember()) {
4521 if (OldVar->isUsed(false))
4522 NewVar->setIsUsed();
4523 NewVar->setReferenced(OldVar->isReferenced());
4526 InstantiateAttrs(TemplateArgs, OldVar, NewVar, LateAttrs, StartingScope);
4528 LookupResult Previous(
4529 *this, NewVar->getDeclName(), NewVar->getLocation(),
4530 NewVar->isLocalExternDecl() ? Sema::LookupRedeclarationWithLinkage
4531 : Sema::LookupOrdinaryName,
4532 NewVar->isLocalExternDecl() ? Sema::ForExternalRedeclaration
4533 : forRedeclarationInCurContext());
4535 if (NewVar->isLocalExternDecl() && OldVar->getPreviousDecl() &&
4536 (!OldVar->getPreviousDecl()->getDeclContext()->isDependentContext() ||
4537 OldVar->getPreviousDecl()->getDeclContext()==OldVar->getDeclContext())) {
4538 // We have a previous declaration. Use that one, so we merge with the
4540 if (NamedDecl *NewPrev = FindInstantiatedDecl(
4541 NewVar->getLocation(), OldVar->getPreviousDecl(), TemplateArgs))
4542 Previous.addDecl(NewPrev);
4543 } else if (!isa<VarTemplateSpecializationDecl>(NewVar) &&
4544 OldVar->hasLinkage()) {
4545 LookupQualifiedName(Previous, NewVar->getDeclContext(), false);
4546 } else if (PrevDeclForVarTemplateSpecialization) {
4547 Previous.addDecl(PrevDeclForVarTemplateSpecialization);
4549 CheckVariableDeclaration(NewVar, Previous);
4551 if (!InstantiatingVarTemplate) {
4552 NewVar->getLexicalDeclContext()->addHiddenDecl(NewVar);
4553 if (!NewVar->isLocalExternDecl() || !NewVar->getPreviousDecl())
4554 NewVar->getDeclContext()->makeDeclVisibleInContext(NewVar);
4557 if (!OldVar->isOutOfLine()) {
4558 if (NewVar->getDeclContext()->isFunctionOrMethod())
4559 CurrentInstantiationScope->InstantiatedLocal(OldVar, NewVar);
4562 // Link instantiations of static data members back to the template from
4563 // which they were instantiated.
4565 // Don't do this when instantiating a template (we link the template itself
4566 // back in that case) nor when instantiating a static data member template
4567 // (that's not a member specialization).
4568 if (NewVar->isStaticDataMember() && !InstantiatingVarTemplate &&
4569 !InstantiatingSpecFromTemplate)
4570 NewVar->setInstantiationOfStaticDataMember(OldVar,
4571 TSK_ImplicitInstantiation);
4573 // If the pattern is an (in-class) explicit specialization, then the result
4574 // is also an explicit specialization.
4575 if (VarTemplateSpecializationDecl *OldVTSD =
4576 dyn_cast<VarTemplateSpecializationDecl>(OldVar)) {
4577 if (OldVTSD->getSpecializationKind() == TSK_ExplicitSpecialization &&
4578 !isa<VarTemplatePartialSpecializationDecl>(OldVTSD))
4579 cast<VarTemplateSpecializationDecl>(NewVar)->setSpecializationKind(
4580 TSK_ExplicitSpecialization);
4583 // Forward the mangling number from the template to the instantiated decl.
4584 Context.setManglingNumber(NewVar, Context.getManglingNumber(OldVar));
4585 Context.setStaticLocalNumber(NewVar, Context.getStaticLocalNumber(OldVar));
4587 // Figure out whether to eagerly instantiate the initializer.
4588 if (InstantiatingVarTemplate || InstantiatingVarTemplatePartialSpec) {
4589 // We're producing a template. Don't instantiate the initializer yet.
4590 } else if (NewVar->getType()->isUndeducedType()) {
4591 // We need the type to complete the declaration of the variable.
4592 InstantiateVariableInitializer(NewVar, OldVar, TemplateArgs);
4593 } else if (InstantiatingSpecFromTemplate ||
4594 (OldVar->isInline() && OldVar->isThisDeclarationADefinition() &&
4595 !NewVar->isThisDeclarationADefinition())) {
4596 // Delay instantiation of the initializer for variable template
4597 // specializations or inline static data members until a definition of the
4598 // variable is needed.
4600 InstantiateVariableInitializer(NewVar, OldVar, TemplateArgs);
4603 // Diagnose unused local variables with dependent types, where the diagnostic
4604 // will have been deferred.
4605 if (!NewVar->isInvalidDecl() &&
4606 NewVar->getDeclContext()->isFunctionOrMethod() &&
4607 OldVar->getType()->isDependentType())
4608 DiagnoseUnusedDecl(NewVar);
4611 /// Instantiate the initializer of a variable.
4612 void Sema::InstantiateVariableInitializer(
4613 VarDecl *Var, VarDecl *OldVar,
4614 const MultiLevelTemplateArgumentList &TemplateArgs) {
4615 if (ASTMutationListener *L = getASTContext().getASTMutationListener())
4616 L->VariableDefinitionInstantiated(Var);
4618 // We propagate the 'inline' flag with the initializer, because it
4619 // would otherwise imply that the variable is a definition for a
4620 // non-static data member.
4621 if (OldVar->isInlineSpecified())
4622 Var->setInlineSpecified();
4623 else if (OldVar->isInline())
4624 Var->setImplicitlyInline();
4626 if (OldVar->getInit()) {
4627 EnterExpressionEvaluationContext Evaluated(
4628 *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated, Var);
4630 // Instantiate the initializer.
4634 ContextRAII SwitchContext(*this, Var->getDeclContext());
4635 Init = SubstInitializer(OldVar->getInit(), TemplateArgs,
4636 OldVar->getInitStyle() == VarDecl::CallInit);
4639 if (!Init.isInvalid()) {
4640 Expr *InitExpr = Init.get();
4642 if (Var->hasAttr<DLLImportAttr>() &&
4644 !InitExpr->isConstantInitializer(getASTContext(), false))) {
4645 // Do not dynamically initialize dllimport variables.
4646 } else if (InitExpr) {
4647 bool DirectInit = OldVar->isDirectInit();
4648 AddInitializerToDecl(Var, InitExpr, DirectInit);
4650 ActOnUninitializedDecl(Var);
4652 // FIXME: Not too happy about invalidating the declaration
4653 // because of a bogus initializer.
4654 Var->setInvalidDecl();
4657 // `inline` variables are a definition and declaration all in one; we won't
4658 // pick up an initializer from anywhere else.
4659 if (Var->isStaticDataMember() && !Var->isInline()) {
4660 if (!Var->isOutOfLine())
4663 // If the declaration inside the class had an initializer, don't add
4664 // another one to the out-of-line definition.
4665 if (OldVar->getFirstDecl()->hasInit())
4669 // We'll add an initializer to a for-range declaration later.
4670 if (Var->isCXXForRangeDecl() || Var->isObjCForDecl())
4673 ActOnUninitializedDecl(Var);
4676 if (getLangOpts().CUDA)
4677 checkAllowedCUDAInitializer(Var);
4680 /// Instantiate the definition of the given variable from its
4683 /// \param PointOfInstantiation the point at which the instantiation was
4684 /// required. Note that this is not precisely a "point of instantiation"
4685 /// for the variable, but it's close.
4687 /// \param Var the already-instantiated declaration of a templated variable.
4689 /// \param Recursive if true, recursively instantiates any functions that
4690 /// are required by this instantiation.
4692 /// \param DefinitionRequired if true, then we are performing an explicit
4693 /// instantiation where a definition of the variable is required. Complain
4694 /// if there is no such definition.
4695 void Sema::InstantiateVariableDefinition(SourceLocation PointOfInstantiation,
4696 VarDecl *Var, bool Recursive,
4697 bool DefinitionRequired, bool AtEndOfTU) {
4698 if (Var->isInvalidDecl())
4701 // Never instantiate an explicitly-specialized entity.
4702 TemplateSpecializationKind TSK =
4703 Var->getTemplateSpecializationKindForInstantiation();
4704 if (TSK == TSK_ExplicitSpecialization)
4707 // Find the pattern and the arguments to substitute into it.
4708 VarDecl *PatternDecl = Var->getTemplateInstantiationPattern();
4709 assert(PatternDecl && "no pattern for templated variable");
4710 MultiLevelTemplateArgumentList TemplateArgs =
4711 getTemplateInstantiationArgs(Var);
4713 VarTemplateSpecializationDecl *VarSpec =
4714 dyn_cast<VarTemplateSpecializationDecl>(Var);
4716 // If this is a variable template specialization, make sure that it is
4718 bool InstantiationDependent = false;
4719 assert(!TemplateSpecializationType::anyDependentTemplateArguments(
4720 VarSpec->getTemplateArgsInfo(), InstantiationDependent) &&
4721 "Only instantiate variable template specializations that are "
4722 "not type-dependent");
4723 (void)InstantiationDependent;
4725 // If this is a static data member template, there might be an
4726 // uninstantiated initializer on the declaration. If so, instantiate
4729 // FIXME: This largely duplicates what we would do below. The difference
4730 // is that along this path we may instantiate an initializer from an
4731 // in-class declaration of the template and instantiate the definition
4732 // from a separate out-of-class definition.
4733 if (PatternDecl->isStaticDataMember() &&
4734 (PatternDecl = PatternDecl->getFirstDecl())->hasInit() &&
4736 // FIXME: Factor out the duplicated instantiation context setup/tear down
4738 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
4739 if (Inst.isInvalid() || Inst.isAlreadyInstantiating())
4741 PrettyDeclStackTraceEntry CrashInfo(Context, Var, SourceLocation(),
4742 "instantiating variable initializer");
4744 // The instantiation is visible here, even if it was first declared in an
4745 // unimported module.
4746 Var->setVisibleDespiteOwningModule();
4748 // If we're performing recursive template instantiation, create our own
4749 // queue of pending implicit instantiations that we will instantiate
4750 // later, while we're still within our own instantiation context.
4751 GlobalEagerInstantiationScope GlobalInstantiations(*this,
4752 /*Enabled=*/Recursive);
4753 LocalInstantiationScope Local(*this);
4754 LocalEagerInstantiationScope LocalInstantiations(*this);
4756 // Enter the scope of this instantiation. We don't use
4757 // PushDeclContext because we don't have a scope.
4758 ContextRAII PreviousContext(*this, Var->getDeclContext());
4759 InstantiateVariableInitializer(Var, PatternDecl, TemplateArgs);
4760 PreviousContext.pop();
4762 // This variable may have local implicit instantiations that need to be
4763 // instantiated within this scope.
4764 LocalInstantiations.perform();
4766 GlobalInstantiations.perform();
4769 assert(Var->isStaticDataMember() && PatternDecl->isStaticDataMember() &&
4770 "not a static data member?");
4773 VarDecl *Def = PatternDecl->getDefinition(getASTContext());
4775 // If we don't have a definition of the variable template, we won't perform
4776 // any instantiation. Rather, we rely on the user to instantiate this
4777 // definition (or provide a specialization for it) in another translation
4779 if (!Def && !DefinitionRequired) {
4780 if (TSK == TSK_ExplicitInstantiationDefinition) {
4781 PendingInstantiations.push_back(
4782 std::make_pair(Var, PointOfInstantiation));
4783 } else if (TSK == TSK_ImplicitInstantiation) {
4784 // Warn about missing definition at the end of translation unit.
4785 if (AtEndOfTU && !getDiagnostics().hasErrorOccurred() &&
4786 !getSourceManager().isInSystemHeader(PatternDecl->getBeginLoc())) {
4787 Diag(PointOfInstantiation, diag::warn_var_template_missing)
4789 Diag(PatternDecl->getLocation(), diag::note_forward_template_decl);
4790 if (getLangOpts().CPlusPlus11)
4791 Diag(PointOfInstantiation, diag::note_inst_declaration_hint) << Var;
4797 // FIXME: We need to track the instantiation stack in order to know which
4798 // definitions should be visible within this instantiation.
4799 // FIXME: Produce diagnostics when Var->getInstantiatedFromStaticDataMember().
4800 if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Var,
4801 /*InstantiatedFromMember*/false,
4802 PatternDecl, Def, TSK,
4803 /*Complain*/DefinitionRequired))
4806 // C++11 [temp.explicit]p10:
4807 // Except for inline functions, const variables of literal types, variables
4808 // of reference types, [...] explicit instantiation declarations
4809 // have the effect of suppressing the implicit instantiation of the entity
4810 // to which they refer.
4812 // FIXME: That's not exactly the same as "might be usable in constant
4813 // expressions", which only allows constexpr variables and const integral
4814 // types, not arbitrary const literal types.
4815 if (TSK == TSK_ExplicitInstantiationDeclaration &&
4816 !Var->mightBeUsableInConstantExpressions(getASTContext()))
4819 // Make sure to pass the instantiated variable to the consumer at the end.
4820 struct PassToConsumerRAII {
4821 ASTConsumer &Consumer;
4824 PassToConsumerRAII(ASTConsumer &Consumer, VarDecl *Var)
4825 : Consumer(Consumer), Var(Var) { }
4827 ~PassToConsumerRAII() {
4828 Consumer.HandleCXXStaticMemberVarInstantiation(Var);
4830 } PassToConsumerRAII(Consumer, Var);
4832 // If we already have a definition, we're done.
4833 if (VarDecl *Def = Var->getDefinition()) {
4834 // We may be explicitly instantiating something we've already implicitly
4836 Def->setTemplateSpecializationKind(Var->getTemplateSpecializationKind(),
4837 PointOfInstantiation);
4841 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
4842 if (Inst.isInvalid() || Inst.isAlreadyInstantiating())
4844 PrettyDeclStackTraceEntry CrashInfo(Context, Var, SourceLocation(),
4845 "instantiating variable definition");
4847 // If we're performing recursive template instantiation, create our own
4848 // queue of pending implicit instantiations that we will instantiate later,
4849 // while we're still within our own instantiation context.
4850 GlobalEagerInstantiationScope GlobalInstantiations(*this,
4851 /*Enabled=*/Recursive);
4853 // Enter the scope of this instantiation. We don't use
4854 // PushDeclContext because we don't have a scope.
4855 ContextRAII PreviousContext(*this, Var->getDeclContext());
4856 LocalInstantiationScope Local(*this);
4858 LocalEagerInstantiationScope LocalInstantiations(*this);
4860 VarDecl *OldVar = Var;
4861 if (Def->isStaticDataMember() && !Def->isOutOfLine()) {
4862 // We're instantiating an inline static data member whose definition was
4863 // provided inside the class.
4864 InstantiateVariableInitializer(Var, Def, TemplateArgs);
4865 } else if (!VarSpec) {
4866 Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(),
4868 } else if (Var->isStaticDataMember() &&
4869 Var->getLexicalDeclContext()->isRecord()) {
4870 // We need to instantiate the definition of a static data member template,
4871 // and all we have is the in-class declaration of it. Instantiate a separate
4872 // declaration of the definition.
4873 TemplateDeclInstantiator Instantiator(*this, Var->getDeclContext(),
4875 Var = cast_or_null<VarDecl>(Instantiator.VisitVarTemplateSpecializationDecl(
4876 VarSpec->getSpecializedTemplate(), Def, nullptr,
4877 VarSpec->getTemplateArgsInfo(), VarSpec->getTemplateArgs().asArray()));
4879 llvm::PointerUnion<VarTemplateDecl *,
4880 VarTemplatePartialSpecializationDecl *> PatternPtr =
4881 VarSpec->getSpecializedTemplateOrPartial();
4882 if (VarTemplatePartialSpecializationDecl *Partial =
4883 PatternPtr.dyn_cast<VarTemplatePartialSpecializationDecl *>())
4884 cast<VarTemplateSpecializationDecl>(Var)->setInstantiationOf(
4885 Partial, &VarSpec->getTemplateInstantiationArgs());
4887 // Merge the definition with the declaration.
4888 LookupResult R(*this, Var->getDeclName(), Var->getLocation(),
4889 LookupOrdinaryName, forRedeclarationInCurContext());
4891 MergeVarDecl(Var, R);
4893 // Attach the initializer.
4894 InstantiateVariableInitializer(Var, Def, TemplateArgs);
4897 // Complete the existing variable's definition with an appropriately
4898 // substituted type and initializer.
4899 Var = CompleteVarTemplateSpecializationDecl(VarSpec, Def, TemplateArgs);
4901 PreviousContext.pop();
4904 PassToConsumerRAII.Var = Var;
4905 Var->setTemplateSpecializationKind(OldVar->getTemplateSpecializationKind(),
4906 OldVar->getPointOfInstantiation());
4909 // This variable may have local implicit instantiations that need to be
4910 // instantiated within this scope.
4911 LocalInstantiations.perform();
4913 GlobalInstantiations.perform();
4917 Sema::InstantiateMemInitializers(CXXConstructorDecl *New,
4918 const CXXConstructorDecl *Tmpl,
4919 const MultiLevelTemplateArgumentList &TemplateArgs) {
4921 SmallVector<CXXCtorInitializer*, 4> NewInits;
4922 bool AnyErrors = Tmpl->isInvalidDecl();
4924 // Instantiate all the initializers.
4925 for (const auto *Init : Tmpl->inits()) {
4926 // Only instantiate written initializers, let Sema re-construct implicit
4928 if (!Init->isWritten())
4931 SourceLocation EllipsisLoc;
4933 if (Init->isPackExpansion()) {
4934 // This is a pack expansion. We should expand it now.
4935 TypeLoc BaseTL = Init->getTypeSourceInfo()->getTypeLoc();
4936 SmallVector<UnexpandedParameterPack, 4> Unexpanded;
4937 collectUnexpandedParameterPacks(BaseTL, Unexpanded);
4938 collectUnexpandedParameterPacks(Init->getInit(), Unexpanded);
4939 bool ShouldExpand = false;
4940 bool RetainExpansion = false;
4941 Optional<unsigned> NumExpansions;
4942 if (CheckParameterPacksForExpansion(Init->getEllipsisLoc(),
4943 BaseTL.getSourceRange(),
4945 TemplateArgs, ShouldExpand,
4949 New->setInvalidDecl();
4952 assert(ShouldExpand && "Partial instantiation of base initializer?");
4954 // Loop over all of the arguments in the argument pack(s),
4955 for (unsigned I = 0; I != *NumExpansions; ++I) {
4956 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
4958 // Instantiate the initializer.
4959 ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs,
4960 /*CXXDirectInit=*/true);
4961 if (TempInit.isInvalid()) {
4966 // Instantiate the base type.
4967 TypeSourceInfo *BaseTInfo = SubstType(Init->getTypeSourceInfo(),
4969 Init->getSourceLocation(),
4970 New->getDeclName());
4976 // Build the initializer.
4977 MemInitResult NewInit = BuildBaseInitializer(BaseTInfo->getType(),
4978 BaseTInfo, TempInit.get(),
4981 if (NewInit.isInvalid()) {
4986 NewInits.push_back(NewInit.get());
4992 // Instantiate the initializer.
4993 ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs,
4994 /*CXXDirectInit=*/true);
4995 if (TempInit.isInvalid()) {
5000 MemInitResult NewInit;
5001 if (Init->isDelegatingInitializer() || Init->isBaseInitializer()) {
5002 TypeSourceInfo *TInfo = SubstType(Init->getTypeSourceInfo(),
5004 Init->getSourceLocation(),
5005 New->getDeclName());
5008 New->setInvalidDecl();
5012 if (Init->isBaseInitializer())
5013 NewInit = BuildBaseInitializer(TInfo->getType(), TInfo, TempInit.get(),
5014 New->getParent(), EllipsisLoc);
5016 NewInit = BuildDelegatingInitializer(TInfo, TempInit.get(),
5017 cast<CXXRecordDecl>(CurContext->getParent()));
5018 } else if (Init->isMemberInitializer()) {
5019 FieldDecl *Member = cast_or_null<FieldDecl>(FindInstantiatedDecl(
5020 Init->getMemberLocation(),
5025 New->setInvalidDecl();
5029 NewInit = BuildMemberInitializer(Member, TempInit.get(),
5030 Init->getSourceLocation());
5031 } else if (Init->isIndirectMemberInitializer()) {
5032 IndirectFieldDecl *IndirectMember =
5033 cast_or_null<IndirectFieldDecl>(FindInstantiatedDecl(
5034 Init->getMemberLocation(),
5035 Init->getIndirectMember(), TemplateArgs));
5037 if (!IndirectMember) {
5039 New->setInvalidDecl();
5043 NewInit = BuildMemberInitializer(IndirectMember, TempInit.get(),
5044 Init->getSourceLocation());
5047 if (NewInit.isInvalid()) {
5049 New->setInvalidDecl();
5051 NewInits.push_back(NewInit.get());
5055 // Assign all the initializers to the new constructor.
5056 ActOnMemInitializers(New,
5057 /*FIXME: ColonLoc */
5063 // TODO: this could be templated if the various decl types used the
5064 // same method name.
5065 static bool isInstantiationOf(ClassTemplateDecl *Pattern,
5066 ClassTemplateDecl *Instance) {
5067 Pattern = Pattern->getCanonicalDecl();
5070 Instance = Instance->getCanonicalDecl();
5071 if (Pattern == Instance) return true;
5072 Instance = Instance->getInstantiatedFromMemberTemplate();
5078 static bool isInstantiationOf(FunctionTemplateDecl *Pattern,
5079 FunctionTemplateDecl *Instance) {
5080 Pattern = Pattern->getCanonicalDecl();
5083 Instance = Instance->getCanonicalDecl();
5084 if (Pattern == Instance) return true;
5085 Instance = Instance->getInstantiatedFromMemberTemplate();
5092 isInstantiationOf(ClassTemplatePartialSpecializationDecl *Pattern,
5093 ClassTemplatePartialSpecializationDecl *Instance) {
5095 = cast<ClassTemplatePartialSpecializationDecl>(Pattern->getCanonicalDecl());
5097 Instance = cast<ClassTemplatePartialSpecializationDecl>(
5098 Instance->getCanonicalDecl());
5099 if (Pattern == Instance)
5101 Instance = Instance->getInstantiatedFromMember();
5107 static bool isInstantiationOf(CXXRecordDecl *Pattern,
5108 CXXRecordDecl *Instance) {
5109 Pattern = Pattern->getCanonicalDecl();
5112 Instance = Instance->getCanonicalDecl();
5113 if (Pattern == Instance) return true;
5114 Instance = Instance->getInstantiatedFromMemberClass();
5120 static bool isInstantiationOf(FunctionDecl *Pattern,
5121 FunctionDecl *Instance) {
5122 Pattern = Pattern->getCanonicalDecl();
5125 Instance = Instance->getCanonicalDecl();
5126 if (Pattern == Instance) return true;
5127 Instance = Instance->getInstantiatedFromMemberFunction();
5133 static bool isInstantiationOf(EnumDecl *Pattern,
5134 EnumDecl *Instance) {
5135 Pattern = Pattern->getCanonicalDecl();
5138 Instance = Instance->getCanonicalDecl();
5139 if (Pattern == Instance) return true;
5140 Instance = Instance->getInstantiatedFromMemberEnum();
5146 static bool isInstantiationOf(UsingShadowDecl *Pattern,
5147 UsingShadowDecl *Instance,
5149 return declaresSameEntity(C.getInstantiatedFromUsingShadowDecl(Instance),
5153 static bool isInstantiationOf(UsingDecl *Pattern, UsingDecl *Instance,
5155 return declaresSameEntity(C.getInstantiatedFromUsingDecl(Instance), Pattern);
5158 template<typename T>
5159 static bool isInstantiationOfUnresolvedUsingDecl(T *Pattern, Decl *Other,
5161 // An unresolved using declaration can instantiate to an unresolved using
5162 // declaration, or to a using declaration or a using declaration pack.
5164 // Multiple declarations can claim to be instantiated from an unresolved
5165 // using declaration if it's a pack expansion. We want the UsingPackDecl
5166 // in that case, not the individual UsingDecls within the pack.
5167 bool OtherIsPackExpansion;
5168 NamedDecl *OtherFrom;
5169 if (auto *OtherUUD = dyn_cast<T>(Other)) {
5170 OtherIsPackExpansion = OtherUUD->isPackExpansion();
5171 OtherFrom = Ctx.getInstantiatedFromUsingDecl(OtherUUD);
5172 } else if (auto *OtherUPD = dyn_cast<UsingPackDecl>(Other)) {
5173 OtherIsPackExpansion = true;
5174 OtherFrom = OtherUPD->getInstantiatedFromUsingDecl();
5175 } else if (auto *OtherUD = dyn_cast<UsingDecl>(Other)) {
5176 OtherIsPackExpansion = false;
5177 OtherFrom = Ctx.getInstantiatedFromUsingDecl(OtherUD);
5181 return Pattern->isPackExpansion() == OtherIsPackExpansion &&
5182 declaresSameEntity(OtherFrom, Pattern);
5185 static bool isInstantiationOfStaticDataMember(VarDecl *Pattern,
5186 VarDecl *Instance) {
5187 assert(Instance->isStaticDataMember());
5189 Pattern = Pattern->getCanonicalDecl();
5192 Instance = Instance->getCanonicalDecl();
5193 if (Pattern == Instance) return true;
5194 Instance = Instance->getInstantiatedFromStaticDataMember();
5200 // Other is the prospective instantiation
5201 // D is the prospective pattern
5202 static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) {
5203 if (auto *UUD = dyn_cast<UnresolvedUsingTypenameDecl>(D))
5204 return isInstantiationOfUnresolvedUsingDecl(UUD, Other, Ctx);
5206 if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(D))
5207 return isInstantiationOfUnresolvedUsingDecl(UUD, Other, Ctx);
5209 if (D->getKind() != Other->getKind())
5212 if (auto *Record = dyn_cast<CXXRecordDecl>(Other))
5213 return isInstantiationOf(cast<CXXRecordDecl>(D), Record);
5215 if (auto *Function = dyn_cast<FunctionDecl>(Other))
5216 return isInstantiationOf(cast<FunctionDecl>(D), Function);
5218 if (auto *Enum = dyn_cast<EnumDecl>(Other))
5219 return isInstantiationOf(cast<EnumDecl>(D), Enum);
5221 if (auto *Var = dyn_cast<VarDecl>(Other))
5222 if (Var->isStaticDataMember())
5223 return isInstantiationOfStaticDataMember(cast<VarDecl>(D), Var);
5225 if (auto *Temp = dyn_cast<ClassTemplateDecl>(Other))
5226 return isInstantiationOf(cast<ClassTemplateDecl>(D), Temp);
5228 if (auto *Temp = dyn_cast<FunctionTemplateDecl>(Other))
5229 return isInstantiationOf(cast<FunctionTemplateDecl>(D), Temp);
5231 if (auto *PartialSpec =
5232 dyn_cast<ClassTemplatePartialSpecializationDecl>(Other))
5233 return isInstantiationOf(cast<ClassTemplatePartialSpecializationDecl>(D),
5236 if (auto *Field = dyn_cast<FieldDecl>(Other)) {
5237 if (!Field->getDeclName()) {
5238 // This is an unnamed field.
5239 return declaresSameEntity(Ctx.getInstantiatedFromUnnamedFieldDecl(Field),
5240 cast<FieldDecl>(D));
5244 if (auto *Using = dyn_cast<UsingDecl>(Other))
5245 return isInstantiationOf(cast<UsingDecl>(D), Using, Ctx);
5247 if (auto *Shadow = dyn_cast<UsingShadowDecl>(Other))
5248 return isInstantiationOf(cast<UsingShadowDecl>(D), Shadow, Ctx);
5250 return D->getDeclName() &&
5251 D->getDeclName() == cast<NamedDecl>(Other)->getDeclName();
5254 template<typename ForwardIterator>
5255 static NamedDecl *findInstantiationOf(ASTContext &Ctx,
5257 ForwardIterator first,
5258 ForwardIterator last) {
5259 for (; first != last; ++first)
5260 if (isInstantiationOf(Ctx, D, *first))
5261 return cast<NamedDecl>(*first);
5266 /// Finds the instantiation of the given declaration context
5267 /// within the current instantiation.
5269 /// \returns NULL if there was an error
5270 DeclContext *Sema::FindInstantiatedContext(SourceLocation Loc, DeclContext* DC,
5271 const MultiLevelTemplateArgumentList &TemplateArgs) {
5272 if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) {
5273 Decl* ID = FindInstantiatedDecl(Loc, D, TemplateArgs, true);
5274 return cast_or_null<DeclContext>(ID);
5278 /// Find the instantiation of the given declaration within the
5279 /// current instantiation.
5281 /// This routine is intended to be used when \p D is a declaration
5282 /// referenced from within a template, that needs to mapped into the
5283 /// corresponding declaration within an instantiation. For example,
5287 /// template<typename T>
5290 /// KnownValue = sizeof(T)
5293 /// bool getKind() const { return KnownValue; }
5296 /// template struct X<int>;
5299 /// In the instantiation of X<int>::getKind(), we need to map the \p
5300 /// EnumConstantDecl for \p KnownValue (which refers to
5301 /// X<T>::<Kind>::KnownValue) to its instantiation (X<int>::<Kind>::KnownValue).
5302 /// \p FindInstantiatedDecl performs this mapping from within the instantiation
5304 NamedDecl *Sema::FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
5305 const MultiLevelTemplateArgumentList &TemplateArgs,
5306 bool FindingInstantiatedContext) {
5307 DeclContext *ParentDC = D->getDeclContext();
5308 // FIXME: Parmeters of pointer to functions (y below) that are themselves
5309 // parameters (p below) can have their ParentDC set to the translation-unit
5310 // - thus we can not consistently check if the ParentDC of such a parameter
5311 // is Dependent or/and a FunctionOrMethod.
5312 // For e.g. this code, during Template argument deduction tries to
5313 // find an instantiated decl for (T y) when the ParentDC for y is
5314 // the translation unit.
5315 // e.g. template <class T> void Foo(auto (*p)(T y) -> decltype(y())) {}
5316 // float baz(float(*)()) { return 0.0; }
5318 // The better fix here is perhaps to ensure that a ParmVarDecl, by the time
5319 // it gets here, always has a FunctionOrMethod as its ParentDC??
5321 // - as long as we have a ParmVarDecl whose parent is non-dependent and
5322 // whose type is not instantiation dependent, do nothing to the decl
5323 // - otherwise find its instantiated decl.
5324 if (isa<ParmVarDecl>(D) && !ParentDC->isDependentContext() &&
5325 !cast<ParmVarDecl>(D)->getType()->isInstantiationDependentType())
5327 if (isa<ParmVarDecl>(D) || isa<NonTypeTemplateParmDecl>(D) ||
5328 isa<TemplateTypeParmDecl>(D) || isa<TemplateTemplateParmDecl>(D) ||
5329 ((ParentDC->isFunctionOrMethod() ||
5330 isa<OMPDeclareReductionDecl>(ParentDC) ||
5331 isa<OMPDeclareMapperDecl>(ParentDC)) &&
5332 ParentDC->isDependentContext()) ||
5333 (isa<CXXRecordDecl>(D) && cast<CXXRecordDecl>(D)->isLambda())) {
5334 // D is a local of some kind. Look into the map of local
5335 // declarations to their instantiations.
5336 if (CurrentInstantiationScope) {
5337 if (auto Found = CurrentInstantiationScope->findInstantiationOf(D)) {
5338 if (Decl *FD = Found->dyn_cast<Decl *>())
5339 return cast<NamedDecl>(FD);
5341 int PackIdx = ArgumentPackSubstitutionIndex;
5342 assert(PackIdx != -1 &&
5343 "found declaration pack but not pack expanding");
5344 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
5345 return cast<NamedDecl>((*Found->get<DeclArgumentPack *>())[PackIdx]);
5349 // If we're performing a partial substitution during template argument
5350 // deduction, we may not have values for template parameters yet. They
5351 // just map to themselves.
5352 if (isa<NonTypeTemplateParmDecl>(D) || isa<TemplateTypeParmDecl>(D) ||
5353 isa<TemplateTemplateParmDecl>(D))
5356 if (D->isInvalidDecl())
5359 // Normally this function only searches for already instantiated declaration
5360 // however we have to make an exclusion for local types used before
5361 // definition as in the code:
5363 // template<typename T> void f1() {
5364 // void g1(struct x1);
5368 // In this case instantiation of the type of 'g1' requires definition of
5369 // 'x1', which is defined later. Error recovery may produce an enum used
5370 // before definition. In these cases we need to instantiate relevant
5371 // declarations here.
5372 bool NeedInstantiate = false;
5373 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
5374 NeedInstantiate = RD->isLocalClass();
5376 NeedInstantiate = isa<EnumDecl>(D);
5377 if (NeedInstantiate) {
5378 Decl *Inst = SubstDecl(D, CurContext, TemplateArgs);
5379 CurrentInstantiationScope->InstantiatedLocal(D, Inst);
5380 return cast<TypeDecl>(Inst);
5383 // If we didn't find the decl, then we must have a label decl that hasn't
5384 // been found yet. Lazily instantiate it and return it now.
5385 assert(isa<LabelDecl>(D));
5387 Decl *Inst = SubstDecl(D, CurContext, TemplateArgs);
5388 assert(Inst && "Failed to instantiate label??");
5390 CurrentInstantiationScope->InstantiatedLocal(D, Inst);
5391 return cast<LabelDecl>(Inst);
5394 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
5395 if (!Record->isDependentContext())
5398 // Determine whether this record is the "templated" declaration describing
5399 // a class template or class template partial specialization.
5400 ClassTemplateDecl *ClassTemplate = Record->getDescribedClassTemplate();
5402 ClassTemplate = ClassTemplate->getCanonicalDecl();
5403 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
5404 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record))
5405 ClassTemplate = PartialSpec->getSpecializedTemplate()->getCanonicalDecl();
5407 // Walk the current context to find either the record or an instantiation of
5409 DeclContext *DC = CurContext;
5410 while (!DC->isFileContext()) {
5411 // If we're performing substitution while we're inside the template
5412 // definition, we'll find our own context. We're done.
5413 if (DC->Equals(Record))
5416 if (CXXRecordDecl *InstRecord = dyn_cast<CXXRecordDecl>(DC)) {
5417 // Check whether we're in the process of instantiating a class template
5418 // specialization of the template we're mapping.
5419 if (ClassTemplateSpecializationDecl *InstSpec
5420 = dyn_cast<ClassTemplateSpecializationDecl>(InstRecord)){
5421 ClassTemplateDecl *SpecTemplate = InstSpec->getSpecializedTemplate();
5422 if (ClassTemplate && isInstantiationOf(ClassTemplate, SpecTemplate))
5426 // Check whether we're in the process of instantiating a member class.
5427 if (isInstantiationOf(Record, InstRecord))
5431 // Move to the outer template scope.
5432 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC)) {
5433 if (FD->getFriendObjectKind() && FD->getDeclContext()->isFileContext()){
5434 DC = FD->getLexicalDeclContext();
5437 // An implicit deduction guide acts as if it's within the class template
5438 // specialization described by its name and first N template params.
5439 auto *Guide = dyn_cast<CXXDeductionGuideDecl>(FD);
5440 if (Guide && Guide->isImplicit()) {
5441 TemplateDecl *TD = Guide->getDeducedTemplate();
5442 // Convert the arguments to an "as-written" list.
5443 TemplateArgumentListInfo Args(Loc, Loc);
5444 for (TemplateArgument Arg : TemplateArgs.getInnermost().take_front(
5445 TD->getTemplateParameters()->size())) {
5446 ArrayRef<TemplateArgument> Unpacked(Arg);
5447 if (Arg.getKind() == TemplateArgument::Pack)
5448 Unpacked = Arg.pack_elements();
5449 for (TemplateArgument UnpackedArg : Unpacked)
5451 getTrivialTemplateArgumentLoc(UnpackedArg, QualType(), Loc));
5453 QualType T = CheckTemplateIdType(TemplateName(TD), Loc, Args);
5456 auto *SubstRecord = T->getAsCXXRecordDecl();
5457 assert(SubstRecord && "class template id not a class type?");
5458 // Check that this template-id names the primary template and not a
5459 // partial or explicit specialization. (In the latter cases, it's
5460 // meaningless to attempt to find an instantiation of D within the
5462 // FIXME: The standard doesn't say what should happen here.
5463 if (FindingInstantiatedContext &&
5464 usesPartialOrExplicitSpecialization(
5465 Loc, cast<ClassTemplateSpecializationDecl>(SubstRecord))) {
5466 Diag(Loc, diag::err_specialization_not_primary_template)
5467 << T << (SubstRecord->getTemplateSpecializationKind() ==
5468 TSK_ExplicitSpecialization);
5476 DC = DC->getParent();
5479 // Fall through to deal with other dependent record types (e.g.,
5480 // anonymous unions in class templates).
5483 if (!ParentDC->isDependentContext())
5486 ParentDC = FindInstantiatedContext(Loc, ParentDC, TemplateArgs);
5490 if (ParentDC != D->getDeclContext()) {
5491 // We performed some kind of instantiation in the parent context,
5492 // so now we need to look into the instantiated parent context to
5493 // find the instantiation of the declaration D.
5495 // If our context used to be dependent, we may need to instantiate
5496 // it before performing lookup into that context.
5497 bool IsBeingInstantiated = false;
5498 if (CXXRecordDecl *Spec = dyn_cast<CXXRecordDecl>(ParentDC)) {
5499 if (!Spec->isDependentContext()) {
5500 QualType T = Context.getTypeDeclType(Spec);
5501 const RecordType *Tag = T->getAs<RecordType>();
5502 assert(Tag && "type of non-dependent record is not a RecordType");
5503 if (Tag->isBeingDefined())
5504 IsBeingInstantiated = true;
5505 if (!Tag->isBeingDefined() &&
5506 RequireCompleteType(Loc, T, diag::err_incomplete_type))
5509 ParentDC = Tag->getDecl();
5513 NamedDecl *Result = nullptr;
5514 // FIXME: If the name is a dependent name, this lookup won't necessarily
5515 // find it. Does that ever matter?
5516 if (auto Name = D->getDeclName()) {
5517 DeclarationNameInfo NameInfo(Name, D->getLocation());
5518 DeclarationNameInfo NewNameInfo =
5519 SubstDeclarationNameInfo(NameInfo, TemplateArgs);
5520 Name = NewNameInfo.getName();
5523 DeclContext::lookup_result Found = ParentDC->lookup(Name);
5525 if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(D)) {
5526 VarTemplateDecl *Templ = cast_or_null<VarTemplateDecl>(
5527 findInstantiationOf(Context, VTSD->getSpecializedTemplate(),
5528 Found.begin(), Found.end()));
5531 Result = getVarTemplateSpecialization(
5532 Templ, &VTSD->getTemplateArgsInfo(), NewNameInfo, SourceLocation());
5534 Result = findInstantiationOf(Context, D, Found.begin(), Found.end());
5536 // Since we don't have a name for the entity we're looking for,
5537 // our only option is to walk through all of the declarations to
5538 // find that name. This will occur in a few cases:
5540 // - anonymous struct/union within a template
5541 // - unnamed class/struct/union/enum within a template
5543 // FIXME: Find a better way to find these instantiations!
5544 Result = findInstantiationOf(Context, D,
5545 ParentDC->decls_begin(),
5546 ParentDC->decls_end());
5550 if (isa<UsingShadowDecl>(D)) {
5551 // UsingShadowDecls can instantiate to nothing because of using hiding.
5552 } else if (Diags.hasErrorOccurred()) {
5553 // We've already complained about something, so most likely this
5554 // declaration failed to instantiate. There's no point in complaining
5555 // further, since this is normal in invalid code.
5556 } else if (IsBeingInstantiated) {
5557 // The class in which this member exists is currently being
5558 // instantiated, and we haven't gotten around to instantiating this
5559 // member yet. This can happen when the code uses forward declarations
5560 // of member classes, and introduces ordering dependencies via
5561 // template instantiation.
5562 Diag(Loc, diag::err_member_not_yet_instantiated)
5564 << Context.getTypeDeclType(cast<CXXRecordDecl>(ParentDC));
5565 Diag(D->getLocation(), diag::note_non_instantiated_member_here);
5566 } else if (EnumConstantDecl *ED = dyn_cast<EnumConstantDecl>(D)) {
5567 // This enumeration constant was found when the template was defined,
5568 // but can't be found in the instantiation. This can happen if an
5569 // unscoped enumeration member is explicitly specialized.
5570 EnumDecl *Enum = cast<EnumDecl>(ED->getLexicalDeclContext());
5571 EnumDecl *Spec = cast<EnumDecl>(FindInstantiatedDecl(Loc, Enum,
5573 assert(Spec->getTemplateSpecializationKind() ==
5574 TSK_ExplicitSpecialization);
5575 Diag(Loc, diag::err_enumerator_does_not_exist)
5577 << Context.getTypeDeclType(cast<TypeDecl>(Spec->getDeclContext()));
5578 Diag(Spec->getLocation(), diag::note_enum_specialized_here)
5579 << Context.getTypeDeclType(Spec);
5581 // We should have found something, but didn't.
5582 llvm_unreachable("Unable to find instantiation of declaration!");
5592 /// Performs template instantiation for all implicit template
5593 /// instantiations we have seen until this point.
5594 void Sema::PerformPendingInstantiations(bool LocalOnly) {
5595 while (!PendingLocalImplicitInstantiations.empty() ||
5596 (!LocalOnly && !PendingInstantiations.empty())) {
5597 PendingImplicitInstantiation Inst;
5599 if (PendingLocalImplicitInstantiations.empty()) {
5600 Inst = PendingInstantiations.front();
5601 PendingInstantiations.pop_front();
5603 Inst = PendingLocalImplicitInstantiations.front();
5604 PendingLocalImplicitInstantiations.pop_front();
5607 // Instantiate function definitions
5608 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) {
5609 bool DefinitionRequired = Function->getTemplateSpecializationKind() ==
5610 TSK_ExplicitInstantiationDefinition;
5611 if (Function->isMultiVersion()) {
5612 getASTContext().forEachMultiversionedFunctionVersion(
5613 Function, [this, Inst, DefinitionRequired](FunctionDecl *CurFD) {
5614 InstantiateFunctionDefinition(/*FIXME:*/ Inst.second, CurFD, true,
5615 DefinitionRequired, true);
5616 if (CurFD->isDefined())
5617 CurFD->setInstantiationIsPending(false);
5620 InstantiateFunctionDefinition(/*FIXME:*/ Inst.second, Function, true,
5621 DefinitionRequired, true);
5622 if (Function->isDefined())
5623 Function->setInstantiationIsPending(false);
5628 // Instantiate variable definitions
5629 VarDecl *Var = cast<VarDecl>(Inst.first);
5631 assert((Var->isStaticDataMember() ||
5632 isa<VarTemplateSpecializationDecl>(Var)) &&
5633 "Not a static data member, nor a variable template"
5634 " specialization?");
5636 // Don't try to instantiate declarations if the most recent redeclaration
5638 if (Var->getMostRecentDecl()->isInvalidDecl())
5641 // Check if the most recent declaration has changed the specialization kind
5642 // and removed the need for implicit instantiation.
5643 switch (Var->getMostRecentDecl()
5644 ->getTemplateSpecializationKindForInstantiation()) {
5645 case TSK_Undeclared:
5646 llvm_unreachable("Cannot instantitiate an undeclared specialization.");
5647 case TSK_ExplicitInstantiationDeclaration:
5648 case TSK_ExplicitSpecialization:
5649 continue; // No longer need to instantiate this type.
5650 case TSK_ExplicitInstantiationDefinition:
5651 // We only need an instantiation if the pending instantiation *is* the
5652 // explicit instantiation.
5653 if (Var != Var->getMostRecentDecl())
5656 case TSK_ImplicitInstantiation:
5660 PrettyDeclStackTraceEntry CrashInfo(Context, Var, SourceLocation(),
5661 "instantiating variable definition");
5662 bool DefinitionRequired = Var->getTemplateSpecializationKind() ==
5663 TSK_ExplicitInstantiationDefinition;
5665 // Instantiate static data member definitions or variable template
5667 InstantiateVariableDefinition(/*FIXME:*/ Inst.second, Var, true,
5668 DefinitionRequired, true);
5672 void Sema::PerformDependentDiagnostics(const DeclContext *Pattern,
5673 const MultiLevelTemplateArgumentList &TemplateArgs) {
5674 for (auto DD : Pattern->ddiags()) {
5675 switch (DD->getKind()) {
5676 case DependentDiagnostic::Access:
5677 HandleDependentAccessCheck(*DD, TemplateArgs);