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(Aligned->getLocation(), New, Result.getAs<Expr>(),
90 Aligned->getSpellingListIndex(), IsPackExpansion);
92 TypeSourceInfo *Result = S.SubstType(Aligned->getAlignmentType(),
93 TemplateArgs, Aligned->getLocation(),
96 S.AddAlignedAttr(Aligned->getLocation(), New, Result,
97 Aligned->getSpellingListIndex(), IsPackExpansion);
101 static void instantiateDependentAlignedAttr(
102 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
103 const AlignedAttr *Aligned, Decl *New) {
104 if (!Aligned->isPackExpansion()) {
105 instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, false);
109 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
110 if (Aligned->isAlignmentExpr())
111 S.collectUnexpandedParameterPacks(Aligned->getAlignmentExpr(),
114 S.collectUnexpandedParameterPacks(Aligned->getAlignmentType()->getTypeLoc(),
116 assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
118 // Determine whether we can expand this attribute pack yet.
119 bool Expand = true, RetainExpansion = false;
120 Optional<unsigned> NumExpansions;
121 // FIXME: Use the actual location of the ellipsis.
122 SourceLocation EllipsisLoc = Aligned->getLocation();
123 if (S.CheckParameterPacksForExpansion(EllipsisLoc, Aligned->getRange(),
124 Unexpanded, TemplateArgs, Expand,
125 RetainExpansion, NumExpansions))
129 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(S, -1);
130 instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, true);
132 for (unsigned I = 0; I != *NumExpansions; ++I) {
133 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(S, I);
134 instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, false);
139 static void instantiateDependentAssumeAlignedAttr(
140 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
141 const AssumeAlignedAttr *Aligned, Decl *New) {
142 // The alignment expression is a constant expression.
143 EnterExpressionEvaluationContext Unevaluated(
144 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
146 Expr *E, *OE = nullptr;
147 ExprResult Result = S.SubstExpr(Aligned->getAlignment(), TemplateArgs);
148 if (Result.isInvalid())
150 E = Result.getAs<Expr>();
152 if (Aligned->getOffset()) {
153 Result = S.SubstExpr(Aligned->getOffset(), TemplateArgs);
154 if (Result.isInvalid())
156 OE = Result.getAs<Expr>();
159 S.AddAssumeAlignedAttr(Aligned->getLocation(), New, E, OE,
160 Aligned->getSpellingListIndex());
163 static void instantiateDependentAlignValueAttr(
164 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
165 const AlignValueAttr *Aligned, Decl *New) {
166 // The alignment expression is a constant expression.
167 EnterExpressionEvaluationContext Unevaluated(
168 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
169 ExprResult Result = S.SubstExpr(Aligned->getAlignment(), TemplateArgs);
170 if (!Result.isInvalid())
171 S.AddAlignValueAttr(Aligned->getLocation(), New, Result.getAs<Expr>(),
172 Aligned->getSpellingListIndex());
175 static void instantiateDependentAllocAlignAttr(
176 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
177 const AllocAlignAttr *Align, Decl *New) {
178 Expr *Param = IntegerLiteral::Create(
180 llvm::APInt(64, Align->getParamIndex().getSourceIndex()),
181 S.getASTContext().UnsignedLongLongTy, Align->getLocation());
182 S.AddAllocAlignAttr(Align->getLocation(), New, Param,
183 Align->getSpellingListIndex());
186 static Expr *instantiateDependentFunctionAttrCondition(
187 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
188 const Attr *A, Expr *OldCond, const Decl *Tmpl, FunctionDecl *New) {
189 Expr *Cond = nullptr;
191 Sema::ContextRAII SwitchContext(S, New);
192 EnterExpressionEvaluationContext Unevaluated(
193 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
194 ExprResult Result = S.SubstExpr(OldCond, TemplateArgs);
195 if (Result.isInvalid())
197 Cond = Result.getAs<Expr>();
199 if (!Cond->isTypeDependent()) {
200 ExprResult Converted = S.PerformContextuallyConvertToBool(Cond);
201 if (Converted.isInvalid())
203 Cond = Converted.get();
206 SmallVector<PartialDiagnosticAt, 8> Diags;
207 if (OldCond->isValueDependent() && !Cond->isValueDependent() &&
208 !Expr::isPotentialConstantExprUnevaluated(Cond, New, Diags)) {
209 S.Diag(A->getLocation(), diag::err_attr_cond_never_constant_expr) << A;
210 for (const auto &P : Diags)
211 S.Diag(P.first, P.second);
217 static void instantiateDependentEnableIfAttr(
218 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
219 const EnableIfAttr *EIA, const Decl *Tmpl, FunctionDecl *New) {
220 Expr *Cond = instantiateDependentFunctionAttrCondition(
221 S, TemplateArgs, EIA, EIA->getCond(), Tmpl, New);
224 New->addAttr(new (S.getASTContext()) EnableIfAttr(
225 EIA->getLocation(), S.getASTContext(), Cond, EIA->getMessage(),
226 EIA->getSpellingListIndex()));
229 static void instantiateDependentDiagnoseIfAttr(
230 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
231 const DiagnoseIfAttr *DIA, const Decl *Tmpl, FunctionDecl *New) {
232 Expr *Cond = instantiateDependentFunctionAttrCondition(
233 S, TemplateArgs, DIA, DIA->getCond(), Tmpl, New);
236 New->addAttr(new (S.getASTContext()) DiagnoseIfAttr(
237 DIA->getLocation(), S.getASTContext(), Cond, DIA->getMessage(),
238 DIA->getDiagnosticType(), DIA->getArgDependent(), New,
239 DIA->getSpellingListIndex()));
242 // Constructs and adds to New a new instance of CUDALaunchBoundsAttr using
243 // template A as the base and arguments from TemplateArgs.
244 static void instantiateDependentCUDALaunchBoundsAttr(
245 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
246 const CUDALaunchBoundsAttr &Attr, Decl *New) {
247 // The alignment expression is a constant expression.
248 EnterExpressionEvaluationContext Unevaluated(
249 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
251 ExprResult Result = S.SubstExpr(Attr.getMaxThreads(), TemplateArgs);
252 if (Result.isInvalid())
254 Expr *MaxThreads = Result.getAs<Expr>();
256 Expr *MinBlocks = nullptr;
257 if (Attr.getMinBlocks()) {
258 Result = S.SubstExpr(Attr.getMinBlocks(), TemplateArgs);
259 if (Result.isInvalid())
261 MinBlocks = Result.getAs<Expr>();
264 S.AddLaunchBoundsAttr(Attr.getLocation(), New, MaxThreads, MinBlocks,
265 Attr.getSpellingListIndex());
269 instantiateDependentModeAttr(Sema &S,
270 const MultiLevelTemplateArgumentList &TemplateArgs,
271 const ModeAttr &Attr, Decl *New) {
272 S.AddModeAttr(Attr.getRange(), New, Attr.getMode(),
273 Attr.getSpellingListIndex(), /*InInstantiation=*/true);
276 /// Instantiation of 'declare simd' attribute and its arguments.
277 static void instantiateOMPDeclareSimdDeclAttr(
278 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
279 const OMPDeclareSimdDeclAttr &Attr, Decl *New) {
280 // Allow 'this' in clauses with varlists.
281 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(New))
282 New = FTD->getTemplatedDecl();
283 auto *FD = cast<FunctionDecl>(New);
284 auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(FD->getDeclContext());
285 SmallVector<Expr *, 4> Uniforms, Aligneds, Alignments, Linears, Steps;
286 SmallVector<unsigned, 4> LinModifiers;
288 auto SubstExpr = [&](Expr *E) -> ExprResult {
289 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
290 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
291 Sema::ContextRAII SavedContext(S, FD);
292 LocalInstantiationScope Local(S);
293 if (FD->getNumParams() > PVD->getFunctionScopeIndex())
294 Local.InstantiatedLocal(
295 PVD, FD->getParamDecl(PVD->getFunctionScopeIndex()));
296 return S.SubstExpr(E, TemplateArgs);
298 Sema::CXXThisScopeRAII ThisScope(S, ThisContext, Qualifiers(),
299 FD->isCXXInstanceMember());
300 return S.SubstExpr(E, TemplateArgs);
303 // Substitute a single OpenMP clause, which is a potentially-evaluated
305 auto Subst = [&](Expr *E) -> ExprResult {
306 EnterExpressionEvaluationContext Evaluated(
307 S, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
308 ExprResult Res = SubstExpr(E);
311 return S.ActOnFinishFullExpr(Res.get(), false);
315 if (auto *E = Attr.getSimdlen())
318 if (Attr.uniforms_size() > 0) {
319 for(auto *E : Attr.uniforms()) {
320 ExprResult Inst = Subst(E);
321 if (Inst.isInvalid())
323 Uniforms.push_back(Inst.get());
327 auto AI = Attr.alignments_begin();
328 for (auto *E : Attr.aligneds()) {
329 ExprResult Inst = Subst(E);
330 if (Inst.isInvalid())
332 Aligneds.push_back(Inst.get());
335 Inst = S.SubstExpr(*AI, TemplateArgs);
336 Alignments.push_back(Inst.get());
340 auto SI = Attr.steps_begin();
341 for (auto *E : Attr.linears()) {
342 ExprResult Inst = Subst(E);
343 if (Inst.isInvalid())
345 Linears.push_back(Inst.get());
348 Inst = S.SubstExpr(*SI, TemplateArgs);
349 Steps.push_back(Inst.get());
352 LinModifiers.append(Attr.modifiers_begin(), Attr.modifiers_end());
353 (void)S.ActOnOpenMPDeclareSimdDirective(
354 S.ConvertDeclToDeclGroup(New), Attr.getBranchState(), Simdlen.get(),
355 Uniforms, Aligneds, Alignments, Linears, LinModifiers, Steps,
359 static void instantiateDependentAMDGPUFlatWorkGroupSizeAttr(
360 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
361 const AMDGPUFlatWorkGroupSizeAttr &Attr, Decl *New) {
362 // Both min and max expression are constant expressions.
363 EnterExpressionEvaluationContext Unevaluated(
364 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
366 ExprResult Result = S.SubstExpr(Attr.getMin(), TemplateArgs);
367 if (Result.isInvalid())
369 Expr *MinExpr = Result.getAs<Expr>();
371 Result = S.SubstExpr(Attr.getMax(), TemplateArgs);
372 if (Result.isInvalid())
374 Expr *MaxExpr = Result.getAs<Expr>();
376 S.addAMDGPUFlatWorkGroupSizeAttr(Attr.getLocation(), New, MinExpr, MaxExpr,
377 Attr.getSpellingListIndex());
380 static ExplicitSpecifier
381 instantiateExplicitSpecifier(Sema &S,
382 const MultiLevelTemplateArgumentList &TemplateArgs,
383 ExplicitSpecifier ES, FunctionDecl *New) {
386 Expr *OldCond = ES.getExpr();
387 Expr *Cond = nullptr;
389 EnterExpressionEvaluationContext Unevaluated(
390 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
391 ExprResult SubstResult = S.SubstExpr(OldCond, TemplateArgs);
392 if (SubstResult.isInvalid()) {
393 return ExplicitSpecifier::Invalid();
395 Cond = SubstResult.get();
397 ExplicitSpecifier Result(Cond, ES.getKind());
398 if (!Cond->isTypeDependent())
399 S.tryResolveExplicitSpecifier(Result);
403 static void instantiateDependentAMDGPUWavesPerEUAttr(
404 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
405 const AMDGPUWavesPerEUAttr &Attr, Decl *New) {
406 // Both min and max expression are constant expressions.
407 EnterExpressionEvaluationContext Unevaluated(
408 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
410 ExprResult Result = S.SubstExpr(Attr.getMin(), TemplateArgs);
411 if (Result.isInvalid())
413 Expr *MinExpr = Result.getAs<Expr>();
415 Expr *MaxExpr = nullptr;
416 if (auto Max = Attr.getMax()) {
417 Result = S.SubstExpr(Max, TemplateArgs);
418 if (Result.isInvalid())
420 MaxExpr = Result.getAs<Expr>();
423 S.addAMDGPUWavesPerEUAttr(Attr.getLocation(), New, MinExpr, MaxExpr,
424 Attr.getSpellingListIndex());
427 void Sema::InstantiateAttrsForDecl(
428 const MultiLevelTemplateArgumentList &TemplateArgs, const Decl *Tmpl,
429 Decl *New, LateInstantiatedAttrVec *LateAttrs,
430 LocalInstantiationScope *OuterMostScope) {
431 if (NamedDecl *ND = dyn_cast<NamedDecl>(New)) {
432 for (const auto *TmplAttr : Tmpl->attrs()) {
433 // FIXME: If any of the special case versions from InstantiateAttrs become
434 // applicable to template declaration, we'll need to add them here.
435 CXXThisScopeRAII ThisScope(
436 *this, dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext()),
437 Qualifiers(), ND->isCXXInstanceMember());
439 Attr *NewAttr = sema::instantiateTemplateAttributeForDecl(
440 TmplAttr, Context, *this, TemplateArgs);
442 New->addAttr(NewAttr);
447 static Sema::RetainOwnershipKind
448 attrToRetainOwnershipKind(const Attr *A) {
449 switch (A->getKind()) {
450 case clang::attr::CFConsumed:
451 return Sema::RetainOwnershipKind::CF;
452 case clang::attr::OSConsumed:
453 return Sema::RetainOwnershipKind::OS;
454 case clang::attr::NSConsumed:
455 return Sema::RetainOwnershipKind::NS;
457 llvm_unreachable("Wrong argument supplied");
461 void Sema::InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs,
462 const Decl *Tmpl, Decl *New,
463 LateInstantiatedAttrVec *LateAttrs,
464 LocalInstantiationScope *OuterMostScope) {
465 for (const auto *TmplAttr : Tmpl->attrs()) {
466 // FIXME: This should be generalized to more than just the AlignedAttr.
467 const AlignedAttr *Aligned = dyn_cast<AlignedAttr>(TmplAttr);
468 if (Aligned && Aligned->isAlignmentDependent()) {
469 instantiateDependentAlignedAttr(*this, TemplateArgs, Aligned, New);
473 const AssumeAlignedAttr *AssumeAligned = dyn_cast<AssumeAlignedAttr>(TmplAttr);
475 instantiateDependentAssumeAlignedAttr(*this, TemplateArgs, AssumeAligned, New);
479 const AlignValueAttr *AlignValue = dyn_cast<AlignValueAttr>(TmplAttr);
481 instantiateDependentAlignValueAttr(*this, TemplateArgs, AlignValue, New);
485 if (const auto *AllocAlign = dyn_cast<AllocAlignAttr>(TmplAttr)) {
486 instantiateDependentAllocAlignAttr(*this, TemplateArgs, AllocAlign, New);
491 if (const auto *EnableIf = dyn_cast<EnableIfAttr>(TmplAttr)) {
492 instantiateDependentEnableIfAttr(*this, TemplateArgs, EnableIf, Tmpl,
493 cast<FunctionDecl>(New));
497 if (const auto *DiagnoseIf = dyn_cast<DiagnoseIfAttr>(TmplAttr)) {
498 instantiateDependentDiagnoseIfAttr(*this, TemplateArgs, DiagnoseIf, Tmpl,
499 cast<FunctionDecl>(New));
503 if (const CUDALaunchBoundsAttr *CUDALaunchBounds =
504 dyn_cast<CUDALaunchBoundsAttr>(TmplAttr)) {
505 instantiateDependentCUDALaunchBoundsAttr(*this, TemplateArgs,
506 *CUDALaunchBounds, New);
510 if (const ModeAttr *Mode = dyn_cast<ModeAttr>(TmplAttr)) {
511 instantiateDependentModeAttr(*this, TemplateArgs, *Mode, New);
515 if (const auto *OMPAttr = dyn_cast<OMPDeclareSimdDeclAttr>(TmplAttr)) {
516 instantiateOMPDeclareSimdDeclAttr(*this, TemplateArgs, *OMPAttr, New);
520 if (const AMDGPUFlatWorkGroupSizeAttr *AMDGPUFlatWorkGroupSize =
521 dyn_cast<AMDGPUFlatWorkGroupSizeAttr>(TmplAttr)) {
522 instantiateDependentAMDGPUFlatWorkGroupSizeAttr(
523 *this, TemplateArgs, *AMDGPUFlatWorkGroupSize, New);
526 if (const AMDGPUWavesPerEUAttr *AMDGPUFlatWorkGroupSize =
527 dyn_cast<AMDGPUWavesPerEUAttr>(TmplAttr)) {
528 instantiateDependentAMDGPUWavesPerEUAttr(*this, TemplateArgs,
529 *AMDGPUFlatWorkGroupSize, New);
532 // Existing DLL attribute on the instantiation takes precedence.
533 if (TmplAttr->getKind() == attr::DLLExport ||
534 TmplAttr->getKind() == attr::DLLImport) {
535 if (New->hasAttr<DLLExportAttr>() || New->hasAttr<DLLImportAttr>()) {
540 if (auto ABIAttr = dyn_cast<ParameterABIAttr>(TmplAttr)) {
541 AddParameterABIAttr(ABIAttr->getRange(), New, ABIAttr->getABI(),
542 ABIAttr->getSpellingListIndex());
546 if (isa<NSConsumedAttr>(TmplAttr) || isa<OSConsumedAttr>(TmplAttr) ||
547 isa<CFConsumedAttr>(TmplAttr)) {
548 AddXConsumedAttr(New, TmplAttr->getRange(),
549 TmplAttr->getSpellingListIndex(),
550 attrToRetainOwnershipKind(TmplAttr),
551 /*template instantiation=*/true);
555 assert(!TmplAttr->isPackExpansion());
556 if (TmplAttr->isLateParsed() && LateAttrs) {
557 // Late parsed attributes must be instantiated and attached after the
558 // enclosing class has been instantiated. See Sema::InstantiateClass.
559 LocalInstantiationScope *Saved = nullptr;
560 if (CurrentInstantiationScope)
561 Saved = CurrentInstantiationScope->cloneScopes(OuterMostScope);
562 LateAttrs->push_back(LateInstantiatedAttribute(TmplAttr, Saved, New));
564 // Allow 'this' within late-parsed attributes.
565 NamedDecl *ND = dyn_cast<NamedDecl>(New);
566 CXXRecordDecl *ThisContext =
567 dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext());
568 CXXThisScopeRAII ThisScope(*this, ThisContext, Qualifiers(),
569 ND && ND->isCXXInstanceMember());
571 Attr *NewAttr = sema::instantiateTemplateAttribute(TmplAttr, Context,
572 *this, TemplateArgs);
574 New->addAttr(NewAttr);
579 /// Get the previous declaration of a declaration for the purposes of template
580 /// instantiation. If this finds a previous declaration, then the previous
581 /// declaration of the instantiation of D should be an instantiation of the
582 /// result of this function.
583 template<typename DeclT>
584 static DeclT *getPreviousDeclForInstantiation(DeclT *D) {
585 DeclT *Result = D->getPreviousDecl();
587 // If the declaration is within a class, and the previous declaration was
588 // merged from a different definition of that class, then we don't have a
589 // previous declaration for the purpose of template instantiation.
590 if (Result && isa<CXXRecordDecl>(D->getDeclContext()) &&
591 D->getLexicalDeclContext() != Result->getLexicalDeclContext())
598 TemplateDeclInstantiator::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
599 llvm_unreachable("Translation units cannot be instantiated");
603 TemplateDeclInstantiator::VisitPragmaCommentDecl(PragmaCommentDecl *D) {
604 llvm_unreachable("pragma comment cannot be instantiated");
607 Decl *TemplateDeclInstantiator::VisitPragmaDetectMismatchDecl(
608 PragmaDetectMismatchDecl *D) {
609 llvm_unreachable("pragma comment cannot be instantiated");
613 TemplateDeclInstantiator::VisitExternCContextDecl(ExternCContextDecl *D) {
614 llvm_unreachable("extern \"C\" context cannot be instantiated");
618 TemplateDeclInstantiator::VisitLabelDecl(LabelDecl *D) {
619 LabelDecl *Inst = LabelDecl::Create(SemaRef.Context, Owner, D->getLocation(),
621 Owner->addDecl(Inst);
626 TemplateDeclInstantiator::VisitNamespaceDecl(NamespaceDecl *D) {
627 llvm_unreachable("Namespaces cannot be instantiated");
631 TemplateDeclInstantiator::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
632 NamespaceAliasDecl *Inst
633 = NamespaceAliasDecl::Create(SemaRef.Context, Owner,
634 D->getNamespaceLoc(),
637 D->getQualifierLoc(),
638 D->getTargetNameLoc(),
640 Owner->addDecl(Inst);
644 Decl *TemplateDeclInstantiator::InstantiateTypedefNameDecl(TypedefNameDecl *D,
646 bool Invalid = false;
647 TypeSourceInfo *DI = D->getTypeSourceInfo();
648 if (DI->getType()->isInstantiationDependentType() ||
649 DI->getType()->isVariablyModifiedType()) {
650 DI = SemaRef.SubstType(DI, TemplateArgs,
651 D->getLocation(), D->getDeclName());
654 DI = SemaRef.Context.getTrivialTypeSourceInfo(SemaRef.Context.IntTy);
657 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
660 // HACK: g++ has a bug where it gets the value kind of ?: wrong.
661 // libstdc++ relies upon this bug in its implementation of common_type.
662 // If we happen to be processing that implementation, fake up the g++ ?:
663 // semantics. See LWG issue 2141 for more information on the bug.
664 const DecltypeType *DT = DI->getType()->getAs<DecltypeType>();
665 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D->getDeclContext());
666 if (DT && RD && isa<ConditionalOperator>(DT->getUnderlyingExpr()) &&
667 DT->isReferenceType() &&
668 RD->getEnclosingNamespaceContext() == SemaRef.getStdNamespace() &&
669 RD->getIdentifier() && RD->getIdentifier()->isStr("common_type") &&
670 D->getIdentifier() && D->getIdentifier()->isStr("type") &&
671 SemaRef.getSourceManager().isInSystemHeader(D->getBeginLoc()))
672 // Fold it to the (non-reference) type which g++ would have produced.
673 DI = SemaRef.Context.getTrivialTypeSourceInfo(
674 DI->getType().getNonReferenceType());
676 // Create the new typedef
677 TypedefNameDecl *Typedef;
679 Typedef = TypeAliasDecl::Create(SemaRef.Context, Owner, D->getBeginLoc(),
680 D->getLocation(), D->getIdentifier(), DI);
682 Typedef = TypedefDecl::Create(SemaRef.Context, Owner, D->getBeginLoc(),
683 D->getLocation(), D->getIdentifier(), DI);
685 Typedef->setInvalidDecl();
687 // If the old typedef was the name for linkage purposes of an anonymous
688 // tag decl, re-establish that relationship for the new typedef.
689 if (const TagType *oldTagType = D->getUnderlyingType()->getAs<TagType>()) {
690 TagDecl *oldTag = oldTagType->getDecl();
691 if (oldTag->getTypedefNameForAnonDecl() == D && !Invalid) {
692 TagDecl *newTag = DI->getType()->castAs<TagType>()->getDecl();
693 assert(!newTag->hasNameForLinkage());
694 newTag->setTypedefNameForAnonDecl(Typedef);
698 if (TypedefNameDecl *Prev = getPreviousDeclForInstantiation(D)) {
699 NamedDecl *InstPrev = SemaRef.FindInstantiatedDecl(D->getLocation(), Prev,
704 TypedefNameDecl *InstPrevTypedef = cast<TypedefNameDecl>(InstPrev);
706 // If the typedef types are not identical, reject them.
707 SemaRef.isIncompatibleTypedef(InstPrevTypedef, Typedef);
709 Typedef->setPreviousDecl(InstPrevTypedef);
712 SemaRef.InstantiateAttrs(TemplateArgs, D, Typedef);
714 Typedef->setAccess(D->getAccess());
719 Decl *TemplateDeclInstantiator::VisitTypedefDecl(TypedefDecl *D) {
720 Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/false);
722 Owner->addDecl(Typedef);
726 Decl *TemplateDeclInstantiator::VisitTypeAliasDecl(TypeAliasDecl *D) {
727 Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/true);
729 Owner->addDecl(Typedef);
734 TemplateDeclInstantiator::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) {
735 // Create a local instantiation scope for this type alias template, which
736 // will contain the instantiations of the template parameters.
737 LocalInstantiationScope Scope(SemaRef);
739 TemplateParameterList *TempParams = D->getTemplateParameters();
740 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
744 TypeAliasDecl *Pattern = D->getTemplatedDecl();
746 TypeAliasTemplateDecl *PrevAliasTemplate = nullptr;
747 if (getPreviousDeclForInstantiation<TypedefNameDecl>(Pattern)) {
748 DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
749 if (!Found.empty()) {
750 PrevAliasTemplate = dyn_cast<TypeAliasTemplateDecl>(Found.front());
754 TypeAliasDecl *AliasInst = cast_or_null<TypeAliasDecl>(
755 InstantiateTypedefNameDecl(Pattern, /*IsTypeAlias=*/true));
759 TypeAliasTemplateDecl *Inst
760 = TypeAliasTemplateDecl::Create(SemaRef.Context, Owner, D->getLocation(),
761 D->getDeclName(), InstParams, AliasInst);
762 AliasInst->setDescribedAliasTemplate(Inst);
763 if (PrevAliasTemplate)
764 Inst->setPreviousDecl(PrevAliasTemplate);
766 Inst->setAccess(D->getAccess());
768 if (!PrevAliasTemplate)
769 Inst->setInstantiatedFromMemberTemplate(D);
771 Owner->addDecl(Inst);
776 Decl *TemplateDeclInstantiator::VisitBindingDecl(BindingDecl *D) {
777 auto *NewBD = BindingDecl::Create(SemaRef.Context, Owner, D->getLocation(),
779 NewBD->setReferenced(D->isReferenced());
780 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewBD);
784 Decl *TemplateDeclInstantiator::VisitDecompositionDecl(DecompositionDecl *D) {
785 // Transform the bindings first.
786 SmallVector<BindingDecl*, 16> NewBindings;
787 for (auto *OldBD : D->bindings())
788 NewBindings.push_back(cast<BindingDecl>(VisitBindingDecl(OldBD)));
789 ArrayRef<BindingDecl*> NewBindingArray = NewBindings;
791 auto *NewDD = cast_or_null<DecompositionDecl>(
792 VisitVarDecl(D, /*InstantiatingVarTemplate=*/false, &NewBindingArray));
794 if (!NewDD || NewDD->isInvalidDecl())
795 for (auto *NewBD : NewBindings)
796 NewBD->setInvalidDecl();
801 Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D) {
802 return VisitVarDecl(D, /*InstantiatingVarTemplate=*/false);
805 Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D,
806 bool InstantiatingVarTemplate,
807 ArrayRef<BindingDecl*> *Bindings) {
809 // Do substitution on the type of the declaration
810 TypeSourceInfo *DI = SemaRef.SubstType(
811 D->getTypeSourceInfo(), TemplateArgs, D->getTypeSpecStartLoc(),
812 D->getDeclName(), /*AllowDeducedTST*/true);
816 if (DI->getType()->isFunctionType()) {
817 SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function)
818 << D->isStaticDataMember() << DI->getType();
822 DeclContext *DC = Owner;
823 if (D->isLocalExternDecl())
824 SemaRef.adjustContextForLocalExternDecl(DC);
826 // Build the instantiated declaration.
829 Var = DecompositionDecl::Create(SemaRef.Context, DC, D->getInnerLocStart(),
830 D->getLocation(), DI->getType(), DI,
831 D->getStorageClass(), *Bindings);
833 Var = VarDecl::Create(SemaRef.Context, DC, D->getInnerLocStart(),
834 D->getLocation(), D->getIdentifier(), DI->getType(),
835 DI, D->getStorageClass());
837 // In ARC, infer 'retaining' for variables of retainable type.
838 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
839 SemaRef.inferObjCARCLifetime(Var))
840 Var->setInvalidDecl();
842 // Substitute the nested name specifier, if any.
843 if (SubstQualifier(D, Var))
846 SemaRef.BuildVariableInstantiation(Var, D, TemplateArgs, LateAttrs, Owner,
847 StartingScope, InstantiatingVarTemplate);
849 if (D->isNRVOVariable()) {
850 QualType ReturnType = cast<FunctionDecl>(DC)->getReturnType();
851 if (SemaRef.isCopyElisionCandidate(ReturnType, Var, Sema::CES_Strict))
852 Var->setNRVOVariable(true);
855 Var->setImplicit(D->isImplicit());
857 if (Var->isStaticLocal())
858 SemaRef.CheckStaticLocalForDllExport(Var);
863 Decl *TemplateDeclInstantiator::VisitAccessSpecDecl(AccessSpecDecl *D) {
865 = AccessSpecDecl::Create(SemaRef.Context, D->getAccess(), Owner,
866 D->getAccessSpecifierLoc(), D->getColonLoc());
867 Owner->addHiddenDecl(AD);
871 Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) {
872 bool Invalid = false;
873 TypeSourceInfo *DI = D->getTypeSourceInfo();
874 if (DI->getType()->isInstantiationDependentType() ||
875 DI->getType()->isVariablyModifiedType()) {
876 DI = SemaRef.SubstType(DI, TemplateArgs,
877 D->getLocation(), D->getDeclName());
879 DI = D->getTypeSourceInfo();
881 } else if (DI->getType()->isFunctionType()) {
882 // C++ [temp.arg.type]p3:
883 // If a declaration acquires a function type through a type
884 // dependent on a template-parameter and this causes a
885 // declaration that does not use the syntactic form of a
886 // function declarator to have function type, the program is
888 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
893 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
896 Expr *BitWidth = D->getBitWidth();
900 // The bit-width expression is a constant expression.
901 EnterExpressionEvaluationContext Unevaluated(
902 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
904 ExprResult InstantiatedBitWidth
905 = SemaRef.SubstExpr(BitWidth, TemplateArgs);
906 if (InstantiatedBitWidth.isInvalid()) {
910 BitWidth = InstantiatedBitWidth.getAs<Expr>();
913 FieldDecl *Field = SemaRef.CheckFieldDecl(D->getDeclName(),
915 cast<RecordDecl>(Owner),
919 D->getInClassInitStyle(),
920 D->getInnerLocStart(),
924 cast<Decl>(Owner)->setInvalidDecl();
928 SemaRef.InstantiateAttrs(TemplateArgs, D, Field, LateAttrs, StartingScope);
930 if (Field->hasAttrs())
931 SemaRef.CheckAlignasUnderalignment(Field);
934 Field->setInvalidDecl();
936 if (!Field->getDeclName()) {
937 // Keep track of where this decl came from.
938 SemaRef.Context.setInstantiatedFromUnnamedFieldDecl(Field, D);
940 if (CXXRecordDecl *Parent= dyn_cast<CXXRecordDecl>(Field->getDeclContext())) {
941 if (Parent->isAnonymousStructOrUnion() &&
942 Parent->getRedeclContext()->isFunctionOrMethod())
943 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Field);
946 Field->setImplicit(D->isImplicit());
947 Field->setAccess(D->getAccess());
948 Owner->addDecl(Field);
953 Decl *TemplateDeclInstantiator::VisitMSPropertyDecl(MSPropertyDecl *D) {
954 bool Invalid = false;
955 TypeSourceInfo *DI = D->getTypeSourceInfo();
957 if (DI->getType()->isVariablyModifiedType()) {
958 SemaRef.Diag(D->getLocation(), diag::err_property_is_variably_modified)
961 } else if (DI->getType()->isInstantiationDependentType()) {
962 DI = SemaRef.SubstType(DI, TemplateArgs,
963 D->getLocation(), D->getDeclName());
965 DI = D->getTypeSourceInfo();
967 } else if (DI->getType()->isFunctionType()) {
968 // C++ [temp.arg.type]p3:
969 // If a declaration acquires a function type through a type
970 // dependent on a template-parameter and this causes a
971 // declaration that does not use the syntactic form of a
972 // function declarator to have function type, the program is
974 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
979 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
982 MSPropertyDecl *Property = MSPropertyDecl::Create(
983 SemaRef.Context, Owner, D->getLocation(), D->getDeclName(), DI->getType(),
984 DI, D->getBeginLoc(), D->getGetterId(), D->getSetterId());
986 SemaRef.InstantiateAttrs(TemplateArgs, D, Property, LateAttrs,
990 Property->setInvalidDecl();
992 Property->setAccess(D->getAccess());
993 Owner->addDecl(Property);
998 Decl *TemplateDeclInstantiator::VisitIndirectFieldDecl(IndirectFieldDecl *D) {
999 NamedDecl **NamedChain =
1000 new (SemaRef.Context)NamedDecl*[D->getChainingSize()];
1003 for (auto *PI : D->chain()) {
1004 NamedDecl *Next = SemaRef.FindInstantiatedDecl(D->getLocation(), PI,
1009 NamedChain[i++] = Next;
1012 QualType T = cast<FieldDecl>(NamedChain[i-1])->getType();
1013 IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
1014 SemaRef.Context, Owner, D->getLocation(), D->getIdentifier(), T,
1015 {NamedChain, D->getChainingSize()});
1017 for (const auto *Attr : D->attrs())
1018 IndirectField->addAttr(Attr->clone(SemaRef.Context));
1020 IndirectField->setImplicit(D->isImplicit());
1021 IndirectField->setAccess(D->getAccess());
1022 Owner->addDecl(IndirectField);
1023 return IndirectField;
1026 Decl *TemplateDeclInstantiator::VisitFriendDecl(FriendDecl *D) {
1027 // Handle friend type expressions by simply substituting template
1028 // parameters into the pattern type and checking the result.
1029 if (TypeSourceInfo *Ty = D->getFriendType()) {
1030 TypeSourceInfo *InstTy;
1031 // If this is an unsupported friend, don't bother substituting template
1032 // arguments into it. The actual type referred to won't be used by any
1033 // parts of Clang, and may not be valid for instantiating. Just use the
1034 // same info for the instantiated friend.
1035 if (D->isUnsupportedFriend()) {
1038 InstTy = SemaRef.SubstType(Ty, TemplateArgs,
1039 D->getLocation(), DeclarationName());
1044 FriendDecl *FD = SemaRef.CheckFriendTypeDecl(D->getBeginLoc(),
1045 D->getFriendLoc(), InstTy);
1049 FD->setAccess(AS_public);
1050 FD->setUnsupportedFriend(D->isUnsupportedFriend());
1055 NamedDecl *ND = D->getFriendDecl();
1056 assert(ND && "friend decl must be a decl or a type!");
1058 // All of the Visit implementations for the various potential friend
1059 // declarations have to be carefully written to work for friend
1060 // objects, with the most important detail being that the target
1061 // decl should almost certainly not be placed in Owner.
1062 Decl *NewND = Visit(ND);
1063 if (!NewND) return nullptr;
1066 FriendDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1067 cast<NamedDecl>(NewND), D->getFriendLoc());
1068 FD->setAccess(AS_public);
1069 FD->setUnsupportedFriend(D->isUnsupportedFriend());
1074 Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) {
1075 Expr *AssertExpr = D->getAssertExpr();
1077 // The expression in a static assertion is a constant expression.
1078 EnterExpressionEvaluationContext Unevaluated(
1079 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
1081 ExprResult InstantiatedAssertExpr
1082 = SemaRef.SubstExpr(AssertExpr, TemplateArgs);
1083 if (InstantiatedAssertExpr.isInvalid())
1086 return SemaRef.BuildStaticAssertDeclaration(D->getLocation(),
1087 InstantiatedAssertExpr.get(),
1093 Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) {
1094 EnumDecl *PrevDecl = nullptr;
1095 if (EnumDecl *PatternPrev = getPreviousDeclForInstantiation(D)) {
1096 NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
1099 if (!Prev) return nullptr;
1100 PrevDecl = cast<EnumDecl>(Prev);
1104 EnumDecl::Create(SemaRef.Context, Owner, D->getBeginLoc(),
1105 D->getLocation(), D->getIdentifier(), PrevDecl,
1106 D->isScoped(), D->isScopedUsingClassTag(), D->isFixed());
1108 if (TypeSourceInfo *TI = D->getIntegerTypeSourceInfo()) {
1109 // If we have type source information for the underlying type, it means it
1110 // has been explicitly set by the user. Perform substitution on it before
1112 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
1113 TypeSourceInfo *NewTI = SemaRef.SubstType(TI, TemplateArgs, UnderlyingLoc,
1115 if (!NewTI || SemaRef.CheckEnumUnderlyingType(NewTI))
1116 Enum->setIntegerType(SemaRef.Context.IntTy);
1118 Enum->setIntegerTypeSourceInfo(NewTI);
1120 assert(!D->getIntegerType()->isDependentType()
1121 && "Dependent type without type source info");
1122 Enum->setIntegerType(D->getIntegerType());
1126 SemaRef.InstantiateAttrs(TemplateArgs, D, Enum);
1128 Enum->setInstantiationOfMemberEnum(D, TSK_ImplicitInstantiation);
1129 Enum->setAccess(D->getAccess());
1130 // Forward the mangling number from the template to the instantiated decl.
1131 SemaRef.Context.setManglingNumber(Enum, SemaRef.Context.getManglingNumber(D));
1132 // See if the old tag was defined along with a declarator.
1133 // If it did, mark the new tag as being associated with that declarator.
1134 if (DeclaratorDecl *DD = SemaRef.Context.getDeclaratorForUnnamedTagDecl(D))
1135 SemaRef.Context.addDeclaratorForUnnamedTagDecl(Enum, DD);
1136 // See if the old tag was defined along with a typedef.
1137 // If it did, mark the new tag as being associated with that typedef.
1138 if (TypedefNameDecl *TND = SemaRef.Context.getTypedefNameForUnnamedTagDecl(D))
1139 SemaRef.Context.addTypedefNameForUnnamedTagDecl(Enum, TND);
1140 if (SubstQualifier(D, Enum)) return nullptr;
1141 Owner->addDecl(Enum);
1143 EnumDecl *Def = D->getDefinition();
1144 if (Def && Def != D) {
1145 // If this is an out-of-line definition of an enum member template, check
1146 // that the underlying types match in the instantiation of both
1148 if (TypeSourceInfo *TI = Def->getIntegerTypeSourceInfo()) {
1149 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
1150 QualType DefnUnderlying =
1151 SemaRef.SubstType(TI->getType(), TemplateArgs,
1152 UnderlyingLoc, DeclarationName());
1153 SemaRef.CheckEnumRedeclaration(Def->getLocation(), Def->isScoped(),
1154 DefnUnderlying, /*IsFixed=*/true, Enum);
1158 // C++11 [temp.inst]p1: The implicit instantiation of a class template
1159 // specialization causes the implicit instantiation of the declarations, but
1160 // not the definitions of scoped member enumerations.
1162 // DR1484 clarifies that enumeration definitions inside of a template
1163 // declaration aren't considered entities that can be separately instantiated
1164 // from the rest of the entity they are declared inside of.
1165 if (isDeclWithinFunction(D) ? D == Def : Def && !Enum->isScoped()) {
1166 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Enum);
1167 InstantiateEnumDefinition(Enum, Def);
1173 void TemplateDeclInstantiator::InstantiateEnumDefinition(
1174 EnumDecl *Enum, EnumDecl *Pattern) {
1175 Enum->startDefinition();
1177 // Update the location to refer to the definition.
1178 Enum->setLocation(Pattern->getLocation());
1180 SmallVector<Decl*, 4> Enumerators;
1182 EnumConstantDecl *LastEnumConst = nullptr;
1183 for (auto *EC : Pattern->enumerators()) {
1184 // The specified value for the enumerator.
1185 ExprResult Value((Expr *)nullptr);
1186 if (Expr *UninstValue = EC->getInitExpr()) {
1187 // The enumerator's value expression is a constant expression.
1188 EnterExpressionEvaluationContext Unevaluated(
1189 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
1191 Value = SemaRef.SubstExpr(UninstValue, TemplateArgs);
1194 // Drop the initial value and continue.
1195 bool isInvalid = false;
1196 if (Value.isInvalid()) {
1201 EnumConstantDecl *EnumConst
1202 = SemaRef.CheckEnumConstant(Enum, LastEnumConst,
1203 EC->getLocation(), EC->getIdentifier(),
1208 EnumConst->setInvalidDecl();
1209 Enum->setInvalidDecl();
1213 SemaRef.InstantiateAttrs(TemplateArgs, EC, EnumConst);
1215 EnumConst->setAccess(Enum->getAccess());
1216 Enum->addDecl(EnumConst);
1217 Enumerators.push_back(EnumConst);
1218 LastEnumConst = EnumConst;
1220 if (Pattern->getDeclContext()->isFunctionOrMethod() &&
1221 !Enum->isScoped()) {
1222 // If the enumeration is within a function or method, record the enum
1223 // constant as a local.
1224 SemaRef.CurrentInstantiationScope->InstantiatedLocal(EC, EnumConst);
1229 SemaRef.ActOnEnumBody(Enum->getLocation(), Enum->getBraceRange(), Enum,
1230 Enumerators, nullptr, ParsedAttributesView());
1233 Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) {
1234 llvm_unreachable("EnumConstantDecls can only occur within EnumDecls.");
1238 TemplateDeclInstantiator::VisitBuiltinTemplateDecl(BuiltinTemplateDecl *D) {
1239 llvm_unreachable("BuiltinTemplateDecls cannot be instantiated.");
1242 Decl *TemplateDeclInstantiator::VisitClassTemplateDecl(ClassTemplateDecl *D) {
1243 bool isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
1245 // Create a local instantiation scope for this class template, which
1246 // will contain the instantiations of the template parameters.
1247 LocalInstantiationScope Scope(SemaRef);
1248 TemplateParameterList *TempParams = D->getTemplateParameters();
1249 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1253 CXXRecordDecl *Pattern = D->getTemplatedDecl();
1255 // Instantiate the qualifier. We have to do this first in case
1256 // we're a friend declaration, because if we are then we need to put
1257 // the new declaration in the appropriate context.
1258 NestedNameSpecifierLoc QualifierLoc = Pattern->getQualifierLoc();
1260 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
1266 CXXRecordDecl *PrevDecl = nullptr;
1267 ClassTemplateDecl *PrevClassTemplate = nullptr;
1269 if (!isFriend && getPreviousDeclForInstantiation(Pattern)) {
1270 DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
1271 if (!Found.empty()) {
1272 PrevClassTemplate = dyn_cast<ClassTemplateDecl>(Found.front());
1273 if (PrevClassTemplate)
1274 PrevDecl = PrevClassTemplate->getTemplatedDecl();
1278 // If this isn't a friend, then it's a member template, in which
1279 // case we just want to build the instantiation in the
1280 // specialization. If it is a friend, we want to build it in
1281 // the appropriate context.
1282 DeclContext *DC = Owner;
1286 SS.Adopt(QualifierLoc);
1287 DC = SemaRef.computeDeclContext(SS);
1288 if (!DC) return nullptr;
1290 DC = SemaRef.FindInstantiatedContext(Pattern->getLocation(),
1291 Pattern->getDeclContext(),
1295 // Look for a previous declaration of the template in the owning
1297 LookupResult R(SemaRef, Pattern->getDeclName(), Pattern->getLocation(),
1298 Sema::LookupOrdinaryName,
1299 SemaRef.forRedeclarationInCurContext());
1300 SemaRef.LookupQualifiedName(R, DC);
1302 if (R.isSingleResult()) {
1303 PrevClassTemplate = R.getAsSingle<ClassTemplateDecl>();
1304 if (PrevClassTemplate)
1305 PrevDecl = PrevClassTemplate->getTemplatedDecl();
1308 if (!PrevClassTemplate && QualifierLoc) {
1309 SemaRef.Diag(Pattern->getLocation(), diag::err_not_tag_in_scope)
1310 << D->getTemplatedDecl()->getTagKind() << Pattern->getDeclName() << DC
1311 << QualifierLoc.getSourceRange();
1315 bool AdoptedPreviousTemplateParams = false;
1316 if (PrevClassTemplate) {
1317 bool Complain = true;
1319 // HACK: libstdc++ 4.2.1 contains an ill-formed friend class
1320 // template for struct std::tr1::__detail::_Map_base, where the
1321 // template parameters of the friend declaration don't match the
1322 // template parameters of the original declaration. In this one
1323 // case, we don't complain about the ill-formed friend
1325 if (isFriend && Pattern->getIdentifier() &&
1326 Pattern->getIdentifier()->isStr("_Map_base") &&
1327 DC->isNamespace() &&
1328 cast<NamespaceDecl>(DC)->getIdentifier() &&
1329 cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__detail")) {
1330 DeclContext *DCParent = DC->getParent();
1331 if (DCParent->isNamespace() &&
1332 cast<NamespaceDecl>(DCParent)->getIdentifier() &&
1333 cast<NamespaceDecl>(DCParent)->getIdentifier()->isStr("tr1")) {
1334 if (cast<Decl>(DCParent)->isInStdNamespace())
1339 TemplateParameterList *PrevParams
1340 = PrevClassTemplate->getMostRecentDecl()->getTemplateParameters();
1342 // Make sure the parameter lists match.
1343 if (!SemaRef.TemplateParameterListsAreEqual(InstParams, PrevParams,
1345 Sema::TPL_TemplateMatch)) {
1349 AdoptedPreviousTemplateParams = true;
1350 InstParams = PrevParams;
1353 // Do some additional validation, then merge default arguments
1354 // from the existing declarations.
1355 if (!AdoptedPreviousTemplateParams &&
1356 SemaRef.CheckTemplateParameterList(InstParams, PrevParams,
1357 Sema::TPC_ClassTemplate))
1362 CXXRecordDecl *RecordInst = CXXRecordDecl::Create(
1363 SemaRef.Context, Pattern->getTagKind(), DC, Pattern->getBeginLoc(),
1364 Pattern->getLocation(), Pattern->getIdentifier(), PrevDecl,
1365 /*DelayTypeCreation=*/true);
1368 RecordInst->setQualifierInfo(QualifierLoc);
1370 SemaRef.InstantiateAttrsForDecl(TemplateArgs, Pattern, RecordInst, LateAttrs,
1373 ClassTemplateDecl *Inst
1374 = ClassTemplateDecl::Create(SemaRef.Context, DC, D->getLocation(),
1375 D->getIdentifier(), InstParams, RecordInst);
1376 assert(!(isFriend && Owner->isDependentContext()));
1377 Inst->setPreviousDecl(PrevClassTemplate);
1379 RecordInst->setDescribedClassTemplate(Inst);
1382 if (PrevClassTemplate)
1383 Inst->setAccess(PrevClassTemplate->getAccess());
1385 Inst->setAccess(D->getAccess());
1387 Inst->setObjectOfFriendDecl();
1388 // TODO: do we want to track the instantiation progeny of this
1389 // friend target decl?
1391 Inst->setAccess(D->getAccess());
1392 if (!PrevClassTemplate)
1393 Inst->setInstantiatedFromMemberTemplate(D);
1396 // Trigger creation of the type for the instantiation.
1397 SemaRef.Context.getInjectedClassNameType(RecordInst,
1398 Inst->getInjectedClassNameSpecialization());
1400 // Finish handling of friends.
1402 DC->makeDeclVisibleInContext(Inst);
1403 Inst->setLexicalDeclContext(Owner);
1404 RecordInst->setLexicalDeclContext(Owner);
1408 if (D->isOutOfLine()) {
1409 Inst->setLexicalDeclContext(D->getLexicalDeclContext());
1410 RecordInst->setLexicalDeclContext(D->getLexicalDeclContext());
1413 Owner->addDecl(Inst);
1415 if (!PrevClassTemplate) {
1416 // Queue up any out-of-line partial specializations of this member
1417 // class template; the client will force their instantiation once
1418 // the enclosing class has been instantiated.
1419 SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
1420 D->getPartialSpecializations(PartialSpecs);
1421 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
1422 if (PartialSpecs[I]->getFirstDecl()->isOutOfLine())
1423 OutOfLinePartialSpecs.push_back(std::make_pair(Inst, PartialSpecs[I]));
1430 TemplateDeclInstantiator::VisitClassTemplatePartialSpecializationDecl(
1431 ClassTemplatePartialSpecializationDecl *D) {
1432 ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
1434 // Lookup the already-instantiated declaration in the instantiation
1435 // of the class template and return that.
1436 DeclContext::lookup_result Found
1437 = Owner->lookup(ClassTemplate->getDeclName());
1441 ClassTemplateDecl *InstClassTemplate
1442 = dyn_cast<ClassTemplateDecl>(Found.front());
1443 if (!InstClassTemplate)
1446 if (ClassTemplatePartialSpecializationDecl *Result
1447 = InstClassTemplate->findPartialSpecInstantiatedFromMember(D))
1450 return InstantiateClassTemplatePartialSpecialization(InstClassTemplate, D);
1453 Decl *TemplateDeclInstantiator::VisitVarTemplateDecl(VarTemplateDecl *D) {
1454 assert(D->getTemplatedDecl()->isStaticDataMember() &&
1455 "Only static data member templates are allowed.");
1457 // Create a local instantiation scope for this variable template, which
1458 // will contain the instantiations of the template parameters.
1459 LocalInstantiationScope Scope(SemaRef);
1460 TemplateParameterList *TempParams = D->getTemplateParameters();
1461 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1465 VarDecl *Pattern = D->getTemplatedDecl();
1466 VarTemplateDecl *PrevVarTemplate = nullptr;
1468 if (getPreviousDeclForInstantiation(Pattern)) {
1469 DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
1471 PrevVarTemplate = dyn_cast<VarTemplateDecl>(Found.front());
1475 cast_or_null<VarDecl>(VisitVarDecl(Pattern,
1476 /*InstantiatingVarTemplate=*/true));
1477 if (!VarInst) return nullptr;
1479 DeclContext *DC = Owner;
1481 VarTemplateDecl *Inst = VarTemplateDecl::Create(
1482 SemaRef.Context, DC, D->getLocation(), D->getIdentifier(), InstParams,
1484 VarInst->setDescribedVarTemplate(Inst);
1485 Inst->setPreviousDecl(PrevVarTemplate);
1487 Inst->setAccess(D->getAccess());
1488 if (!PrevVarTemplate)
1489 Inst->setInstantiatedFromMemberTemplate(D);
1491 if (D->isOutOfLine()) {
1492 Inst->setLexicalDeclContext(D->getLexicalDeclContext());
1493 VarInst->setLexicalDeclContext(D->getLexicalDeclContext());
1496 Owner->addDecl(Inst);
1498 if (!PrevVarTemplate) {
1499 // Queue up any out-of-line partial specializations of this member
1500 // variable template; the client will force their instantiation once
1501 // the enclosing class has been instantiated.
1502 SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs;
1503 D->getPartialSpecializations(PartialSpecs);
1504 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
1505 if (PartialSpecs[I]->getFirstDecl()->isOutOfLine())
1506 OutOfLineVarPartialSpecs.push_back(
1507 std::make_pair(Inst, PartialSpecs[I]));
1513 Decl *TemplateDeclInstantiator::VisitVarTemplatePartialSpecializationDecl(
1514 VarTemplatePartialSpecializationDecl *D) {
1515 assert(D->isStaticDataMember() &&
1516 "Only static data member templates are allowed.");
1518 VarTemplateDecl *VarTemplate = D->getSpecializedTemplate();
1520 // Lookup the already-instantiated declaration and return that.
1521 DeclContext::lookup_result Found = Owner->lookup(VarTemplate->getDeclName());
1522 assert(!Found.empty() && "Instantiation found nothing?");
1524 VarTemplateDecl *InstVarTemplate = dyn_cast<VarTemplateDecl>(Found.front());
1525 assert(InstVarTemplate && "Instantiation did not find a variable template?");
1527 if (VarTemplatePartialSpecializationDecl *Result =
1528 InstVarTemplate->findPartialSpecInstantiatedFromMember(D))
1531 return InstantiateVarTemplatePartialSpecialization(InstVarTemplate, D);
1535 TemplateDeclInstantiator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
1536 // Create a local instantiation scope for this function template, which
1537 // will contain the instantiations of the template parameters and then get
1538 // merged with the local instantiation scope for the function template
1540 LocalInstantiationScope Scope(SemaRef);
1542 TemplateParameterList *TempParams = D->getTemplateParameters();
1543 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1547 FunctionDecl *Instantiated = nullptr;
1548 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(D->getTemplatedDecl()))
1549 Instantiated = cast_or_null<FunctionDecl>(VisitCXXMethodDecl(DMethod,
1552 Instantiated = cast_or_null<FunctionDecl>(VisitFunctionDecl(
1553 D->getTemplatedDecl(),
1559 // Link the instantiated function template declaration to the function
1560 // template from which it was instantiated.
1561 FunctionTemplateDecl *InstTemplate
1562 = Instantiated->getDescribedFunctionTemplate();
1563 InstTemplate->setAccess(D->getAccess());
1564 assert(InstTemplate &&
1565 "VisitFunctionDecl/CXXMethodDecl didn't create a template!");
1567 bool isFriend = (InstTemplate->getFriendObjectKind() != Decl::FOK_None);
1569 // Link the instantiation back to the pattern *unless* this is a
1570 // non-definition friend declaration.
1571 if (!InstTemplate->getInstantiatedFromMemberTemplate() &&
1572 !(isFriend && !D->getTemplatedDecl()->isThisDeclarationADefinition()))
1573 InstTemplate->setInstantiatedFromMemberTemplate(D);
1575 // Make declarations visible in the appropriate context.
1577 Owner->addDecl(InstTemplate);
1578 } else if (InstTemplate->getDeclContext()->isRecord() &&
1579 !getPreviousDeclForInstantiation(D)) {
1580 SemaRef.CheckFriendAccess(InstTemplate);
1583 return InstTemplate;
1586 Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) {
1587 CXXRecordDecl *PrevDecl = nullptr;
1588 if (D->isInjectedClassName())
1589 PrevDecl = cast<CXXRecordDecl>(Owner);
1590 else if (CXXRecordDecl *PatternPrev = getPreviousDeclForInstantiation(D)) {
1591 NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
1594 if (!Prev) return nullptr;
1595 PrevDecl = cast<CXXRecordDecl>(Prev);
1598 CXXRecordDecl *Record = CXXRecordDecl::Create(
1599 SemaRef.Context, D->getTagKind(), Owner, D->getBeginLoc(),
1600 D->getLocation(), D->getIdentifier(), PrevDecl);
1602 // Substitute the nested name specifier, if any.
1603 if (SubstQualifier(D, Record))
1606 SemaRef.InstantiateAttrsForDecl(TemplateArgs, D, Record, LateAttrs,
1609 Record->setImplicit(D->isImplicit());
1610 // FIXME: Check against AS_none is an ugly hack to work around the issue that
1611 // the tag decls introduced by friend class declarations don't have an access
1612 // specifier. Remove once this area of the code gets sorted out.
1613 if (D->getAccess() != AS_none)
1614 Record->setAccess(D->getAccess());
1615 if (!D->isInjectedClassName())
1616 Record->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
1618 // If the original function was part of a friend declaration,
1619 // inherit its namespace state.
1620 if (D->getFriendObjectKind())
1621 Record->setObjectOfFriendDecl();
1623 // Make sure that anonymous structs and unions are recorded.
1624 if (D->isAnonymousStructOrUnion())
1625 Record->setAnonymousStructOrUnion(true);
1627 if (D->isLocalClass())
1628 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Record);
1630 // Forward the mangling number from the template to the instantiated decl.
1631 SemaRef.Context.setManglingNumber(Record,
1632 SemaRef.Context.getManglingNumber(D));
1634 // See if the old tag was defined along with a declarator.
1635 // If it did, mark the new tag as being associated with that declarator.
1636 if (DeclaratorDecl *DD = SemaRef.Context.getDeclaratorForUnnamedTagDecl(D))
1637 SemaRef.Context.addDeclaratorForUnnamedTagDecl(Record, DD);
1639 // See if the old tag was defined along with a typedef.
1640 // If it did, mark the new tag as being associated with that typedef.
1641 if (TypedefNameDecl *TND = SemaRef.Context.getTypedefNameForUnnamedTagDecl(D))
1642 SemaRef.Context.addTypedefNameForUnnamedTagDecl(Record, TND);
1644 Owner->addDecl(Record);
1646 // DR1484 clarifies that the members of a local class are instantiated as part
1647 // of the instantiation of their enclosing entity.
1648 if (D->isCompleteDefinition() && D->isLocalClass()) {
1649 Sema::LocalEagerInstantiationScope LocalInstantiations(SemaRef);
1651 SemaRef.InstantiateClass(D->getLocation(), Record, D, TemplateArgs,
1652 TSK_ImplicitInstantiation,
1655 // For nested local classes, we will instantiate the members when we
1656 // reach the end of the outermost (non-nested) local class.
1657 if (!D->isCXXClassMember())
1658 SemaRef.InstantiateClassMembers(D->getLocation(), Record, TemplateArgs,
1659 TSK_ImplicitInstantiation);
1661 // This class may have local implicit instantiations that need to be
1662 // performed within this scope.
1663 LocalInstantiations.perform();
1666 SemaRef.DiagnoseUnusedNestedTypedefs(Record);
1671 /// Adjust the given function type for an instantiation of the
1672 /// given declaration, to cope with modifications to the function's type that
1673 /// aren't reflected in the type-source information.
1675 /// \param D The declaration we're instantiating.
1676 /// \param TInfo The already-instantiated type.
1677 static QualType adjustFunctionTypeForInstantiation(ASTContext &Context,
1679 TypeSourceInfo *TInfo) {
1680 const FunctionProtoType *OrigFunc
1681 = D->getType()->castAs<FunctionProtoType>();
1682 const FunctionProtoType *NewFunc
1683 = TInfo->getType()->castAs<FunctionProtoType>();
1684 if (OrigFunc->getExtInfo() == NewFunc->getExtInfo())
1685 return TInfo->getType();
1687 FunctionProtoType::ExtProtoInfo NewEPI = NewFunc->getExtProtoInfo();
1688 NewEPI.ExtInfo = OrigFunc->getExtInfo();
1689 return Context.getFunctionType(NewFunc->getReturnType(),
1690 NewFunc->getParamTypes(), NewEPI);
1693 /// Normal class members are of more specific types and therefore
1694 /// don't make it here. This function serves three purposes:
1695 /// 1) instantiating function templates
1696 /// 2) substituting friend declarations
1697 /// 3) substituting deduction guide declarations for nested class templates
1698 Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D,
1699 TemplateParameterList *TemplateParams) {
1700 // Check whether there is already a function template specialization for
1701 // this declaration.
1702 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
1703 if (FunctionTemplate && !TemplateParams) {
1704 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
1706 void *InsertPos = nullptr;
1707 FunctionDecl *SpecFunc
1708 = FunctionTemplate->findSpecialization(Innermost, InsertPos);
1710 // If we already have a function template specialization, return it.
1716 if (FunctionTemplate)
1717 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
1719 isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
1721 bool MergeWithParentScope = (TemplateParams != nullptr) ||
1722 Owner->isFunctionOrMethod() ||
1723 !(isa<Decl>(Owner) &&
1724 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
1725 LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
1727 ExplicitSpecifier InstantiatedExplicitSpecifier;
1728 if (auto *DGuide = dyn_cast<CXXDeductionGuideDecl>(D)) {
1729 InstantiatedExplicitSpecifier = instantiateExplicitSpecifier(
1730 SemaRef, TemplateArgs, DGuide->getExplicitSpecifier(), DGuide);
1731 if (InstantiatedExplicitSpecifier.isInvalid())
1735 SmallVector<ParmVarDecl *, 4> Params;
1736 TypeSourceInfo *TInfo = SubstFunctionType(D, Params);
1739 QualType T = adjustFunctionTypeForInstantiation(SemaRef.Context, D, TInfo);
1741 NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
1743 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
1749 // If we're instantiating a local function declaration, put the result
1750 // in the enclosing namespace; otherwise we need to find the instantiated
1753 if (D->isLocalExternDecl()) {
1755 SemaRef.adjustContextForLocalExternDecl(DC);
1756 } else if (isFriend && QualifierLoc) {
1758 SS.Adopt(QualifierLoc);
1759 DC = SemaRef.computeDeclContext(SS);
1760 if (!DC) return nullptr;
1762 DC = SemaRef.FindInstantiatedContext(D->getLocation(), D->getDeclContext(),
1766 DeclarationNameInfo NameInfo
1767 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
1769 FunctionDecl *Function;
1770 if (auto *DGuide = dyn_cast<CXXDeductionGuideDecl>(D)) {
1771 Function = CXXDeductionGuideDecl::Create(
1772 SemaRef.Context, DC, D->getInnerLocStart(),
1773 InstantiatedExplicitSpecifier, NameInfo, T, TInfo,
1774 D->getSourceRange().getEnd());
1775 if (DGuide->isCopyDeductionCandidate())
1776 cast<CXXDeductionGuideDecl>(Function)->setIsCopyDeductionCandidate();
1777 Function->setAccess(D->getAccess());
1779 Function = FunctionDecl::Create(
1780 SemaRef.Context, DC, D->getInnerLocStart(), NameInfo, T, TInfo,
1781 D->getCanonicalDecl()->getStorageClass(), D->isInlineSpecified(),
1782 D->hasWrittenPrototype(), D->getConstexprKind());
1783 Function->setRangeEnd(D->getSourceRange().getEnd());
1787 Function->setImplicitlyInline();
1790 Function->setQualifierInfo(QualifierLoc);
1792 if (D->isLocalExternDecl())
1793 Function->setLocalExternDecl();
1795 DeclContext *LexicalDC = Owner;
1796 if (!isFriend && D->isOutOfLine() && !D->isLocalExternDecl()) {
1797 assert(D->getDeclContext()->isFileContext());
1798 LexicalDC = D->getDeclContext();
1801 Function->setLexicalDeclContext(LexicalDC);
1803 // Attach the parameters
1804 for (unsigned P = 0; P < Params.size(); ++P)
1806 Params[P]->setOwningFunction(Function);
1807 Function->setParams(Params);
1809 if (TemplateParams) {
1810 // Our resulting instantiation is actually a function template, since we
1811 // are substituting only the outer template parameters. For example, given
1813 // template<typename T>
1815 // template<typename U> friend void f(T, U);
1820 // We are instantiating the friend function template "f" within X<int>,
1821 // which means substituting int for T, but leaving "f" as a friend function
1823 // Build the function template itself.
1824 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, DC,
1825 Function->getLocation(),
1826 Function->getDeclName(),
1827 TemplateParams, Function);
1828 Function->setDescribedFunctionTemplate(FunctionTemplate);
1830 FunctionTemplate->setLexicalDeclContext(LexicalDC);
1832 if (isFriend && D->isThisDeclarationADefinition()) {
1833 FunctionTemplate->setInstantiatedFromMemberTemplate(
1834 D->getDescribedFunctionTemplate());
1836 } else if (FunctionTemplate) {
1837 // Record this function template specialization.
1838 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
1839 Function->setFunctionTemplateSpecialization(FunctionTemplate,
1840 TemplateArgumentList::CreateCopy(SemaRef.Context,
1842 /*InsertPos=*/nullptr);
1843 } else if (isFriend && D->isThisDeclarationADefinition()) {
1844 // Do not connect the friend to the template unless it's actually a
1845 // definition. We don't want non-template functions to be marked as being
1846 // template instantiations.
1847 Function->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
1851 Function->setObjectOfFriendDecl();
1853 if (InitFunctionInstantiation(Function, D))
1854 Function->setInvalidDecl();
1856 bool IsExplicitSpecialization = false;
1858 LookupResult Previous(
1859 SemaRef, Function->getDeclName(), SourceLocation(),
1860 D->isLocalExternDecl() ? Sema::LookupRedeclarationWithLinkage
1861 : Sema::LookupOrdinaryName,
1862 D->isLocalExternDecl() ? Sema::ForExternalRedeclaration
1863 : SemaRef.forRedeclarationInCurContext());
1865 if (DependentFunctionTemplateSpecializationInfo *Info
1866 = D->getDependentSpecializationInfo()) {
1867 assert(isFriend && "non-friend has dependent specialization info?");
1869 // Instantiate the explicit template arguments.
1870 TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(),
1871 Info->getRAngleLoc());
1872 if (SemaRef.Subst(Info->getTemplateArgs(), Info->getNumTemplateArgs(),
1873 ExplicitArgs, TemplateArgs))
1876 // Map the candidate templates to their instantiations.
1877 for (unsigned I = 0, E = Info->getNumTemplates(); I != E; ++I) {
1878 Decl *Temp = SemaRef.FindInstantiatedDecl(D->getLocation(),
1879 Info->getTemplate(I),
1881 if (!Temp) return nullptr;
1883 Previous.addDecl(cast<FunctionTemplateDecl>(Temp));
1886 if (SemaRef.CheckFunctionTemplateSpecialization(Function,
1889 Function->setInvalidDecl();
1891 IsExplicitSpecialization = true;
1892 } else if (const ASTTemplateArgumentListInfo *Info =
1893 D->getTemplateSpecializationArgsAsWritten()) {
1894 // The name of this function was written as a template-id.
1895 SemaRef.LookupQualifiedName(Previous, DC);
1897 // Instantiate the explicit template arguments.
1898 TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(),
1899 Info->getRAngleLoc());
1900 if (SemaRef.Subst(Info->getTemplateArgs(), Info->getNumTemplateArgs(),
1901 ExplicitArgs, TemplateArgs))
1904 if (SemaRef.CheckFunctionTemplateSpecialization(Function,
1907 Function->setInvalidDecl();
1909 IsExplicitSpecialization = true;
1910 } else if (TemplateParams || !FunctionTemplate) {
1911 // Look only into the namespace where the friend would be declared to
1912 // find a previous declaration. This is the innermost enclosing namespace,
1913 // as described in ActOnFriendFunctionDecl.
1914 SemaRef.LookupQualifiedName(Previous, DC);
1916 // In C++, the previous declaration we find might be a tag type
1917 // (class or enum). In this case, the new declaration will hide the
1918 // tag type. Note that this does does not apply if we're declaring a
1919 // typedef (C++ [dcl.typedef]p4).
1920 if (Previous.isSingleTagDecl())
1924 SemaRef.CheckFunctionDeclaration(/*Scope*/ nullptr, Function, Previous,
1925 IsExplicitSpecialization);
1927 NamedDecl *PrincipalDecl = (TemplateParams
1928 ? cast<NamedDecl>(FunctionTemplate)
1931 // If the original function was part of a friend declaration,
1932 // inherit its namespace state and add it to the owner.
1934 Function->setObjectOfFriendDecl();
1935 if (FunctionTemplateDecl *FT = Function->getDescribedFunctionTemplate())
1936 FT->setObjectOfFriendDecl();
1937 DC->makeDeclVisibleInContext(PrincipalDecl);
1939 bool QueuedInstantiation = false;
1941 // C++11 [temp.friend]p4 (DR329):
1942 // When a function is defined in a friend function declaration in a class
1943 // template, the function is instantiated when the function is odr-used.
1944 // The same restrictions on multiple declarations and definitions that
1945 // apply to non-template function declarations and definitions also apply
1946 // to these implicit definitions.
1947 if (D->isThisDeclarationADefinition()) {
1948 SemaRef.CheckForFunctionRedefinition(Function);
1949 if (!Function->isInvalidDecl()) {
1950 for (auto R : Function->redecls()) {
1954 // If some prior declaration of this function has been used, we need
1955 // to instantiate its definition.
1956 if (!QueuedInstantiation && R->isUsed(false)) {
1957 if (MemberSpecializationInfo *MSInfo =
1958 Function->getMemberSpecializationInfo()) {
1959 if (MSInfo->getPointOfInstantiation().isInvalid()) {
1960 SourceLocation Loc = R->getLocation(); // FIXME
1961 MSInfo->setPointOfInstantiation(Loc);
1962 SemaRef.PendingLocalImplicitInstantiations.push_back(
1963 std::make_pair(Function, Loc));
1964 QueuedInstantiation = true;
1972 // Check the template parameter list against the previous declaration. The
1973 // goal here is to pick up default arguments added since the friend was
1974 // declared; we know the template parameter lists match, since otherwise
1975 // we would not have picked this template as the previous declaration.
1976 if (TemplateParams && FunctionTemplate->getPreviousDecl()) {
1977 SemaRef.CheckTemplateParameterList(
1979 FunctionTemplate->getPreviousDecl()->getTemplateParameters(),
1980 Function->isThisDeclarationADefinition()
1981 ? Sema::TPC_FriendFunctionTemplateDefinition
1982 : Sema::TPC_FriendFunctionTemplate);
1986 if (Function->isLocalExternDecl() && !Function->getPreviousDecl())
1987 DC->makeDeclVisibleInContext(PrincipalDecl);
1989 if (Function->isOverloadedOperator() && !DC->isRecord() &&
1990 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
1991 PrincipalDecl->setNonMemberOperator();
1993 assert(!D->isDefaulted() && "only methods should be defaulted");
1997 Decl *TemplateDeclInstantiator::VisitCXXMethodDecl(
1998 CXXMethodDecl *D, TemplateParameterList *TemplateParams,
1999 Optional<const ASTTemplateArgumentListInfo *>
2000 ClassScopeSpecializationArgs) {
2001 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
2002 if (FunctionTemplate && !TemplateParams) {
2003 // We are creating a function template specialization from a function
2004 // template. Check whether there is already a function template
2005 // specialization for this particular set of template arguments.
2006 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
2008 void *InsertPos = nullptr;
2009 FunctionDecl *SpecFunc
2010 = FunctionTemplate->findSpecialization(Innermost, InsertPos);
2012 // If we already have a function template specialization, return it.
2018 if (FunctionTemplate)
2019 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
2021 isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
2023 bool MergeWithParentScope = (TemplateParams != nullptr) ||
2024 !(isa<Decl>(Owner) &&
2025 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
2026 LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
2028 // Instantiate enclosing template arguments for friends.
2029 SmallVector<TemplateParameterList *, 4> TempParamLists;
2030 unsigned NumTempParamLists = 0;
2031 if (isFriend && (NumTempParamLists = D->getNumTemplateParameterLists())) {
2032 TempParamLists.resize(NumTempParamLists);
2033 for (unsigned I = 0; I != NumTempParamLists; ++I) {
2034 TemplateParameterList *TempParams = D->getTemplateParameterList(I);
2035 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
2038 TempParamLists[I] = InstParams;
2042 ExplicitSpecifier InstantiatedExplicitSpecifier =
2043 instantiateExplicitSpecifier(SemaRef, TemplateArgs,
2044 ExplicitSpecifier::getFromDecl(D), D);
2045 if (InstantiatedExplicitSpecifier.isInvalid())
2048 SmallVector<ParmVarDecl *, 4> Params;
2049 TypeSourceInfo *TInfo = SubstFunctionType(D, Params);
2052 QualType T = adjustFunctionTypeForInstantiation(SemaRef.Context, D, TInfo);
2054 NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
2056 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
2062 DeclContext *DC = Owner;
2066 SS.Adopt(QualifierLoc);
2067 DC = SemaRef.computeDeclContext(SS);
2069 if (DC && SemaRef.RequireCompleteDeclContext(SS, DC))
2072 DC = SemaRef.FindInstantiatedContext(D->getLocation(),
2073 D->getDeclContext(),
2076 if (!DC) return nullptr;
2079 // Build the instantiated method declaration.
2080 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
2081 CXXMethodDecl *Method = nullptr;
2083 SourceLocation StartLoc = D->getInnerLocStart();
2084 DeclarationNameInfo NameInfo
2085 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
2086 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
2087 Method = CXXConstructorDecl::Create(
2088 SemaRef.Context, Record, StartLoc, NameInfo, T, TInfo,
2089 InstantiatedExplicitSpecifier, Constructor->isInlineSpecified(), false,
2090 Constructor->getConstexprKind());
2091 Method->setRangeEnd(Constructor->getEndLoc());
2092 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
2093 Method = CXXDestructorDecl::Create(SemaRef.Context, Record,
2094 StartLoc, NameInfo, T, TInfo,
2095 Destructor->isInlineSpecified(),
2097 Method->setRangeEnd(Destructor->getEndLoc());
2098 } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) {
2099 Method = CXXConversionDecl::Create(
2100 SemaRef.Context, Record, StartLoc, NameInfo, T, TInfo,
2101 Conversion->isInlineSpecified(), InstantiatedExplicitSpecifier,
2102 Conversion->getConstexprKind(), Conversion->getEndLoc());
2104 StorageClass SC = D->isStatic() ? SC_Static : SC_None;
2105 Method = CXXMethodDecl::Create(SemaRef.Context, Record, StartLoc, NameInfo,
2106 T, TInfo, SC, D->isInlineSpecified(),
2107 D->getConstexprKind(), D->getEndLoc());
2111 Method->setImplicitlyInline();
2114 Method->setQualifierInfo(QualifierLoc);
2116 if (TemplateParams) {
2117 // Our resulting instantiation is actually a function template, since we
2118 // are substituting only the outer template parameters. For example, given
2120 // template<typename T>
2122 // template<typename U> void f(T, U);
2127 // We are instantiating the member template "f" within X<int>, which means
2128 // substituting int for T, but leaving "f" as a member function template.
2129 // Build the function template itself.
2130 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Record,
2131 Method->getLocation(),
2132 Method->getDeclName(),
2133 TemplateParams, Method);
2135 FunctionTemplate->setLexicalDeclContext(Owner);
2136 FunctionTemplate->setObjectOfFriendDecl();
2137 } else if (D->isOutOfLine())
2138 FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
2139 Method->setDescribedFunctionTemplate(FunctionTemplate);
2140 } else if (FunctionTemplate) {
2141 // Record this function template specialization.
2142 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
2143 Method->setFunctionTemplateSpecialization(FunctionTemplate,
2144 TemplateArgumentList::CreateCopy(SemaRef.Context,
2146 /*InsertPos=*/nullptr);
2147 } else if (!isFriend) {
2148 // Record that this is an instantiation of a member function.
2149 Method->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
2152 // If we are instantiating a member function defined
2153 // out-of-line, the instantiation will have the same lexical
2154 // context (which will be a namespace scope) as the template.
2156 if (NumTempParamLists)
2157 Method->setTemplateParameterListsInfo(
2159 llvm::makeArrayRef(TempParamLists.data(), NumTempParamLists));
2161 Method->setLexicalDeclContext(Owner);
2162 Method->setObjectOfFriendDecl();
2163 } else if (D->isOutOfLine())
2164 Method->setLexicalDeclContext(D->getLexicalDeclContext());
2166 // Attach the parameters
2167 for (unsigned P = 0; P < Params.size(); ++P)
2168 Params[P]->setOwningFunction(Method);
2169 Method->setParams(Params);
2171 if (InitMethodInstantiation(Method, D))
2172 Method->setInvalidDecl();
2174 LookupResult Previous(SemaRef, NameInfo, Sema::LookupOrdinaryName,
2175 Sema::ForExternalRedeclaration);
2177 bool IsExplicitSpecialization = false;
2179 // If the name of this function was written as a template-id, instantiate
2180 // the explicit template arguments.
2181 if (DependentFunctionTemplateSpecializationInfo *Info
2182 = D->getDependentSpecializationInfo()) {
2183 assert(isFriend && "non-friend has dependent specialization info?");
2185 // Instantiate the explicit template arguments.
2186 TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(),
2187 Info->getRAngleLoc());
2188 if (SemaRef.Subst(Info->getTemplateArgs(), Info->getNumTemplateArgs(),
2189 ExplicitArgs, TemplateArgs))
2192 // Map the candidate templates to their instantiations.
2193 for (unsigned I = 0, E = Info->getNumTemplates(); I != E; ++I) {
2194 Decl *Temp = SemaRef.FindInstantiatedDecl(D->getLocation(),
2195 Info->getTemplate(I),
2197 if (!Temp) return nullptr;
2199 Previous.addDecl(cast<FunctionTemplateDecl>(Temp));
2202 if (SemaRef.CheckFunctionTemplateSpecialization(Method,
2205 Method->setInvalidDecl();
2207 IsExplicitSpecialization = true;
2208 } else if (const ASTTemplateArgumentListInfo *Info =
2209 ClassScopeSpecializationArgs.getValueOr(
2210 D->getTemplateSpecializationArgsAsWritten())) {
2211 SemaRef.LookupQualifiedName(Previous, DC);
2213 TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(),
2214 Info->getRAngleLoc());
2215 if (SemaRef.Subst(Info->getTemplateArgs(), Info->getNumTemplateArgs(),
2216 ExplicitArgs, TemplateArgs))
2219 if (SemaRef.CheckFunctionTemplateSpecialization(Method,
2222 Method->setInvalidDecl();
2224 IsExplicitSpecialization = true;
2225 } else if (ClassScopeSpecializationArgs) {
2226 // Class-scope explicit specialization written without explicit template
2228 SemaRef.LookupQualifiedName(Previous, DC);
2229 if (SemaRef.CheckFunctionTemplateSpecialization(Method, nullptr, Previous))
2230 Method->setInvalidDecl();
2232 IsExplicitSpecialization = true;
2233 } else if (!FunctionTemplate || TemplateParams || isFriend) {
2234 SemaRef.LookupQualifiedName(Previous, Record);
2236 // In C++, the previous declaration we find might be a tag type
2237 // (class or enum). In this case, the new declaration will hide the
2238 // tag type. Note that this does does not apply if we're declaring a
2239 // typedef (C++ [dcl.typedef]p4).
2240 if (Previous.isSingleTagDecl())
2244 SemaRef.CheckFunctionDeclaration(nullptr, Method, Previous,
2245 IsExplicitSpecialization);
2248 SemaRef.CheckPureMethod(Method, SourceRange());
2250 // Propagate access. For a non-friend declaration, the access is
2251 // whatever we're propagating from. For a friend, it should be the
2252 // previous declaration we just found.
2253 if (isFriend && Method->getPreviousDecl())
2254 Method->setAccess(Method->getPreviousDecl()->getAccess());
2256 Method->setAccess(D->getAccess());
2257 if (FunctionTemplate)
2258 FunctionTemplate->setAccess(Method->getAccess());
2260 SemaRef.CheckOverrideControl(Method);
2262 // If a function is defined as defaulted or deleted, mark it as such now.
2263 if (D->isExplicitlyDefaulted())
2264 SemaRef.SetDeclDefaulted(Method, Method->getLocation());
2265 if (D->isDeletedAsWritten())
2266 SemaRef.SetDeclDeleted(Method, Method->getLocation());
2268 // If this is an explicit specialization, mark the implicitly-instantiated
2269 // template specialization as being an explicit specialization too.
2270 // FIXME: Is this necessary?
2271 if (IsExplicitSpecialization && !isFriend)
2272 SemaRef.CompleteMemberSpecialization(Method, Previous);
2274 // If there's a function template, let our caller handle it.
2275 if (FunctionTemplate) {
2278 // Don't hide a (potentially) valid declaration with an invalid one.
2279 } else if (Method->isInvalidDecl() && !Previous.empty()) {
2282 // Otherwise, check access to friends and make them visible.
2283 } else if (isFriend) {
2284 // We only need to re-check access for methods which we didn't
2285 // manage to match during parsing.
2286 if (!D->getPreviousDecl())
2287 SemaRef.CheckFriendAccess(Method);
2289 Record->makeDeclVisibleInContext(Method);
2291 // Otherwise, add the declaration. We don't need to do this for
2292 // class-scope specializations because we'll have matched them with
2293 // the appropriate template.
2295 Owner->addDecl(Method);
2298 // PR17480: Honor the used attribute to instantiate member function
2300 if (Method->hasAttr<UsedAttr>()) {
2301 if (const auto *A = dyn_cast<CXXRecordDecl>(Owner)) {
2303 if (const MemberSpecializationInfo *MSInfo =
2304 A->getMemberSpecializationInfo())
2305 Loc = MSInfo->getPointOfInstantiation();
2306 else if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(A))
2307 Loc = Spec->getPointOfInstantiation();
2308 SemaRef.MarkFunctionReferenced(Loc, Method);
2315 Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
2316 return VisitCXXMethodDecl(D);
2319 Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
2320 return VisitCXXMethodDecl(D);
2323 Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
2324 return VisitCXXMethodDecl(D);
2327 Decl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
2328 return SemaRef.SubstParmVarDecl(D, TemplateArgs, /*indexAdjustment*/ 0, None,
2329 /*ExpectParameterPack=*/ false);
2332 Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl(
2333 TemplateTypeParmDecl *D) {
2334 // TODO: don't always clone when decls are refcounted.
2335 assert(D->getTypeForDecl()->isTemplateTypeParmType());
2337 TemplateTypeParmDecl *Inst = TemplateTypeParmDecl::Create(
2338 SemaRef.Context, Owner, D->getBeginLoc(), D->getLocation(),
2339 D->getDepth() - TemplateArgs.getNumSubstitutedLevels(), D->getIndex(),
2340 D->getIdentifier(), D->wasDeclaredWithTypename(), D->isParameterPack());
2341 Inst->setAccess(AS_public);
2343 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited()) {
2344 TypeSourceInfo *InstantiatedDefaultArg =
2345 SemaRef.SubstType(D->getDefaultArgumentInfo(), TemplateArgs,
2346 D->getDefaultArgumentLoc(), D->getDeclName());
2347 if (InstantiatedDefaultArg)
2348 Inst->setDefaultArgument(InstantiatedDefaultArg);
2351 // Introduce this template parameter's instantiation into the instantiation
2353 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst);
2358 Decl *TemplateDeclInstantiator::VisitNonTypeTemplateParmDecl(
2359 NonTypeTemplateParmDecl *D) {
2360 // Substitute into the type of the non-type template parameter.
2361 TypeLoc TL = D->getTypeSourceInfo()->getTypeLoc();
2362 SmallVector<TypeSourceInfo *, 4> ExpandedParameterPackTypesAsWritten;
2363 SmallVector<QualType, 4> ExpandedParameterPackTypes;
2364 bool IsExpandedParameterPack = false;
2367 bool Invalid = false;
2369 if (D->isExpandedParameterPack()) {
2370 // The non-type template parameter pack is an already-expanded pack
2371 // expansion of types. Substitute into each of the expanded types.
2372 ExpandedParameterPackTypes.reserve(D->getNumExpansionTypes());
2373 ExpandedParameterPackTypesAsWritten.reserve(D->getNumExpansionTypes());
2374 for (unsigned I = 0, N = D->getNumExpansionTypes(); I != N; ++I) {
2375 TypeSourceInfo *NewDI =
2376 SemaRef.SubstType(D->getExpansionTypeSourceInfo(I), TemplateArgs,
2377 D->getLocation(), D->getDeclName());
2382 SemaRef.CheckNonTypeTemplateParameterType(NewDI, D->getLocation());
2386 ExpandedParameterPackTypesAsWritten.push_back(NewDI);
2387 ExpandedParameterPackTypes.push_back(NewT);
2390 IsExpandedParameterPack = true;
2391 DI = D->getTypeSourceInfo();
2393 } else if (D->isPackExpansion()) {
2394 // The non-type template parameter pack's type is a pack expansion of types.
2395 // Determine whether we need to expand this parameter pack into separate
2397 PackExpansionTypeLoc Expansion = TL.castAs<PackExpansionTypeLoc>();
2398 TypeLoc Pattern = Expansion.getPatternLoc();
2399 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
2400 SemaRef.collectUnexpandedParameterPacks(Pattern, Unexpanded);
2402 // Determine whether the set of unexpanded parameter packs can and should
2405 bool RetainExpansion = false;
2406 Optional<unsigned> OrigNumExpansions
2407 = Expansion.getTypePtr()->getNumExpansions();
2408 Optional<unsigned> NumExpansions = OrigNumExpansions;
2409 if (SemaRef.CheckParameterPacksForExpansion(Expansion.getEllipsisLoc(),
2410 Pattern.getSourceRange(),
2413 Expand, RetainExpansion,
2418 for (unsigned I = 0; I != *NumExpansions; ++I) {
2419 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
2420 TypeSourceInfo *NewDI = SemaRef.SubstType(Pattern, TemplateArgs,
2427 SemaRef.CheckNonTypeTemplateParameterType(NewDI, D->getLocation());
2431 ExpandedParameterPackTypesAsWritten.push_back(NewDI);
2432 ExpandedParameterPackTypes.push_back(NewT);
2435 // Note that we have an expanded parameter pack. The "type" of this
2436 // expanded parameter pack is the original expansion type, but callers
2437 // will end up using the expanded parameter pack types for type-checking.
2438 IsExpandedParameterPack = true;
2439 DI = D->getTypeSourceInfo();
2442 // We cannot fully expand the pack expansion now, so substitute into the
2443 // pattern and create a new pack expansion type.
2444 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
2445 TypeSourceInfo *NewPattern = SemaRef.SubstType(Pattern, TemplateArgs,
2451 SemaRef.CheckNonTypeTemplateParameterType(NewPattern, D->getLocation());
2452 DI = SemaRef.CheckPackExpansion(NewPattern, Expansion.getEllipsisLoc(),
2460 // Simple case: substitution into a parameter that is not a parameter pack.
2461 DI = SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs,
2462 D->getLocation(), D->getDeclName());
2466 // Check that this type is acceptable for a non-type template parameter.
2467 T = SemaRef.CheckNonTypeTemplateParameterType(DI, D->getLocation());
2469 T = SemaRef.Context.IntTy;
2474 NonTypeTemplateParmDecl *Param;
2475 if (IsExpandedParameterPack)
2476 Param = NonTypeTemplateParmDecl::Create(
2477 SemaRef.Context, Owner, D->getInnerLocStart(), D->getLocation(),
2478 D->getDepth() - TemplateArgs.getNumSubstitutedLevels(),
2479 D->getPosition(), D->getIdentifier(), T, DI, ExpandedParameterPackTypes,
2480 ExpandedParameterPackTypesAsWritten);
2482 Param = NonTypeTemplateParmDecl::Create(
2483 SemaRef.Context, Owner, D->getInnerLocStart(), D->getLocation(),
2484 D->getDepth() - TemplateArgs.getNumSubstitutedLevels(),
2485 D->getPosition(), D->getIdentifier(), T, D->isParameterPack(), DI);
2487 Param->setAccess(AS_public);
2489 Param->setInvalidDecl();
2491 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited()) {
2492 EnterExpressionEvaluationContext ConstantEvaluated(
2493 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
2494 ExprResult Value = SemaRef.SubstExpr(D->getDefaultArgument(), TemplateArgs);
2495 if (!Value.isInvalid())
2496 Param->setDefaultArgument(Value.get());
2499 // Introduce this template parameter's instantiation into the instantiation
2501 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
2505 static void collectUnexpandedParameterPacks(
2507 TemplateParameterList *Params,
2508 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
2509 for (const auto &P : *Params) {
2510 if (P->isTemplateParameterPack())
2512 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P))
2513 S.collectUnexpandedParameterPacks(NTTP->getTypeSourceInfo()->getTypeLoc(),
2515 if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(P))
2516 collectUnexpandedParameterPacks(S, TTP->getTemplateParameters(),
2522 TemplateDeclInstantiator::VisitTemplateTemplateParmDecl(
2523 TemplateTemplateParmDecl *D) {
2524 // Instantiate the template parameter list of the template template parameter.
2525 TemplateParameterList *TempParams = D->getTemplateParameters();
2526 TemplateParameterList *InstParams;
2527 SmallVector<TemplateParameterList*, 8> ExpandedParams;
2529 bool IsExpandedParameterPack = false;
2531 if (D->isExpandedParameterPack()) {
2532 // The template template parameter pack is an already-expanded pack
2533 // expansion of template parameters. Substitute into each of the expanded
2535 ExpandedParams.reserve(D->getNumExpansionTemplateParameters());
2536 for (unsigned I = 0, N = D->getNumExpansionTemplateParameters();
2538 LocalInstantiationScope Scope(SemaRef);
2539 TemplateParameterList *Expansion =
2540 SubstTemplateParams(D->getExpansionTemplateParameters(I));
2543 ExpandedParams.push_back(Expansion);
2546 IsExpandedParameterPack = true;
2547 InstParams = TempParams;
2548 } else if (D->isPackExpansion()) {
2549 // The template template parameter pack expands to a pack of template
2550 // template parameters. Determine whether we need to expand this parameter
2551 // pack into separate parameters.
2552 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
2553 collectUnexpandedParameterPacks(SemaRef, D->getTemplateParameters(),
2556 // Determine whether the set of unexpanded parameter packs can and should
2559 bool RetainExpansion = false;
2560 Optional<unsigned> NumExpansions;
2561 if (SemaRef.CheckParameterPacksForExpansion(D->getLocation(),
2562 TempParams->getSourceRange(),
2565 Expand, RetainExpansion,
2570 for (unsigned I = 0; I != *NumExpansions; ++I) {
2571 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
2572 LocalInstantiationScope Scope(SemaRef);
2573 TemplateParameterList *Expansion = SubstTemplateParams(TempParams);
2576 ExpandedParams.push_back(Expansion);
2579 // Note that we have an expanded parameter pack. The "type" of this
2580 // expanded parameter pack is the original expansion type, but callers
2581 // will end up using the expanded parameter pack types for type-checking.
2582 IsExpandedParameterPack = true;
2583 InstParams = TempParams;
2585 // We cannot fully expand the pack expansion now, so just substitute
2586 // into the pattern.
2587 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
2589 LocalInstantiationScope Scope(SemaRef);
2590 InstParams = SubstTemplateParams(TempParams);
2595 // Perform the actual substitution of template parameters within a new,
2596 // local instantiation scope.
2597 LocalInstantiationScope Scope(SemaRef);
2598 InstParams = SubstTemplateParams(TempParams);
2603 // Build the template template parameter.
2604 TemplateTemplateParmDecl *Param;
2605 if (IsExpandedParameterPack)
2606 Param = TemplateTemplateParmDecl::Create(
2607 SemaRef.Context, Owner, D->getLocation(),
2608 D->getDepth() - TemplateArgs.getNumSubstitutedLevels(),
2609 D->getPosition(), D->getIdentifier(), InstParams, ExpandedParams);
2611 Param = TemplateTemplateParmDecl::Create(
2612 SemaRef.Context, Owner, D->getLocation(),
2613 D->getDepth() - TemplateArgs.getNumSubstitutedLevels(),
2614 D->getPosition(), D->isParameterPack(), D->getIdentifier(), InstParams);
2615 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited()) {
2616 NestedNameSpecifierLoc QualifierLoc =
2617 D->getDefaultArgument().getTemplateQualifierLoc();
2619 SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgs);
2620 TemplateName TName = SemaRef.SubstTemplateName(
2621 QualifierLoc, D->getDefaultArgument().getArgument().getAsTemplate(),
2622 D->getDefaultArgument().getTemplateNameLoc(), TemplateArgs);
2623 if (!TName.isNull())
2624 Param->setDefaultArgument(
2626 TemplateArgumentLoc(TemplateArgument(TName),
2627 D->getDefaultArgument().getTemplateQualifierLoc(),
2628 D->getDefaultArgument().getTemplateNameLoc()));
2630 Param->setAccess(AS_public);
2632 // Introduce this template parameter's instantiation into the instantiation
2634 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
2639 Decl *TemplateDeclInstantiator::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
2640 // Using directives are never dependent (and never contain any types or
2641 // expressions), so they require no explicit instantiation work.
2643 UsingDirectiveDecl *Inst
2644 = UsingDirectiveDecl::Create(SemaRef.Context, Owner, D->getLocation(),
2645 D->getNamespaceKeyLocation(),
2646 D->getQualifierLoc(),
2647 D->getIdentLocation(),
2648 D->getNominatedNamespace(),
2649 D->getCommonAncestor());
2651 // Add the using directive to its declaration context
2652 // only if this is not a function or method.
2653 if (!Owner->isFunctionOrMethod())
2654 Owner->addDecl(Inst);
2659 Decl *TemplateDeclInstantiator::VisitUsingDecl(UsingDecl *D) {
2661 // The nested name specifier may be dependent, for example
2662 // template <typename T> struct t {
2663 // struct s1 { T f1(); };
2664 // struct s2 : s1 { using s1::f1; };
2666 // template struct t<int>;
2667 // Here, in using s1::f1, s1 refers to t<T>::s1;
2668 // we need to substitute for t<int>::s1.
2669 NestedNameSpecifierLoc QualifierLoc
2670 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
2675 // For an inheriting constructor declaration, the name of the using
2676 // declaration is the name of a constructor in this class, not in the
2678 DeclarationNameInfo NameInfo = D->getNameInfo();
2679 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName)
2680 if (auto *RD = dyn_cast<CXXRecordDecl>(SemaRef.CurContext))
2681 NameInfo.setName(SemaRef.Context.DeclarationNames.getCXXConstructorName(
2682 SemaRef.Context.getCanonicalType(SemaRef.Context.getRecordType(RD))));
2684 // We only need to do redeclaration lookups if we're in a class
2685 // scope (in fact, it's not really even possible in non-class
2687 bool CheckRedeclaration = Owner->isRecord();
2689 LookupResult Prev(SemaRef, NameInfo, Sema::LookupUsingDeclName,
2690 Sema::ForVisibleRedeclaration);
2692 UsingDecl *NewUD = UsingDecl::Create(SemaRef.Context, Owner,
2699 SS.Adopt(QualifierLoc);
2700 if (CheckRedeclaration) {
2701 Prev.setHideTags(false);
2702 SemaRef.LookupQualifiedName(Prev, Owner);
2704 // Check for invalid redeclarations.
2705 if (SemaRef.CheckUsingDeclRedeclaration(D->getUsingLoc(),
2706 D->hasTypename(), SS,
2707 D->getLocation(), Prev))
2708 NewUD->setInvalidDecl();
2712 if (!NewUD->isInvalidDecl() &&
2713 SemaRef.CheckUsingDeclQualifier(D->getUsingLoc(), D->hasTypename(),
2714 SS, NameInfo, D->getLocation()))
2715 NewUD->setInvalidDecl();
2717 SemaRef.Context.setInstantiatedFromUsingDecl(NewUD, D);
2718 NewUD->setAccess(D->getAccess());
2719 Owner->addDecl(NewUD);
2721 // Don't process the shadow decls for an invalid decl.
2722 if (NewUD->isInvalidDecl())
2725 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName)
2726 SemaRef.CheckInheritingConstructorUsingDecl(NewUD);
2728 bool isFunctionScope = Owner->isFunctionOrMethod();
2730 // Process the shadow decls.
2731 for (auto *Shadow : D->shadows()) {
2732 // FIXME: UsingShadowDecl doesn't preserve its immediate target, so
2733 // reconstruct it in the case where it matters.
2734 NamedDecl *OldTarget = Shadow->getTargetDecl();
2735 if (auto *CUSD = dyn_cast<ConstructorUsingShadowDecl>(Shadow))
2736 if (auto *BaseShadow = CUSD->getNominatedBaseClassShadowDecl())
2737 OldTarget = BaseShadow;
2739 NamedDecl *InstTarget =
2740 cast_or_null<NamedDecl>(SemaRef.FindInstantiatedDecl(
2741 Shadow->getLocation(), OldTarget, TemplateArgs));
2745 UsingShadowDecl *PrevDecl = nullptr;
2746 if (CheckRedeclaration) {
2747 if (SemaRef.CheckUsingShadowDecl(NewUD, InstTarget, Prev, PrevDecl))
2749 } else if (UsingShadowDecl *OldPrev =
2750 getPreviousDeclForInstantiation(Shadow)) {
2751 PrevDecl = cast_or_null<UsingShadowDecl>(SemaRef.FindInstantiatedDecl(
2752 Shadow->getLocation(), OldPrev, TemplateArgs));
2755 UsingShadowDecl *InstShadow =
2756 SemaRef.BuildUsingShadowDecl(/*Scope*/nullptr, NewUD, InstTarget,
2758 SemaRef.Context.setInstantiatedFromUsingShadowDecl(InstShadow, Shadow);
2760 if (isFunctionScope)
2761 SemaRef.CurrentInstantiationScope->InstantiatedLocal(Shadow, InstShadow);
2767 Decl *TemplateDeclInstantiator::VisitUsingShadowDecl(UsingShadowDecl *D) {
2768 // Ignore these; we handle them in bulk when processing the UsingDecl.
2772 Decl *TemplateDeclInstantiator::VisitConstructorUsingShadowDecl(
2773 ConstructorUsingShadowDecl *D) {
2774 // Ignore these; we handle them in bulk when processing the UsingDecl.
2778 template <typename T>
2779 Decl *TemplateDeclInstantiator::instantiateUnresolvedUsingDecl(
2780 T *D, bool InstantiatingPackElement) {
2781 // If this is a pack expansion, expand it now.
2782 if (D->isPackExpansion() && !InstantiatingPackElement) {
2783 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
2784 SemaRef.collectUnexpandedParameterPacks(D->getQualifierLoc(), Unexpanded);
2785 SemaRef.collectUnexpandedParameterPacks(D->getNameInfo(), Unexpanded);
2787 // Determine whether the set of unexpanded parameter packs can and should
2790 bool RetainExpansion = false;
2791 Optional<unsigned> NumExpansions;
2792 if (SemaRef.CheckParameterPacksForExpansion(
2793 D->getEllipsisLoc(), D->getSourceRange(), Unexpanded, TemplateArgs,
2794 Expand, RetainExpansion, NumExpansions))
2797 // This declaration cannot appear within a function template signature,
2798 // so we can't have a partial argument list for a parameter pack.
2799 assert(!RetainExpansion &&
2800 "should never need to retain an expansion for UsingPackDecl");
2803 // We cannot fully expand the pack expansion now, so substitute into the
2804 // pattern and create a new pack expansion.
2805 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
2806 return instantiateUnresolvedUsingDecl(D, true);
2809 // Within a function, we don't have any normal way to check for conflicts
2810 // between shadow declarations from different using declarations in the
2811 // same pack expansion, but this is always ill-formed because all expansions
2812 // must produce (conflicting) enumerators.
2814 // Sadly we can't just reject this in the template definition because it
2815 // could be valid if the pack is empty or has exactly one expansion.
2816 if (D->getDeclContext()->isFunctionOrMethod() && *NumExpansions > 1) {
2817 SemaRef.Diag(D->getEllipsisLoc(),
2818 diag::err_using_decl_redeclaration_expansion);
2822 // Instantiate the slices of this pack and build a UsingPackDecl.
2823 SmallVector<NamedDecl*, 8> Expansions;
2824 for (unsigned I = 0; I != *NumExpansions; ++I) {
2825 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
2826 Decl *Slice = instantiateUnresolvedUsingDecl(D, true);
2829 // Note that we can still get unresolved using declarations here, if we
2830 // had arguments for all packs but the pattern also contained other
2831 // template arguments (this only happens during partial substitution, eg
2832 // into the body of a generic lambda in a function template).
2833 Expansions.push_back(cast<NamedDecl>(Slice));
2836 auto *NewD = SemaRef.BuildUsingPackDecl(D, Expansions);
2837 if (isDeclWithinFunction(D))
2838 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewD);
2842 UnresolvedUsingTypenameDecl *TD = dyn_cast<UnresolvedUsingTypenameDecl>(D);
2843 SourceLocation TypenameLoc = TD ? TD->getTypenameLoc() : SourceLocation();
2845 NestedNameSpecifierLoc QualifierLoc
2846 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
2852 SS.Adopt(QualifierLoc);
2854 DeclarationNameInfo NameInfo
2855 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
2857 // Produce a pack expansion only if we're not instantiating a particular
2858 // slice of a pack expansion.
2859 bool InstantiatingSlice = D->getEllipsisLoc().isValid() &&
2860 SemaRef.ArgumentPackSubstitutionIndex != -1;
2861 SourceLocation EllipsisLoc =
2862 InstantiatingSlice ? SourceLocation() : D->getEllipsisLoc();
2864 NamedDecl *UD = SemaRef.BuildUsingDeclaration(
2865 /*Scope*/ nullptr, D->getAccess(), D->getUsingLoc(),
2866 /*HasTypename*/ TD, TypenameLoc, SS, NameInfo, EllipsisLoc,
2867 ParsedAttributesView(),
2868 /*IsInstantiation*/ true);
2870 SemaRef.Context.setInstantiatedFromUsingDecl(UD, D);
2875 Decl *TemplateDeclInstantiator::VisitUnresolvedUsingTypenameDecl(
2876 UnresolvedUsingTypenameDecl *D) {
2877 return instantiateUnresolvedUsingDecl(D);
2880 Decl *TemplateDeclInstantiator::VisitUnresolvedUsingValueDecl(
2881 UnresolvedUsingValueDecl *D) {
2882 return instantiateUnresolvedUsingDecl(D);
2885 Decl *TemplateDeclInstantiator::VisitUsingPackDecl(UsingPackDecl *D) {
2886 SmallVector<NamedDecl*, 8> Expansions;
2887 for (auto *UD : D->expansions()) {
2888 if (NamedDecl *NewUD =
2889 SemaRef.FindInstantiatedDecl(D->getLocation(), UD, TemplateArgs))
2890 Expansions.push_back(NewUD);
2895 auto *NewD = SemaRef.BuildUsingPackDecl(D, Expansions);
2896 if (isDeclWithinFunction(D))
2897 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewD);
2901 Decl *TemplateDeclInstantiator::VisitClassScopeFunctionSpecializationDecl(
2902 ClassScopeFunctionSpecializationDecl *Decl) {
2903 CXXMethodDecl *OldFD = Decl->getSpecialization();
2904 return cast_or_null<CXXMethodDecl>(
2905 VisitCXXMethodDecl(OldFD, nullptr, Decl->getTemplateArgsAsWritten()));
2908 Decl *TemplateDeclInstantiator::VisitOMPThreadPrivateDecl(
2909 OMPThreadPrivateDecl *D) {
2910 SmallVector<Expr *, 5> Vars;
2911 for (auto *I : D->varlists()) {
2912 Expr *Var = SemaRef.SubstExpr(I, TemplateArgs).get();
2913 assert(isa<DeclRefExpr>(Var) && "threadprivate arg is not a DeclRefExpr");
2914 Vars.push_back(Var);
2917 OMPThreadPrivateDecl *TD =
2918 SemaRef.CheckOMPThreadPrivateDecl(D->getLocation(), Vars);
2920 TD->setAccess(AS_public);
2926 Decl *TemplateDeclInstantiator::VisitOMPAllocateDecl(OMPAllocateDecl *D) {
2927 SmallVector<Expr *, 5> Vars;
2928 for (auto *I : D->varlists()) {
2929 Expr *Var = SemaRef.SubstExpr(I, TemplateArgs).get();
2930 assert(isa<DeclRefExpr>(Var) && "allocate arg is not a DeclRefExpr");
2931 Vars.push_back(Var);
2933 SmallVector<OMPClause *, 4> Clauses;
2934 // Copy map clauses from the original mapper.
2935 for (OMPClause *C : D->clauselists()) {
2936 auto *AC = cast<OMPAllocatorClause>(C);
2937 ExprResult NewE = SemaRef.SubstExpr(AC->getAllocator(), TemplateArgs);
2938 if (!NewE.isUsable())
2940 OMPClause *IC = SemaRef.ActOnOpenMPAllocatorClause(
2941 NewE.get(), AC->getBeginLoc(), AC->getLParenLoc(), AC->getEndLoc());
2942 Clauses.push_back(IC);
2945 Sema::DeclGroupPtrTy Res = SemaRef.ActOnOpenMPAllocateDirective(
2946 D->getLocation(), Vars, Clauses, Owner);
2947 if (Res.get().isNull())
2949 return Res.get().getSingleDecl();
2952 Decl *TemplateDeclInstantiator::VisitOMPRequiresDecl(OMPRequiresDecl *D) {
2954 "Requires directive cannot be instantiated within a dependent context");
2957 Decl *TemplateDeclInstantiator::VisitOMPDeclareReductionDecl(
2958 OMPDeclareReductionDecl *D) {
2959 // Instantiate type and check if it is allowed.
2960 const bool RequiresInstantiation =
2961 D->getType()->isDependentType() ||
2962 D->getType()->isInstantiationDependentType() ||
2963 D->getType()->containsUnexpandedParameterPack();
2964 QualType SubstReductionType;
2965 if (RequiresInstantiation) {
2966 SubstReductionType = SemaRef.ActOnOpenMPDeclareReductionType(
2968 ParsedType::make(SemaRef.SubstType(
2969 D->getType(), TemplateArgs, D->getLocation(), DeclarationName())));
2971 SubstReductionType = D->getType();
2973 if (SubstReductionType.isNull())
2975 bool IsCorrect = !SubstReductionType.isNull();
2976 // Create instantiated copy.
2977 std::pair<QualType, SourceLocation> ReductionTypes[] = {
2978 std::make_pair(SubstReductionType, D->getLocation())};
2979 auto *PrevDeclInScope = D->getPrevDeclInScope();
2980 if (PrevDeclInScope && !PrevDeclInScope->isInvalidDecl()) {
2981 PrevDeclInScope = cast<OMPDeclareReductionDecl>(
2982 SemaRef.CurrentInstantiationScope->findInstantiationOf(PrevDeclInScope)
2985 auto DRD = SemaRef.ActOnOpenMPDeclareReductionDirectiveStart(
2986 /*S=*/nullptr, Owner, D->getDeclName(), ReductionTypes, D->getAccess(),
2988 auto *NewDRD = cast<OMPDeclareReductionDecl>(DRD.get().getSingleDecl());
2989 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewDRD);
2990 if (!RequiresInstantiation) {
2991 if (Expr *Combiner = D->getCombiner()) {
2992 NewDRD->setCombinerData(D->getCombinerIn(), D->getCombinerOut());
2993 NewDRD->setCombiner(Combiner);
2994 if (Expr *Init = D->getInitializer()) {
2995 NewDRD->setInitializerData(D->getInitOrig(), D->getInitPriv());
2996 NewDRD->setInitializer(Init, D->getInitializerKind());
2999 (void)SemaRef.ActOnOpenMPDeclareReductionDirectiveEnd(
3000 /*S=*/nullptr, DRD, IsCorrect && !D->isInvalidDecl());
3003 Expr *SubstCombiner = nullptr;
3004 Expr *SubstInitializer = nullptr;
3005 // Combiners instantiation sequence.
3006 if (D->getCombiner()) {
3007 SemaRef.ActOnOpenMPDeclareReductionCombinerStart(
3008 /*S=*/nullptr, NewDRD);
3009 SemaRef.CurrentInstantiationScope->InstantiatedLocal(
3010 cast<DeclRefExpr>(D->getCombinerIn())->getDecl(),
3011 cast<DeclRefExpr>(NewDRD->getCombinerIn())->getDecl());
3012 SemaRef.CurrentInstantiationScope->InstantiatedLocal(
3013 cast<DeclRefExpr>(D->getCombinerOut())->getDecl(),
3014 cast<DeclRefExpr>(NewDRD->getCombinerOut())->getDecl());
3015 auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(Owner);
3016 Sema::CXXThisScopeRAII ThisScope(SemaRef, ThisContext, Qualifiers(),
3018 SubstCombiner = SemaRef.SubstExpr(D->getCombiner(), TemplateArgs).get();
3019 SemaRef.ActOnOpenMPDeclareReductionCombinerEnd(NewDRD, SubstCombiner);
3020 // Initializers instantiation sequence.
3021 if (D->getInitializer()) {
3022 VarDecl *OmpPrivParm =
3023 SemaRef.ActOnOpenMPDeclareReductionInitializerStart(
3024 /*S=*/nullptr, NewDRD);
3025 SemaRef.CurrentInstantiationScope->InstantiatedLocal(
3026 cast<DeclRefExpr>(D->getInitOrig())->getDecl(),
3027 cast<DeclRefExpr>(NewDRD->getInitOrig())->getDecl());
3028 SemaRef.CurrentInstantiationScope->InstantiatedLocal(
3029 cast<DeclRefExpr>(D->getInitPriv())->getDecl(),
3030 cast<DeclRefExpr>(NewDRD->getInitPriv())->getDecl());
3031 if (D->getInitializerKind() == OMPDeclareReductionDecl::CallInit) {
3033 SemaRef.SubstExpr(D->getInitializer(), TemplateArgs).get();
3035 IsCorrect = IsCorrect && OmpPrivParm->hasInit();
3037 SemaRef.ActOnOpenMPDeclareReductionInitializerEnd(
3038 NewDRD, SubstInitializer, OmpPrivParm);
3041 IsCorrect && SubstCombiner &&
3042 (!D->getInitializer() ||
3043 (D->getInitializerKind() == OMPDeclareReductionDecl::CallInit &&
3044 SubstInitializer) ||
3045 (D->getInitializerKind() != OMPDeclareReductionDecl::CallInit &&
3046 !SubstInitializer && !SubstInitializer));
3051 (void)SemaRef.ActOnOpenMPDeclareReductionDirectiveEnd(/*S=*/nullptr, DRD,
3058 TemplateDeclInstantiator::VisitOMPDeclareMapperDecl(OMPDeclareMapperDecl *D) {
3059 // Instantiate type and check if it is allowed.
3060 const bool RequiresInstantiation =
3061 D->getType()->isDependentType() ||
3062 D->getType()->isInstantiationDependentType() ||
3063 D->getType()->containsUnexpandedParameterPack();
3064 QualType SubstMapperTy;
3065 DeclarationName VN = D->getVarName();
3066 if (RequiresInstantiation) {
3067 SubstMapperTy = SemaRef.ActOnOpenMPDeclareMapperType(
3069 ParsedType::make(SemaRef.SubstType(D->getType(), TemplateArgs,
3070 D->getLocation(), VN)));
3072 SubstMapperTy = D->getType();
3074 if (SubstMapperTy.isNull())
3076 // Create an instantiated copy of mapper.
3077 auto *PrevDeclInScope = D->getPrevDeclInScope();
3078 if (PrevDeclInScope && !PrevDeclInScope->isInvalidDecl()) {
3079 PrevDeclInScope = cast<OMPDeclareMapperDecl>(
3080 SemaRef.CurrentInstantiationScope->findInstantiationOf(PrevDeclInScope)
3083 OMPDeclareMapperDecl *NewDMD = SemaRef.ActOnOpenMPDeclareMapperDirectiveStart(
3084 /*S=*/nullptr, Owner, D->getDeclName(), SubstMapperTy, D->getLocation(),
3085 VN, D->getAccess(), PrevDeclInScope);
3086 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewDMD);
3087 SmallVector<OMPClause *, 6> Clauses;
3088 bool IsCorrect = true;
3089 if (!RequiresInstantiation) {
3090 // Copy the mapper variable.
3091 NewDMD->setMapperVarRef(D->getMapperVarRef());
3092 // Copy map clauses from the original mapper.
3093 for (OMPClause *C : D->clauselists())
3094 Clauses.push_back(C);
3096 // Instantiate the mapper variable.
3097 DeclarationNameInfo DirName;
3098 SemaRef.StartOpenMPDSABlock(OMPD_declare_mapper, DirName, /*S=*/nullptr,
3099 (*D->clauselist_begin())->getBeginLoc());
3100 SemaRef.ActOnOpenMPDeclareMapperDirectiveVarDecl(
3101 NewDMD, /*S=*/nullptr, SubstMapperTy, D->getLocation(), VN);
3102 SemaRef.CurrentInstantiationScope->InstantiatedLocal(
3103 cast<DeclRefExpr>(D->getMapperVarRef())->getDecl(),
3104 cast<DeclRefExpr>(NewDMD->getMapperVarRef())->getDecl());
3105 auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(Owner);
3106 Sema::CXXThisScopeRAII ThisScope(SemaRef, ThisContext, Qualifiers(),
3108 // Instantiate map clauses.
3109 for (OMPClause *C : D->clauselists()) {
3110 auto *OldC = cast<OMPMapClause>(C);
3111 SmallVector<Expr *, 4> NewVars;
3112 for (Expr *OE : OldC->varlists()) {
3113 Expr *NE = SemaRef.SubstExpr(OE, TemplateArgs).get();
3118 NewVars.push_back(NE);
3122 NestedNameSpecifierLoc NewQualifierLoc =
3123 SemaRef.SubstNestedNameSpecifierLoc(OldC->getMapperQualifierLoc(),
3126 SS.Adopt(NewQualifierLoc);
3127 DeclarationNameInfo NewNameInfo = SemaRef.SubstDeclarationNameInfo(
3128 OldC->getMapperIdInfo(), TemplateArgs);
3129 OMPVarListLocTy Locs(OldC->getBeginLoc(), OldC->getLParenLoc(),
3131 OMPClause *NewC = SemaRef.ActOnOpenMPMapClause(
3132 OldC->getMapTypeModifiers(), OldC->getMapTypeModifiersLoc(), SS,
3133 NewNameInfo, OldC->getMapType(), OldC->isImplicitMapType(),
3134 OldC->getMapLoc(), OldC->getColonLoc(), NewVars, Locs);
3135 Clauses.push_back(NewC);
3137 SemaRef.EndOpenMPDSABlock(nullptr);
3139 (void)SemaRef.ActOnOpenMPDeclareMapperDirectiveEnd(NewDMD, /*S=*/nullptr,
3146 Decl *TemplateDeclInstantiator::VisitOMPCapturedExprDecl(
3147 OMPCapturedExprDecl * /*D*/) {
3148 llvm_unreachable("Should not be met in templates");
3151 Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D) {
3152 return VisitFunctionDecl(D, nullptr);
3156 TemplateDeclInstantiator::VisitCXXDeductionGuideDecl(CXXDeductionGuideDecl *D) {
3157 Decl *Inst = VisitFunctionDecl(D, nullptr);
3158 if (Inst && !D->getDescribedFunctionTemplate())
3159 Owner->addDecl(Inst);
3163 Decl *TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D) {
3164 return VisitCXXMethodDecl(D, nullptr);
3167 Decl *TemplateDeclInstantiator::VisitRecordDecl(RecordDecl *D) {
3168 llvm_unreachable("There are only CXXRecordDecls in C++");
3172 TemplateDeclInstantiator::VisitClassTemplateSpecializationDecl(
3173 ClassTemplateSpecializationDecl *D) {
3174 // As a MS extension, we permit class-scope explicit specialization
3175 // of member class templates.
3176 ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
3177 assert(ClassTemplate->getDeclContext()->isRecord() &&
3178 D->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
3179 "can only instantiate an explicit specialization "
3180 "for a member class template");
3182 // Lookup the already-instantiated declaration in the instantiation
3183 // of the class template.
3184 ClassTemplateDecl *InstClassTemplate =
3185 cast_or_null<ClassTemplateDecl>(SemaRef.FindInstantiatedDecl(
3186 D->getLocation(), ClassTemplate, TemplateArgs));
3187 if (!InstClassTemplate)
3190 // Substitute into the template arguments of the class template explicit
3192 TemplateSpecializationTypeLoc Loc = D->getTypeAsWritten()->getTypeLoc().
3193 castAs<TemplateSpecializationTypeLoc>();
3194 TemplateArgumentListInfo InstTemplateArgs(Loc.getLAngleLoc(),
3195 Loc.getRAngleLoc());
3196 SmallVector<TemplateArgumentLoc, 4> ArgLocs;
3197 for (unsigned I = 0; I != Loc.getNumArgs(); ++I)
3198 ArgLocs.push_back(Loc.getArgLoc(I));
3199 if (SemaRef.Subst(ArgLocs.data(), ArgLocs.size(),
3200 InstTemplateArgs, TemplateArgs))
3203 // Check that the template argument list is well-formed for this
3205 SmallVector<TemplateArgument, 4> Converted;
3206 if (SemaRef.CheckTemplateArgumentList(InstClassTemplate,
3213 // Figure out where to insert this class template explicit specialization
3214 // in the member template's set of class template explicit specializations.
3215 void *InsertPos = nullptr;
3216 ClassTemplateSpecializationDecl *PrevDecl =
3217 InstClassTemplate->findSpecialization(Converted, InsertPos);
3219 // Check whether we've already seen a conflicting instantiation of this
3220 // declaration (for instance, if there was a prior implicit instantiation).
3223 SemaRef.CheckSpecializationInstantiationRedecl(D->getLocation(),
3224 D->getSpecializationKind(),
3226 PrevDecl->getSpecializationKind(),
3227 PrevDecl->getPointOfInstantiation(),
3231 // If PrevDecl was a definition and D is also a definition, diagnose.
3232 // This happens in cases like:
3234 // template<typename T, typename U>
3236 // template<typename X> struct Inner;
3237 // template<> struct Inner<T> {};
3238 // template<> struct Inner<U> {};
3241 // Outer<int, int> outer; // error: the explicit specializations of Inner
3242 // // have the same signature.
3243 if (PrevDecl && PrevDecl->getDefinition() &&
3244 D->isThisDeclarationADefinition()) {
3245 SemaRef.Diag(D->getLocation(), diag::err_redefinition) << PrevDecl;
3246 SemaRef.Diag(PrevDecl->getDefinition()->getLocation(),
3247 diag::note_previous_definition);
3251 // Create the class template partial specialization declaration.
3252 ClassTemplateSpecializationDecl *InstD =
3253 ClassTemplateSpecializationDecl::Create(
3254 SemaRef.Context, D->getTagKind(), Owner, D->getBeginLoc(),
3255 D->getLocation(), InstClassTemplate, Converted, PrevDecl);
3257 // Add this partial specialization to the set of class template partial
3260 InstClassTemplate->AddSpecialization(InstD, InsertPos);
3262 // Substitute the nested name specifier, if any.
3263 if (SubstQualifier(D, InstD))
3266 // Build the canonical type that describes the converted template
3267 // arguments of the class template explicit specialization.
3268 QualType CanonType = SemaRef.Context.getTemplateSpecializationType(
3269 TemplateName(InstClassTemplate), Converted,
3270 SemaRef.Context.getRecordType(InstD));
3272 // Build the fully-sugared type for this class template
3273 // specialization as the user wrote in the specialization
3274 // itself. This means that we'll pretty-print the type retrieved
3275 // from the specialization's declaration the way that the user
3276 // actually wrote the specialization, rather than formatting the
3277 // name based on the "canonical" representation used to store the
3278 // template arguments in the specialization.
3279 TypeSourceInfo *WrittenTy = SemaRef.Context.getTemplateSpecializationTypeInfo(
3280 TemplateName(InstClassTemplate), D->getLocation(), InstTemplateArgs,
3283 InstD->setAccess(D->getAccess());
3284 InstD->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
3285 InstD->setSpecializationKind(D->getSpecializationKind());
3286 InstD->setTypeAsWritten(WrittenTy);
3287 InstD->setExternLoc(D->getExternLoc());
3288 InstD->setTemplateKeywordLoc(D->getTemplateKeywordLoc());
3290 Owner->addDecl(InstD);
3292 // Instantiate the members of the class-scope explicit specialization eagerly.
3293 // We don't have support for lazy instantiation of an explicit specialization
3294 // yet, and MSVC eagerly instantiates in this case.
3295 // FIXME: This is wrong in standard C++.
3296 if (D->isThisDeclarationADefinition() &&
3297 SemaRef.InstantiateClass(D->getLocation(), InstD, D, TemplateArgs,
3298 TSK_ImplicitInstantiation,
3305 Decl *TemplateDeclInstantiator::VisitVarTemplateSpecializationDecl(
3306 VarTemplateSpecializationDecl *D) {
3308 TemplateArgumentListInfo VarTemplateArgsInfo;
3309 VarTemplateDecl *VarTemplate = D->getSpecializedTemplate();
3310 assert(VarTemplate &&
3311 "A template specialization without specialized template?");
3313 VarTemplateDecl *InstVarTemplate =
3314 cast_or_null<VarTemplateDecl>(SemaRef.FindInstantiatedDecl(
3315 D->getLocation(), VarTemplate, TemplateArgs));
3316 if (!InstVarTemplate)
3319 // Substitute the current template arguments.
3320 const TemplateArgumentListInfo &TemplateArgsInfo = D->getTemplateArgsInfo();
3321 VarTemplateArgsInfo.setLAngleLoc(TemplateArgsInfo.getLAngleLoc());
3322 VarTemplateArgsInfo.setRAngleLoc(TemplateArgsInfo.getRAngleLoc());
3324 if (SemaRef.Subst(TemplateArgsInfo.getArgumentArray(),
3325 TemplateArgsInfo.size(), VarTemplateArgsInfo, TemplateArgs))
3328 // Check that the template argument list is well-formed for this template.
3329 SmallVector<TemplateArgument, 4> Converted;
3330 if (SemaRef.CheckTemplateArgumentList(InstVarTemplate, D->getLocation(),
3331 VarTemplateArgsInfo, false, Converted))
3334 // Check whether we've already seen a declaration of this specialization.
3335 void *InsertPos = nullptr;
3336 VarTemplateSpecializationDecl *PrevDecl =
3337 InstVarTemplate->findSpecialization(Converted, InsertPos);
3339 // Check whether we've already seen a conflicting instantiation of this
3340 // declaration (for instance, if there was a prior implicit instantiation).
3342 if (PrevDecl && SemaRef.CheckSpecializationInstantiationRedecl(
3343 D->getLocation(), D->getSpecializationKind(), PrevDecl,
3344 PrevDecl->getSpecializationKind(),
3345 PrevDecl->getPointOfInstantiation(), Ignored))
3348 return VisitVarTemplateSpecializationDecl(
3349 InstVarTemplate, D, InsertPos, VarTemplateArgsInfo, Converted, PrevDecl);
3352 Decl *TemplateDeclInstantiator::VisitVarTemplateSpecializationDecl(
3353 VarTemplateDecl *VarTemplate, VarDecl *D, void *InsertPos,
3354 const TemplateArgumentListInfo &TemplateArgsInfo,
3355 ArrayRef<TemplateArgument> Converted,
3356 VarTemplateSpecializationDecl *PrevDecl) {
3358 // Do substitution on the type of the declaration
3359 TypeSourceInfo *DI =
3360 SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs,
3361 D->getTypeSpecStartLoc(), D->getDeclName());
3365 if (DI->getType()->isFunctionType()) {
3366 SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function)
3367 << D->isStaticDataMember() << DI->getType();
3371 // Build the instantiated declaration
3372 VarTemplateSpecializationDecl *Var = VarTemplateSpecializationDecl::Create(
3373 SemaRef.Context, Owner, D->getInnerLocStart(), D->getLocation(),
3374 VarTemplate, DI->getType(), DI, D->getStorageClass(), Converted);
3375 Var->setTemplateArgsInfo(TemplateArgsInfo);
3377 VarTemplate->AddSpecialization(Var, InsertPos);
3379 // Substitute the nested name specifier, if any.
3380 if (SubstQualifier(D, Var))
3383 SemaRef.BuildVariableInstantiation(Var, D, TemplateArgs, LateAttrs, Owner,
3384 StartingScope, false, PrevDecl);
3389 Decl *TemplateDeclInstantiator::VisitObjCAtDefsFieldDecl(ObjCAtDefsFieldDecl *D) {
3390 llvm_unreachable("@defs is not supported in Objective-C++");
3393 Decl *TemplateDeclInstantiator::VisitFriendTemplateDecl(FriendTemplateDecl *D) {
3394 // FIXME: We need to be able to instantiate FriendTemplateDecls.
3395 unsigned DiagID = SemaRef.getDiagnostics().getCustomDiagID(
3396 DiagnosticsEngine::Error,
3397 "cannot instantiate %0 yet");
3398 SemaRef.Diag(D->getLocation(), DiagID)
3399 << D->getDeclKindName();
3404 Decl *TemplateDeclInstantiator::VisitConceptDecl(ConceptDecl *D) {
3405 llvm_unreachable("Concept definitions cannot reside inside a template");
3408 Decl *TemplateDeclInstantiator::VisitDecl(Decl *D) {
3409 llvm_unreachable("Unexpected decl");
3412 Decl *Sema::SubstDecl(Decl *D, DeclContext *Owner,
3413 const MultiLevelTemplateArgumentList &TemplateArgs) {
3414 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
3415 if (D->isInvalidDecl())
3418 return Instantiator.Visit(D);
3421 /// Instantiates a nested template parameter list in the current
3422 /// instantiation context.
3424 /// \param L The parameter list to instantiate
3426 /// \returns NULL if there was an error
3427 TemplateParameterList *
3428 TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList *L) {
3429 // Get errors for all the parameters before bailing out.
3430 bool Invalid = false;
3432 unsigned N = L->size();
3433 typedef SmallVector<NamedDecl *, 8> ParamVector;
3436 for (auto &P : *L) {
3437 NamedDecl *D = cast_or_null<NamedDecl>(Visit(P));
3438 Params.push_back(D);
3439 Invalid = Invalid || !D || D->isInvalidDecl();
3442 // Clean up if we had an error.
3446 // Note: we substitute into associated constraints later
3447 Expr *const UninstantiatedRequiresClause = L->getRequiresClause();
3449 TemplateParameterList *InstL
3450 = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(),
3451 L->getLAngleLoc(), Params,
3453 UninstantiatedRequiresClause);
3457 TemplateParameterList *
3458 Sema::SubstTemplateParams(TemplateParameterList *Params, DeclContext *Owner,
3459 const MultiLevelTemplateArgumentList &TemplateArgs) {
3460 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
3461 return Instantiator.SubstTemplateParams(Params);
3464 /// Instantiate the declaration of a class template partial
3467 /// \param ClassTemplate the (instantiated) class template that is partially
3468 // specialized by the instantiation of \p PartialSpec.
3470 /// \param PartialSpec the (uninstantiated) class template partial
3471 /// specialization that we are instantiating.
3473 /// \returns The instantiated partial specialization, if successful; otherwise,
3474 /// NULL to indicate an error.
3475 ClassTemplatePartialSpecializationDecl *
3476 TemplateDeclInstantiator::InstantiateClassTemplatePartialSpecialization(
3477 ClassTemplateDecl *ClassTemplate,
3478 ClassTemplatePartialSpecializationDecl *PartialSpec) {
3479 // Create a local instantiation scope for this class template partial
3480 // specialization, which will contain the instantiations of the template
3482 LocalInstantiationScope Scope(SemaRef);
3484 // Substitute into the template parameters of the class template partial
3486 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
3487 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
3491 // Substitute into the template arguments of the class template partial
3493 const ASTTemplateArgumentListInfo *TemplArgInfo
3494 = PartialSpec->getTemplateArgsAsWritten();
3495 TemplateArgumentListInfo InstTemplateArgs(TemplArgInfo->LAngleLoc,
3496 TemplArgInfo->RAngleLoc);
3497 if (SemaRef.Subst(TemplArgInfo->getTemplateArgs(),
3498 TemplArgInfo->NumTemplateArgs,
3499 InstTemplateArgs, TemplateArgs))
3502 // Check that the template argument list is well-formed for this
3504 SmallVector<TemplateArgument, 4> Converted;
3505 if (SemaRef.CheckTemplateArgumentList(ClassTemplate,
3506 PartialSpec->getLocation(),
3512 // Check these arguments are valid for a template partial specialization.
3513 if (SemaRef.CheckTemplatePartialSpecializationArgs(
3514 PartialSpec->getLocation(), ClassTemplate, InstTemplateArgs.size(),
3518 // Figure out where to insert this class template partial specialization
3519 // in the member template's set of class template partial specializations.
3520 void *InsertPos = nullptr;
3521 ClassTemplateSpecializationDecl *PrevDecl
3522 = ClassTemplate->findPartialSpecialization(Converted, InsertPos);
3524 // Build the canonical type that describes the converted template
3525 // arguments of the class template partial specialization.
3527 = SemaRef.Context.getTemplateSpecializationType(TemplateName(ClassTemplate),
3530 // Build the fully-sugared type for this class template
3531 // specialization as the user wrote in the specialization
3532 // itself. This means that we'll pretty-print the type retrieved
3533 // from the specialization's declaration the way that the user
3534 // actually wrote the specialization, rather than formatting the
3535 // name based on the "canonical" representation used to store the
3536 // template arguments in the specialization.
3537 TypeSourceInfo *WrittenTy
3538 = SemaRef.Context.getTemplateSpecializationTypeInfo(
3539 TemplateName(ClassTemplate),
3540 PartialSpec->getLocation(),
3545 // We've already seen a partial specialization with the same template
3546 // parameters and template arguments. This can happen, for example, when
3547 // substituting the outer template arguments ends up causing two
3548 // class template partial specializations of a member class template
3549 // to have identical forms, e.g.,
3551 // template<typename T, typename U>
3553 // template<typename X, typename Y> struct Inner;
3554 // template<typename Y> struct Inner<T, Y>;
3555 // template<typename Y> struct Inner<U, Y>;
3558 // Outer<int, int> outer; // error: the partial specializations of Inner
3559 // // have the same signature.
3560 SemaRef.Diag(PartialSpec->getLocation(), diag::err_partial_spec_redeclared)
3561 << WrittenTy->getType();
3562 SemaRef.Diag(PrevDecl->getLocation(), diag::note_prev_partial_spec_here)
3563 << SemaRef.Context.getTypeDeclType(PrevDecl);
3568 // Create the class template partial specialization declaration.
3569 ClassTemplatePartialSpecializationDecl *InstPartialSpec =
3570 ClassTemplatePartialSpecializationDecl::Create(
3571 SemaRef.Context, PartialSpec->getTagKind(), Owner,
3572 PartialSpec->getBeginLoc(), PartialSpec->getLocation(), InstParams,
3573 ClassTemplate, Converted, InstTemplateArgs, CanonType, nullptr);
3574 // Substitute the nested name specifier, if any.
3575 if (SubstQualifier(PartialSpec, InstPartialSpec))
3578 InstPartialSpec->setInstantiatedFromMember(PartialSpec);
3579 InstPartialSpec->setTypeAsWritten(WrittenTy);
3581 // Check the completed partial specialization.
3582 SemaRef.CheckTemplatePartialSpecialization(InstPartialSpec);
3584 // Add this partial specialization to the set of class template partial
3586 ClassTemplate->AddPartialSpecialization(InstPartialSpec,
3587 /*InsertPos=*/nullptr);
3588 return InstPartialSpec;
3591 /// Instantiate the declaration of a variable template partial
3594 /// \param VarTemplate the (instantiated) variable template that is partially
3595 /// specialized by the instantiation of \p PartialSpec.
3597 /// \param PartialSpec the (uninstantiated) variable template partial
3598 /// specialization that we are instantiating.
3600 /// \returns The instantiated partial specialization, if successful; otherwise,
3601 /// NULL to indicate an error.
3602 VarTemplatePartialSpecializationDecl *
3603 TemplateDeclInstantiator::InstantiateVarTemplatePartialSpecialization(
3604 VarTemplateDecl *VarTemplate,
3605 VarTemplatePartialSpecializationDecl *PartialSpec) {
3606 // Create a local instantiation scope for this variable template partial
3607 // specialization, which will contain the instantiations of the template
3609 LocalInstantiationScope Scope(SemaRef);
3611 // Substitute into the template parameters of the variable template partial
3613 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
3614 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
3618 // Substitute into the template arguments of the variable template partial
3620 const ASTTemplateArgumentListInfo *TemplArgInfo
3621 = PartialSpec->getTemplateArgsAsWritten();
3622 TemplateArgumentListInfo InstTemplateArgs(TemplArgInfo->LAngleLoc,
3623 TemplArgInfo->RAngleLoc);
3624 if (SemaRef.Subst(TemplArgInfo->getTemplateArgs(),
3625 TemplArgInfo->NumTemplateArgs,
3626 InstTemplateArgs, TemplateArgs))
3629 // Check that the template argument list is well-formed for this
3631 SmallVector<TemplateArgument, 4> Converted;
3632 if (SemaRef.CheckTemplateArgumentList(VarTemplate, PartialSpec->getLocation(),
3633 InstTemplateArgs, false, Converted))
3636 // Check these arguments are valid for a template partial specialization.
3637 if (SemaRef.CheckTemplatePartialSpecializationArgs(
3638 PartialSpec->getLocation(), VarTemplate, InstTemplateArgs.size(),
3642 // Figure out where to insert this variable template partial specialization
3643 // in the member template's set of variable template partial specializations.
3644 void *InsertPos = nullptr;
3645 VarTemplateSpecializationDecl *PrevDecl =
3646 VarTemplate->findPartialSpecialization(Converted, InsertPos);
3648 // Build the canonical type that describes the converted template
3649 // arguments of the variable template partial specialization.
3650 QualType CanonType = SemaRef.Context.getTemplateSpecializationType(
3651 TemplateName(VarTemplate), Converted);
3653 // Build the fully-sugared type for this variable template
3654 // specialization as the user wrote in the specialization
3655 // itself. This means that we'll pretty-print the type retrieved
3656 // from the specialization's declaration the way that the user
3657 // actually wrote the specialization, rather than formatting the
3658 // name based on the "canonical" representation used to store the
3659 // template arguments in the specialization.
3660 TypeSourceInfo *WrittenTy = SemaRef.Context.getTemplateSpecializationTypeInfo(
3661 TemplateName(VarTemplate), PartialSpec->getLocation(), InstTemplateArgs,
3665 // We've already seen a partial specialization with the same template
3666 // parameters and template arguments. This can happen, for example, when
3667 // substituting the outer template arguments ends up causing two
3668 // variable template partial specializations of a member variable template
3669 // to have identical forms, e.g.,
3671 // template<typename T, typename U>
3673 // template<typename X, typename Y> pair<X,Y> p;
3674 // template<typename Y> pair<T, Y> p;
3675 // template<typename Y> pair<U, Y> p;
3678 // Outer<int, int> outer; // error: the partial specializations of Inner
3679 // // have the same signature.
3680 SemaRef.Diag(PartialSpec->getLocation(),
3681 diag::err_var_partial_spec_redeclared)
3682 << WrittenTy->getType();
3683 SemaRef.Diag(PrevDecl->getLocation(),
3684 diag::note_var_prev_partial_spec_here);
3688 // Do substitution on the type of the declaration
3689 TypeSourceInfo *DI = SemaRef.SubstType(
3690 PartialSpec->getTypeSourceInfo(), TemplateArgs,
3691 PartialSpec->getTypeSpecStartLoc(), PartialSpec->getDeclName());
3695 if (DI->getType()->isFunctionType()) {
3696 SemaRef.Diag(PartialSpec->getLocation(),
3697 diag::err_variable_instantiates_to_function)
3698 << PartialSpec->isStaticDataMember() << DI->getType();
3702 // Create the variable template partial specialization declaration.
3703 VarTemplatePartialSpecializationDecl *InstPartialSpec =
3704 VarTemplatePartialSpecializationDecl::Create(
3705 SemaRef.Context, Owner, PartialSpec->getInnerLocStart(),
3706 PartialSpec->getLocation(), InstParams, VarTemplate, DI->getType(),
3707 DI, PartialSpec->getStorageClass(), Converted, InstTemplateArgs);
3709 // Substitute the nested name specifier, if any.
3710 if (SubstQualifier(PartialSpec, InstPartialSpec))
3713 InstPartialSpec->setInstantiatedFromMember(PartialSpec);
3714 InstPartialSpec->setTypeAsWritten(WrittenTy);
3716 // Check the completed partial specialization.
3717 SemaRef.CheckTemplatePartialSpecialization(InstPartialSpec);
3719 // Add this partial specialization to the set of variable template partial
3720 // specializations. The instantiation of the initializer is not necessary.
3721 VarTemplate->AddPartialSpecialization(InstPartialSpec, /*InsertPos=*/nullptr);
3723 SemaRef.BuildVariableInstantiation(InstPartialSpec, PartialSpec, TemplateArgs,
3724 LateAttrs, Owner, StartingScope);
3726 return InstPartialSpec;
3730 TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D,
3731 SmallVectorImpl<ParmVarDecl *> &Params) {
3732 TypeSourceInfo *OldTInfo = D->getTypeSourceInfo();
3733 assert(OldTInfo && "substituting function without type source info");
3734 assert(Params.empty() && "parameter vector is non-empty at start");
3736 CXXRecordDecl *ThisContext = nullptr;
3737 Qualifiers ThisTypeQuals;
3738 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
3739 ThisContext = cast<CXXRecordDecl>(Owner);
3740 ThisTypeQuals = Method->getMethodQualifiers();
3743 TypeSourceInfo *NewTInfo
3744 = SemaRef.SubstFunctionDeclType(OldTInfo, TemplateArgs,
3745 D->getTypeSpecStartLoc(),
3747 ThisContext, ThisTypeQuals);
3751 TypeLoc OldTL = OldTInfo->getTypeLoc().IgnoreParens();
3752 if (FunctionProtoTypeLoc OldProtoLoc = OldTL.getAs<FunctionProtoTypeLoc>()) {
3753 if (NewTInfo != OldTInfo) {
3754 // Get parameters from the new type info.
3755 TypeLoc NewTL = NewTInfo->getTypeLoc().IgnoreParens();
3756 FunctionProtoTypeLoc NewProtoLoc = NewTL.castAs<FunctionProtoTypeLoc>();
3757 unsigned NewIdx = 0;
3758 for (unsigned OldIdx = 0, NumOldParams = OldProtoLoc.getNumParams();
3759 OldIdx != NumOldParams; ++OldIdx) {
3760 ParmVarDecl *OldParam = OldProtoLoc.getParam(OldIdx);
3761 LocalInstantiationScope *Scope = SemaRef.CurrentInstantiationScope;
3763 Optional<unsigned> NumArgumentsInExpansion;
3764 if (OldParam->isParameterPack())
3765 NumArgumentsInExpansion =
3766 SemaRef.getNumArgumentsInExpansion(OldParam->getType(),
3768 if (!NumArgumentsInExpansion) {
3769 // Simple case: normal parameter, or a parameter pack that's
3770 // instantiated to a (still-dependent) parameter pack.
3771 ParmVarDecl *NewParam = NewProtoLoc.getParam(NewIdx++);
3772 Params.push_back(NewParam);
3773 Scope->InstantiatedLocal(OldParam, NewParam);
3775 // Parameter pack expansion: make the instantiation an argument pack.
3776 Scope->MakeInstantiatedLocalArgPack(OldParam);
3777 for (unsigned I = 0; I != *NumArgumentsInExpansion; ++I) {
3778 ParmVarDecl *NewParam = NewProtoLoc.getParam(NewIdx++);
3779 Params.push_back(NewParam);
3780 Scope->InstantiatedLocalPackArg(OldParam, NewParam);
3785 // The function type itself was not dependent and therefore no
3786 // substitution occurred. However, we still need to instantiate
3787 // the function parameters themselves.
3788 const FunctionProtoType *OldProto =
3789 cast<FunctionProtoType>(OldProtoLoc.getType());
3790 for (unsigned i = 0, i_end = OldProtoLoc.getNumParams(); i != i_end;
3792 ParmVarDecl *OldParam = OldProtoLoc.getParam(i);
3794 Params.push_back(SemaRef.BuildParmVarDeclForTypedef(
3795 D, D->getLocation(), OldProto->getParamType(i)));
3800 cast_or_null<ParmVarDecl>(VisitParmVarDecl(OldParam));
3803 Params.push_back(Parm);
3807 // If the type of this function, after ignoring parentheses, is not
3808 // *directly* a function type, then we're instantiating a function that
3809 // was declared via a typedef or with attributes, e.g.,
3811 // typedef int functype(int, int);
3813 // int __cdecl meth(int, int);
3815 // In this case, we'll just go instantiate the ParmVarDecls that we
3816 // synthesized in the method declaration.
3817 SmallVector<QualType, 4> ParamTypes;
3818 Sema::ExtParameterInfoBuilder ExtParamInfos;
3819 if (SemaRef.SubstParmTypes(D->getLocation(), D->parameters(), nullptr,
3820 TemplateArgs, ParamTypes, &Params,
3828 /// Introduce the instantiated function parameters into the local
3829 /// instantiation scope, and set the parameter names to those used
3830 /// in the template.
3831 static bool addInstantiatedParametersToScope(Sema &S, FunctionDecl *Function,
3832 const FunctionDecl *PatternDecl,
3833 LocalInstantiationScope &Scope,
3834 const MultiLevelTemplateArgumentList &TemplateArgs) {
3835 unsigned FParamIdx = 0;
3836 for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I) {
3837 const ParmVarDecl *PatternParam = PatternDecl->getParamDecl(I);
3838 if (!PatternParam->isParameterPack()) {
3839 // Simple case: not a parameter pack.
3840 assert(FParamIdx < Function->getNumParams());
3841 ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
3842 FunctionParam->setDeclName(PatternParam->getDeclName());
3843 // If the parameter's type is not dependent, update it to match the type
3844 // in the pattern. They can differ in top-level cv-qualifiers, and we want
3845 // the pattern's type here. If the type is dependent, they can't differ,
3846 // per core issue 1668. Substitute into the type from the pattern, in case
3847 // it's instantiation-dependent.
3848 // FIXME: Updating the type to work around this is at best fragile.
3849 if (!PatternDecl->getType()->isDependentType()) {
3850 QualType T = S.SubstType(PatternParam->getType(), TemplateArgs,
3851 FunctionParam->getLocation(),
3852 FunctionParam->getDeclName());
3855 FunctionParam->setType(T);
3858 Scope.InstantiatedLocal(PatternParam, FunctionParam);
3863 // Expand the parameter pack.
3864 Scope.MakeInstantiatedLocalArgPack(PatternParam);
3865 Optional<unsigned> NumArgumentsInExpansion
3866 = S.getNumArgumentsInExpansion(PatternParam->getType(), TemplateArgs);
3867 if (NumArgumentsInExpansion) {
3868 QualType PatternType =
3869 PatternParam->getType()->castAs<PackExpansionType>()->getPattern();
3870 for (unsigned Arg = 0; Arg < *NumArgumentsInExpansion; ++Arg) {
3871 ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
3872 FunctionParam->setDeclName(PatternParam->getDeclName());
3873 if (!PatternDecl->getType()->isDependentType()) {
3874 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(S, Arg);
3875 QualType T = S.SubstType(PatternType, TemplateArgs,
3876 FunctionParam->getLocation(),
3877 FunctionParam->getDeclName());
3880 FunctionParam->setType(T);
3883 Scope.InstantiatedLocalPackArg(PatternParam, FunctionParam);
3892 void Sema::InstantiateExceptionSpec(SourceLocation PointOfInstantiation,
3893 FunctionDecl *Decl) {
3894 const FunctionProtoType *Proto = Decl->getType()->castAs<FunctionProtoType>();
3895 if (Proto->getExceptionSpecType() != EST_Uninstantiated)
3898 InstantiatingTemplate Inst(*this, PointOfInstantiation, Decl,
3899 InstantiatingTemplate::ExceptionSpecification());
3900 if (Inst.isInvalid()) {
3901 // We hit the instantiation depth limit. Clear the exception specification
3902 // so that our callers don't have to cope with EST_Uninstantiated.
3903 UpdateExceptionSpec(Decl, EST_None);
3906 if (Inst.isAlreadyInstantiating()) {
3907 // This exception specification indirectly depends on itself. Reject.
3908 // FIXME: Corresponding rule in the standard?
3909 Diag(PointOfInstantiation, diag::err_exception_spec_cycle) << Decl;
3910 UpdateExceptionSpec(Decl, EST_None);
3914 // Enter the scope of this instantiation. We don't use
3915 // PushDeclContext because we don't have a scope.
3916 Sema::ContextRAII savedContext(*this, Decl);
3917 LocalInstantiationScope Scope(*this);
3919 MultiLevelTemplateArgumentList TemplateArgs =
3920 getTemplateInstantiationArgs(Decl, nullptr, /*RelativeToPrimary*/true);
3922 FunctionDecl *Template = Proto->getExceptionSpecTemplate();
3923 if (addInstantiatedParametersToScope(*this, Decl, Template, Scope,
3925 UpdateExceptionSpec(Decl, EST_None);
3929 SubstExceptionSpec(Decl, Template->getType()->castAs<FunctionProtoType>(),
3933 /// Initializes the common fields of an instantiation function
3934 /// declaration (New) from the corresponding fields of its template (Tmpl).
3936 /// \returns true if there was an error
3938 TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New,
3939 FunctionDecl *Tmpl) {
3940 if (Tmpl->isDeleted())
3941 New->setDeletedAsWritten();
3943 New->setImplicit(Tmpl->isImplicit());
3945 // Forward the mangling number from the template to the instantiated decl.
3946 SemaRef.Context.setManglingNumber(New,
3947 SemaRef.Context.getManglingNumber(Tmpl));
3949 // If we are performing substituting explicitly-specified template arguments
3950 // or deduced template arguments into a function template and we reach this
3951 // point, we are now past the point where SFINAE applies and have committed
3952 // to keeping the new function template specialization. We therefore
3953 // convert the active template instantiation for the function template
3954 // into a template instantiation for this specific function template
3955 // specialization, which is not a SFINAE context, so that we diagnose any
3956 // further errors in the declaration itself.
3957 typedef Sema::CodeSynthesisContext ActiveInstType;
3958 ActiveInstType &ActiveInst = SemaRef.CodeSynthesisContexts.back();
3959 if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution ||
3960 ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) {
3961 if (FunctionTemplateDecl *FunTmpl
3962 = dyn_cast<FunctionTemplateDecl>(ActiveInst.Entity)) {
3963 assert(FunTmpl->getTemplatedDecl() == Tmpl &&
3964 "Deduction from the wrong function template?");
3966 atTemplateEnd(SemaRef.TemplateInstCallbacks, SemaRef, ActiveInst);
3967 ActiveInst.Kind = ActiveInstType::TemplateInstantiation;
3968 ActiveInst.Entity = New;
3969 atTemplateBegin(SemaRef.TemplateInstCallbacks, SemaRef, ActiveInst);
3973 const FunctionProtoType *Proto = Tmpl->getType()->getAs<FunctionProtoType>();
3974 assert(Proto && "Function template without prototype?");
3976 if (Proto->hasExceptionSpec() || Proto->getNoReturnAttr()) {
3977 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
3979 // DR1330: In C++11, defer instantiation of a non-trivial
3980 // exception specification.
3981 // DR1484: Local classes and their members are instantiated along with the
3982 // containing function.
3983 if (SemaRef.getLangOpts().CPlusPlus11 &&
3984 EPI.ExceptionSpec.Type != EST_None &&
3985 EPI.ExceptionSpec.Type != EST_DynamicNone &&
3986 EPI.ExceptionSpec.Type != EST_BasicNoexcept &&
3987 !Tmpl->isLexicallyWithinFunctionOrMethod()) {
3988 FunctionDecl *ExceptionSpecTemplate = Tmpl;
3989 if (EPI.ExceptionSpec.Type == EST_Uninstantiated)
3990 ExceptionSpecTemplate = EPI.ExceptionSpec.SourceTemplate;
3991 ExceptionSpecificationType NewEST = EST_Uninstantiated;
3992 if (EPI.ExceptionSpec.Type == EST_Unevaluated)
3993 NewEST = EST_Unevaluated;
3995 // Mark the function has having an uninstantiated exception specification.
3996 const FunctionProtoType *NewProto
3997 = New->getType()->getAs<FunctionProtoType>();
3998 assert(NewProto && "Template instantiation without function prototype?");
3999 EPI = NewProto->getExtProtoInfo();
4000 EPI.ExceptionSpec.Type = NewEST;
4001 EPI.ExceptionSpec.SourceDecl = New;
4002 EPI.ExceptionSpec.SourceTemplate = ExceptionSpecTemplate;
4003 New->setType(SemaRef.Context.getFunctionType(
4004 NewProto->getReturnType(), NewProto->getParamTypes(), EPI));
4006 Sema::ContextRAII SwitchContext(SemaRef, New);
4007 SemaRef.SubstExceptionSpec(New, Proto, TemplateArgs);
4011 // Get the definition. Leaves the variable unchanged if undefined.
4012 const FunctionDecl *Definition = Tmpl;
4013 Tmpl->isDefined(Definition);
4015 SemaRef.InstantiateAttrs(TemplateArgs, Definition, New,
4016 LateAttrs, StartingScope);
4021 /// Initializes common fields of an instantiated method
4022 /// declaration (New) from the corresponding fields of its template
4025 /// \returns true if there was an error
4027 TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New,
4028 CXXMethodDecl *Tmpl) {
4029 if (InitFunctionInstantiation(New, Tmpl))
4032 if (isa<CXXDestructorDecl>(New) && SemaRef.getLangOpts().CPlusPlus11)
4033 SemaRef.AdjustDestructorExceptionSpec(cast<CXXDestructorDecl>(New));
4035 New->setAccess(Tmpl->getAccess());
4036 if (Tmpl->isVirtualAsWritten())
4037 New->setVirtualAsWritten(true);
4039 // FIXME: New needs a pointer to Tmpl
4043 /// Instantiate (or find existing instantiation of) a function template with a
4044 /// given set of template arguments.
4046 /// Usually this should not be used, and template argument deduction should be
4047 /// used in its place.
4049 Sema::InstantiateFunctionDeclaration(FunctionTemplateDecl *FTD,
4050 const TemplateArgumentList *Args,
4051 SourceLocation Loc) {
4052 FunctionDecl *FD = FTD->getTemplatedDecl();
4054 sema::TemplateDeductionInfo Info(Loc);
4055 InstantiatingTemplate Inst(
4056 *this, Loc, FTD, Args->asArray(),
4057 CodeSynthesisContext::ExplicitTemplateArgumentSubstitution, Info);
4058 if (Inst.isInvalid())
4061 ContextRAII SavedContext(*this, FD);
4062 MultiLevelTemplateArgumentList MArgs(*Args);
4064 return cast_or_null<FunctionDecl>(SubstDecl(FD, FD->getParent(), MArgs));
4067 /// In the MS ABI, we need to instantiate default arguments of dllexported
4068 /// default constructors along with the constructor definition. This allows IR
4069 /// gen to emit a constructor closure which calls the default constructor with
4070 /// its default arguments.
4071 static void InstantiateDefaultCtorDefaultArgs(Sema &S,
4072 CXXConstructorDecl *Ctor) {
4073 assert(S.Context.getTargetInfo().getCXXABI().isMicrosoft() &&
4074 Ctor->isDefaultConstructor());
4075 unsigned NumParams = Ctor->getNumParams();
4078 DLLExportAttr *Attr = Ctor->getAttr<DLLExportAttr>();
4081 for (unsigned I = 0; I != NumParams; ++I) {
4082 (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), Ctor,
4083 Ctor->getParamDecl(I));
4084 S.DiscardCleanupsInEvaluationContext();
4088 /// Instantiate the definition of the given function from its
4091 /// \param PointOfInstantiation the point at which the instantiation was
4092 /// required. Note that this is not precisely a "point of instantiation"
4093 /// for the function, but it's close.
4095 /// \param Function the already-instantiated declaration of a
4096 /// function template specialization or member function of a class template
4099 /// \param Recursive if true, recursively instantiates any functions that
4100 /// are required by this instantiation.
4102 /// \param DefinitionRequired if true, then we are performing an explicit
4103 /// instantiation where the body of the function is required. Complain if
4104 /// there is no such body.
4105 void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
4106 FunctionDecl *Function,
4108 bool DefinitionRequired,
4110 if (Function->isInvalidDecl() || Function->isDefined() ||
4111 isa<CXXDeductionGuideDecl>(Function))
4114 // Never instantiate an explicit specialization except if it is a class scope
4115 // explicit specialization.
4116 TemplateSpecializationKind TSK =
4117 Function->getTemplateSpecializationKindForInstantiation();
4118 if (TSK == TSK_ExplicitSpecialization)
4121 // Find the function body that we'll be substituting.
4122 const FunctionDecl *PatternDecl = Function->getTemplateInstantiationPattern();
4123 assert(PatternDecl && "instantiating a non-template");
4125 const FunctionDecl *PatternDef = PatternDecl->getDefinition();
4126 Stmt *Pattern = nullptr;
4128 Pattern = PatternDef->getBody(PatternDef);
4129 PatternDecl = PatternDef;
4130 if (PatternDef->willHaveBody())
4131 PatternDef = nullptr;
4134 // FIXME: We need to track the instantiation stack in order to know which
4135 // definitions should be visible within this instantiation.
4136 if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Function,
4137 Function->getInstantiatedFromMemberFunction(),
4138 PatternDecl, PatternDef, TSK,
4139 /*Complain*/DefinitionRequired)) {
4140 if (DefinitionRequired)
4141 Function->setInvalidDecl();
4142 else if (TSK == TSK_ExplicitInstantiationDefinition) {
4143 // Try again at the end of the translation unit (at which point a
4144 // definition will be required).
4146 Function->setInstantiationIsPending(true);
4147 PendingInstantiations.push_back(
4148 std::make_pair(Function, PointOfInstantiation));
4149 } else if (TSK == TSK_ImplicitInstantiation) {
4150 if (AtEndOfTU && !getDiagnostics().hasErrorOccurred() &&
4151 !getSourceManager().isInSystemHeader(PatternDecl->getBeginLoc())) {
4152 Diag(PointOfInstantiation, diag::warn_func_template_missing)
4154 Diag(PatternDecl->getLocation(), diag::note_forward_template_decl);
4155 if (getLangOpts().CPlusPlus11)
4156 Diag(PointOfInstantiation, diag::note_inst_declaration_hint)
4164 // Postpone late parsed template instantiations.
4165 if (PatternDecl->isLateTemplateParsed() &&
4166 !LateTemplateParser) {
4167 Function->setInstantiationIsPending(true);
4168 LateParsedInstantiations.push_back(
4169 std::make_pair(Function, PointOfInstantiation));
4173 llvm::TimeTraceScope TimeScope("InstantiateFunction", [&]() {
4175 llvm::raw_string_ostream OS(Name);
4176 Function->getNameForDiagnostic(OS, getPrintingPolicy(),
4177 /*Qualified=*/true);
4181 // If we're performing recursive template instantiation, create our own
4182 // queue of pending implicit instantiations that we will instantiate later,
4183 // while we're still within our own instantiation context.
4184 // This has to happen before LateTemplateParser below is called, so that
4185 // it marks vtables used in late parsed templates as used.
4186 GlobalEagerInstantiationScope GlobalInstantiations(*this,
4187 /*Enabled=*/Recursive);
4188 LocalEagerInstantiationScope LocalInstantiations(*this);
4190 // Call the LateTemplateParser callback if there is a need to late parse
4191 // a templated function definition.
4192 if (!Pattern && PatternDecl->isLateTemplateParsed() &&
4193 LateTemplateParser) {
4194 // FIXME: Optimize to allow individual templates to be deserialized.
4195 if (PatternDecl->isFromASTFile())
4196 ExternalSource->ReadLateParsedTemplates(LateParsedTemplateMap);
4198 auto LPTIter = LateParsedTemplateMap.find(PatternDecl);
4199 assert(LPTIter != LateParsedTemplateMap.end() &&
4200 "missing LateParsedTemplate");
4201 LateTemplateParser(OpaqueParser, *LPTIter->second);
4202 Pattern = PatternDecl->getBody(PatternDecl);
4205 // Note, we should never try to instantiate a deleted function template.
4206 assert((Pattern || PatternDecl->isDefaulted() ||
4207 PatternDecl->hasSkippedBody()) &&
4208 "unexpected kind of function template definition");
4210 // C++1y [temp.explicit]p10:
4211 // Except for inline functions, declarations with types deduced from their
4212 // initializer or return value, and class template specializations, other
4213 // explicit instantiation declarations have the effect of suppressing the
4214 // implicit instantiation of the entity to which they refer.
4215 if (TSK == TSK_ExplicitInstantiationDeclaration &&
4216 !PatternDecl->isInlined() &&
4217 !PatternDecl->getReturnType()->getContainedAutoType())
4220 if (PatternDecl->isInlined()) {
4221 // Function, and all later redeclarations of it (from imported modules,
4222 // for instance), are now implicitly inline.
4223 for (auto *D = Function->getMostRecentDecl(); /**/;
4224 D = D->getPreviousDecl()) {
4225 D->setImplicitlyInline();
4231 InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
4232 if (Inst.isInvalid() || Inst.isAlreadyInstantiating())
4234 PrettyDeclStackTraceEntry CrashInfo(Context, Function, SourceLocation(),
4235 "instantiating function definition");
4237 // The instantiation is visible here, even if it was first declared in an
4238 // unimported module.
4239 Function->setVisibleDespiteOwningModule();
4241 // Copy the inner loc start from the pattern.
4242 Function->setInnerLocStart(PatternDecl->getInnerLocStart());
4244 EnterExpressionEvaluationContext EvalContext(
4245 *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
4247 // Introduce a new scope where local variable instantiations will be
4248 // recorded, unless we're actually a member function within a local
4249 // class, in which case we need to merge our results with the parent
4250 // scope (of the enclosing function).
4251 bool MergeWithParentScope = false;
4252 if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Function->getDeclContext()))
4253 MergeWithParentScope = Rec->isLocalClass();
4255 LocalInstantiationScope Scope(*this, MergeWithParentScope);
4257 if (PatternDecl->isDefaulted())
4258 SetDeclDefaulted(Function, PatternDecl->getLocation());
4260 MultiLevelTemplateArgumentList TemplateArgs =
4261 getTemplateInstantiationArgs(Function, nullptr, false, PatternDecl);
4263 // Substitute into the qualifier; we can get a substitution failure here
4264 // through evil use of alias templates.
4265 // FIXME: Is CurContext correct for this? Should we go to the (instantiation
4266 // of the) lexical context of the pattern?
4267 SubstQualifier(*this, PatternDecl, Function, TemplateArgs);
4269 ActOnStartOfFunctionDef(nullptr, Function);
4271 // Enter the scope of this instantiation. We don't use
4272 // PushDeclContext because we don't have a scope.
4273 Sema::ContextRAII savedContext(*this, Function);
4275 if (addInstantiatedParametersToScope(*this, Function, PatternDecl, Scope,
4280 if (PatternDecl->hasSkippedBody()) {
4281 ActOnSkippedFunctionBody(Function);
4284 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Function)) {
4285 // If this is a constructor, instantiate the member initializers.
4286 InstantiateMemInitializers(Ctor, cast<CXXConstructorDecl>(PatternDecl),
4289 // If this is an MS ABI dllexport default constructor, instantiate any
4290 // default arguments.
4291 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
4292 Ctor->isDefaultConstructor()) {
4293 InstantiateDefaultCtorDefaultArgs(*this, Ctor);
4297 // Instantiate the function body.
4298 Body = SubstStmt(Pattern, TemplateArgs);
4300 if (Body.isInvalid())
4301 Function->setInvalidDecl();
4303 // FIXME: finishing the function body while in an expression evaluation
4304 // context seems wrong. Investigate more.
4305 ActOnFinishFunctionBody(Function, Body.get(), /*IsInstantiation=*/true);
4307 PerformDependentDiagnostics(PatternDecl, TemplateArgs);
4309 if (auto *Listener = getASTMutationListener())
4310 Listener->FunctionDefinitionInstantiated(Function);
4315 DeclGroupRef DG(Function);
4316 Consumer.HandleTopLevelDecl(DG);
4318 // This class may have local implicit instantiations that need to be
4319 // instantiation within this scope.
4320 LocalInstantiations.perform();
4322 GlobalInstantiations.perform();
4325 VarTemplateSpecializationDecl *Sema::BuildVarTemplateInstantiation(
4326 VarTemplateDecl *VarTemplate, VarDecl *FromVar,
4327 const TemplateArgumentList &TemplateArgList,
4328 const TemplateArgumentListInfo &TemplateArgsInfo,
4329 SmallVectorImpl<TemplateArgument> &Converted,
4330 SourceLocation PointOfInstantiation, void *InsertPos,
4331 LateInstantiatedAttrVec *LateAttrs,
4332 LocalInstantiationScope *StartingScope) {
4333 if (FromVar->isInvalidDecl())
4336 InstantiatingTemplate Inst(*this, PointOfInstantiation, FromVar);
4337 if (Inst.isInvalid())
4340 MultiLevelTemplateArgumentList TemplateArgLists;
4341 TemplateArgLists.addOuterTemplateArguments(&TemplateArgList);
4343 // Instantiate the first declaration of the variable template: for a partial
4344 // specialization of a static data member template, the first declaration may
4345 // or may not be the declaration in the class; if it's in the class, we want
4346 // to instantiate a member in the class (a declaration), and if it's outside,
4347 // we want to instantiate a definition.
4349 // If we're instantiating an explicitly-specialized member template or member
4350 // partial specialization, don't do this. The member specialization completely
4351 // replaces the original declaration in this case.
4352 bool IsMemberSpec = false;
4353 if (VarTemplatePartialSpecializationDecl *PartialSpec =
4354 dyn_cast<VarTemplatePartialSpecializationDecl>(FromVar))
4355 IsMemberSpec = PartialSpec->isMemberSpecialization();
4356 else if (VarTemplateDecl *FromTemplate = FromVar->getDescribedVarTemplate())
4357 IsMemberSpec = FromTemplate->isMemberSpecialization();
4359 FromVar = FromVar->getFirstDecl();
4361 MultiLevelTemplateArgumentList MultiLevelList(TemplateArgList);
4362 TemplateDeclInstantiator Instantiator(*this, FromVar->getDeclContext(),
4365 // TODO: Set LateAttrs and StartingScope ...
4367 return cast_or_null<VarTemplateSpecializationDecl>(
4368 Instantiator.VisitVarTemplateSpecializationDecl(
4369 VarTemplate, FromVar, InsertPos, TemplateArgsInfo, Converted));
4372 /// Instantiates a variable template specialization by completing it
4373 /// with appropriate type information and initializer.
4374 VarTemplateSpecializationDecl *Sema::CompleteVarTemplateSpecializationDecl(
4375 VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl,
4376 const MultiLevelTemplateArgumentList &TemplateArgs) {
4377 assert(PatternDecl->isThisDeclarationADefinition() &&
4378 "don't have a definition to instantiate from");
4380 // Do substitution on the type of the declaration
4381 TypeSourceInfo *DI =
4382 SubstType(PatternDecl->getTypeSourceInfo(), TemplateArgs,
4383 PatternDecl->getTypeSpecStartLoc(), PatternDecl->getDeclName());
4387 // Update the type of this variable template specialization.
4388 VarSpec->setType(DI->getType());
4390 // Convert the declaration into a definition now.
4391 VarSpec->setCompleteDefinition();
4393 // Instantiate the initializer.
4394 InstantiateVariableInitializer(VarSpec, PatternDecl, TemplateArgs);
4399 /// BuildVariableInstantiation - Used after a new variable has been created.
4400 /// Sets basic variable data and decides whether to postpone the
4401 /// variable instantiation.
4402 void Sema::BuildVariableInstantiation(
4403 VarDecl *NewVar, VarDecl *OldVar,
4404 const MultiLevelTemplateArgumentList &TemplateArgs,
4405 LateInstantiatedAttrVec *LateAttrs, DeclContext *Owner,
4406 LocalInstantiationScope *StartingScope,
4407 bool InstantiatingVarTemplate,
4408 VarTemplateSpecializationDecl *PrevDeclForVarTemplateSpecialization) {
4409 // Instantiating a partial specialization to produce a partial
4411 bool InstantiatingVarTemplatePartialSpec =
4412 isa<VarTemplatePartialSpecializationDecl>(OldVar) &&
4413 isa<VarTemplatePartialSpecializationDecl>(NewVar);
4414 // Instantiating from a variable template (or partial specialization) to
4415 // produce a variable template specialization.
4416 bool InstantiatingSpecFromTemplate =
4417 isa<VarTemplateSpecializationDecl>(NewVar) &&
4418 (OldVar->getDescribedVarTemplate() ||
4419 isa<VarTemplatePartialSpecializationDecl>(OldVar));
4421 // If we are instantiating a local extern declaration, the
4422 // instantiation belongs lexically to the containing function.
4423 // If we are instantiating a static data member defined
4424 // out-of-line, the instantiation will have the same lexical
4425 // context (which will be a namespace scope) as the template.
4426 if (OldVar->isLocalExternDecl()) {
4427 NewVar->setLocalExternDecl();
4428 NewVar->setLexicalDeclContext(Owner);
4429 } else if (OldVar->isOutOfLine())
4430 NewVar->setLexicalDeclContext(OldVar->getLexicalDeclContext());
4431 NewVar->setTSCSpec(OldVar->getTSCSpec());
4432 NewVar->setInitStyle(OldVar->getInitStyle());
4433 NewVar->setCXXForRangeDecl(OldVar->isCXXForRangeDecl());
4434 NewVar->setObjCForDecl(OldVar->isObjCForDecl());
4435 NewVar->setConstexpr(OldVar->isConstexpr());
4436 NewVar->setInitCapture(OldVar->isInitCapture());
4437 NewVar->setPreviousDeclInSameBlockScope(
4438 OldVar->isPreviousDeclInSameBlockScope());
4439 NewVar->setAccess(OldVar->getAccess());
4441 if (!OldVar->isStaticDataMember()) {
4442 if (OldVar->isUsed(false))
4443 NewVar->setIsUsed();
4444 NewVar->setReferenced(OldVar->isReferenced());
4447 InstantiateAttrs(TemplateArgs, OldVar, NewVar, LateAttrs, StartingScope);
4449 LookupResult Previous(
4450 *this, NewVar->getDeclName(), NewVar->getLocation(),
4451 NewVar->isLocalExternDecl() ? Sema::LookupRedeclarationWithLinkage
4452 : Sema::LookupOrdinaryName,
4453 NewVar->isLocalExternDecl() ? Sema::ForExternalRedeclaration
4454 : forRedeclarationInCurContext());
4456 if (NewVar->isLocalExternDecl() && OldVar->getPreviousDecl() &&
4457 (!OldVar->getPreviousDecl()->getDeclContext()->isDependentContext() ||
4458 OldVar->getPreviousDecl()->getDeclContext()==OldVar->getDeclContext())) {
4459 // We have a previous declaration. Use that one, so we merge with the
4461 if (NamedDecl *NewPrev = FindInstantiatedDecl(
4462 NewVar->getLocation(), OldVar->getPreviousDecl(), TemplateArgs))
4463 Previous.addDecl(NewPrev);
4464 } else if (!isa<VarTemplateSpecializationDecl>(NewVar) &&
4465 OldVar->hasLinkage()) {
4466 LookupQualifiedName(Previous, NewVar->getDeclContext(), false);
4467 } else if (PrevDeclForVarTemplateSpecialization) {
4468 Previous.addDecl(PrevDeclForVarTemplateSpecialization);
4470 CheckVariableDeclaration(NewVar, Previous);
4472 if (!InstantiatingVarTemplate) {
4473 NewVar->getLexicalDeclContext()->addHiddenDecl(NewVar);
4474 if (!NewVar->isLocalExternDecl() || !NewVar->getPreviousDecl())
4475 NewVar->getDeclContext()->makeDeclVisibleInContext(NewVar);
4478 if (!OldVar->isOutOfLine()) {
4479 if (NewVar->getDeclContext()->isFunctionOrMethod())
4480 CurrentInstantiationScope->InstantiatedLocal(OldVar, NewVar);
4483 // Link instantiations of static data members back to the template from
4484 // which they were instantiated.
4486 // Don't do this when instantiating a template (we link the template itself
4487 // back in that case) nor when instantiating a static data member template
4488 // (that's not a member specialization).
4489 if (NewVar->isStaticDataMember() && !InstantiatingVarTemplate &&
4490 !InstantiatingSpecFromTemplate)
4491 NewVar->setInstantiationOfStaticDataMember(OldVar,
4492 TSK_ImplicitInstantiation);
4494 // If the pattern is an (in-class) explicit specialization, then the result
4495 // is also an explicit specialization.
4496 if (VarTemplateSpecializationDecl *OldVTSD =
4497 dyn_cast<VarTemplateSpecializationDecl>(OldVar)) {
4498 if (OldVTSD->getSpecializationKind() == TSK_ExplicitSpecialization &&
4499 !isa<VarTemplatePartialSpecializationDecl>(OldVTSD))
4500 cast<VarTemplateSpecializationDecl>(NewVar)->setSpecializationKind(
4501 TSK_ExplicitSpecialization);
4504 // Forward the mangling number from the template to the instantiated decl.
4505 Context.setManglingNumber(NewVar, Context.getManglingNumber(OldVar));
4506 Context.setStaticLocalNumber(NewVar, Context.getStaticLocalNumber(OldVar));
4508 // Figure out whether to eagerly instantiate the initializer.
4509 if (InstantiatingVarTemplate || InstantiatingVarTemplatePartialSpec) {
4510 // We're producing a template. Don't instantiate the initializer yet.
4511 } else if (NewVar->getType()->isUndeducedType()) {
4512 // We need the type to complete the declaration of the variable.
4513 InstantiateVariableInitializer(NewVar, OldVar, TemplateArgs);
4514 } else if (InstantiatingSpecFromTemplate ||
4515 (OldVar->isInline() && OldVar->isThisDeclarationADefinition() &&
4516 !NewVar->isThisDeclarationADefinition())) {
4517 // Delay instantiation of the initializer for variable template
4518 // specializations or inline static data members until a definition of the
4519 // variable is needed.
4521 InstantiateVariableInitializer(NewVar, OldVar, TemplateArgs);
4524 // Diagnose unused local variables with dependent types, where the diagnostic
4525 // will have been deferred.
4526 if (!NewVar->isInvalidDecl() &&
4527 NewVar->getDeclContext()->isFunctionOrMethod() &&
4528 OldVar->getType()->isDependentType())
4529 DiagnoseUnusedDecl(NewVar);
4532 /// Instantiate the initializer of a variable.
4533 void Sema::InstantiateVariableInitializer(
4534 VarDecl *Var, VarDecl *OldVar,
4535 const MultiLevelTemplateArgumentList &TemplateArgs) {
4536 if (ASTMutationListener *L = getASTContext().getASTMutationListener())
4537 L->VariableDefinitionInstantiated(Var);
4539 // We propagate the 'inline' flag with the initializer, because it
4540 // would otherwise imply that the variable is a definition for a
4541 // non-static data member.
4542 if (OldVar->isInlineSpecified())
4543 Var->setInlineSpecified();
4544 else if (OldVar->isInline())
4545 Var->setImplicitlyInline();
4547 if (OldVar->getInit()) {
4548 EnterExpressionEvaluationContext Evaluated(
4549 *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated, Var);
4551 // Instantiate the initializer.
4555 ContextRAII SwitchContext(*this, Var->getDeclContext());
4556 Init = SubstInitializer(OldVar->getInit(), TemplateArgs,
4557 OldVar->getInitStyle() == VarDecl::CallInit);
4560 if (!Init.isInvalid()) {
4561 Expr *InitExpr = Init.get();
4563 if (Var->hasAttr<DLLImportAttr>() &&
4565 !InitExpr->isConstantInitializer(getASTContext(), false))) {
4566 // Do not dynamically initialize dllimport variables.
4567 } else if (InitExpr) {
4568 bool DirectInit = OldVar->isDirectInit();
4569 AddInitializerToDecl(Var, InitExpr, DirectInit);
4571 ActOnUninitializedDecl(Var);
4573 // FIXME: Not too happy about invalidating the declaration
4574 // because of a bogus initializer.
4575 Var->setInvalidDecl();
4578 // `inline` variables are a definition and declaration all in one; we won't
4579 // pick up an initializer from anywhere else.
4580 if (Var->isStaticDataMember() && !Var->isInline()) {
4581 if (!Var->isOutOfLine())
4584 // If the declaration inside the class had an initializer, don't add
4585 // another one to the out-of-line definition.
4586 if (OldVar->getFirstDecl()->hasInit())
4590 // We'll add an initializer to a for-range declaration later.
4591 if (Var->isCXXForRangeDecl() || Var->isObjCForDecl())
4594 ActOnUninitializedDecl(Var);
4597 if (getLangOpts().CUDA)
4598 checkAllowedCUDAInitializer(Var);
4601 /// Instantiate the definition of the given variable from its
4604 /// \param PointOfInstantiation the point at which the instantiation was
4605 /// required. Note that this is not precisely a "point of instantiation"
4606 /// for the variable, but it's close.
4608 /// \param Var the already-instantiated declaration of a templated variable.
4610 /// \param Recursive if true, recursively instantiates any functions that
4611 /// are required by this instantiation.
4613 /// \param DefinitionRequired if true, then we are performing an explicit
4614 /// instantiation where a definition of the variable is required. Complain
4615 /// if there is no such definition.
4616 void Sema::InstantiateVariableDefinition(SourceLocation PointOfInstantiation,
4617 VarDecl *Var, bool Recursive,
4618 bool DefinitionRequired, bool AtEndOfTU) {
4619 if (Var->isInvalidDecl())
4622 // Never instantiate an explicitly-specialized entity.
4623 TemplateSpecializationKind TSK =
4624 Var->getTemplateSpecializationKindForInstantiation();
4625 if (TSK == TSK_ExplicitSpecialization)
4628 // Find the pattern and the arguments to substitute into it.
4629 VarDecl *PatternDecl = Var->getTemplateInstantiationPattern();
4630 assert(PatternDecl && "no pattern for templated variable");
4631 MultiLevelTemplateArgumentList TemplateArgs =
4632 getTemplateInstantiationArgs(Var);
4634 VarTemplateSpecializationDecl *VarSpec =
4635 dyn_cast<VarTemplateSpecializationDecl>(Var);
4637 // If this is a variable template specialization, make sure that it is
4639 bool InstantiationDependent = false;
4640 assert(!TemplateSpecializationType::anyDependentTemplateArguments(
4641 VarSpec->getTemplateArgsInfo(), InstantiationDependent) &&
4642 "Only instantiate variable template specializations that are "
4643 "not type-dependent");
4644 (void)InstantiationDependent;
4646 // If this is a static data member template, there might be an
4647 // uninstantiated initializer on the declaration. If so, instantiate
4650 // FIXME: This largely duplicates what we would do below. The difference
4651 // is that along this path we may instantiate an initializer from an
4652 // in-class declaration of the template and instantiate the definition
4653 // from a separate out-of-class definition.
4654 if (PatternDecl->isStaticDataMember() &&
4655 (PatternDecl = PatternDecl->getFirstDecl())->hasInit() &&
4657 // FIXME: Factor out the duplicated instantiation context setup/tear down
4659 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
4660 if (Inst.isInvalid() || Inst.isAlreadyInstantiating())
4662 PrettyDeclStackTraceEntry CrashInfo(Context, Var, SourceLocation(),
4663 "instantiating variable initializer");
4665 // The instantiation is visible here, even if it was first declared in an
4666 // unimported module.
4667 Var->setVisibleDespiteOwningModule();
4669 // If we're performing recursive template instantiation, create our own
4670 // queue of pending implicit instantiations that we will instantiate
4671 // later, while we're still within our own instantiation context.
4672 GlobalEagerInstantiationScope GlobalInstantiations(*this,
4673 /*Enabled=*/Recursive);
4674 LocalInstantiationScope Local(*this);
4675 LocalEagerInstantiationScope LocalInstantiations(*this);
4677 // Enter the scope of this instantiation. We don't use
4678 // PushDeclContext because we don't have a scope.
4679 ContextRAII PreviousContext(*this, Var->getDeclContext());
4680 InstantiateVariableInitializer(Var, PatternDecl, TemplateArgs);
4681 PreviousContext.pop();
4683 // This variable may have local implicit instantiations that need to be
4684 // instantiated within this scope.
4685 LocalInstantiations.perform();
4687 GlobalInstantiations.perform();
4690 assert(Var->isStaticDataMember() && PatternDecl->isStaticDataMember() &&
4691 "not a static data member?");
4694 VarDecl *Def = PatternDecl->getDefinition(getASTContext());
4696 // If we don't have a definition of the variable template, we won't perform
4697 // any instantiation. Rather, we rely on the user to instantiate this
4698 // definition (or provide a specialization for it) in another translation
4700 if (!Def && !DefinitionRequired) {
4701 if (TSK == TSK_ExplicitInstantiationDefinition) {
4702 PendingInstantiations.push_back(
4703 std::make_pair(Var, PointOfInstantiation));
4704 } else if (TSK == TSK_ImplicitInstantiation) {
4705 // Warn about missing definition at the end of translation unit.
4706 if (AtEndOfTU && !getDiagnostics().hasErrorOccurred() &&
4707 !getSourceManager().isInSystemHeader(PatternDecl->getBeginLoc())) {
4708 Diag(PointOfInstantiation, diag::warn_var_template_missing)
4710 Diag(PatternDecl->getLocation(), diag::note_forward_template_decl);
4711 if (getLangOpts().CPlusPlus11)
4712 Diag(PointOfInstantiation, diag::note_inst_declaration_hint) << Var;
4718 // FIXME: We need to track the instantiation stack in order to know which
4719 // definitions should be visible within this instantiation.
4720 // FIXME: Produce diagnostics when Var->getInstantiatedFromStaticDataMember().
4721 if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Var,
4722 /*InstantiatedFromMember*/false,
4723 PatternDecl, Def, TSK,
4724 /*Complain*/DefinitionRequired))
4727 // C++11 [temp.explicit]p10:
4728 // Except for inline functions, const variables of literal types, variables
4729 // of reference types, [...] explicit instantiation declarations
4730 // have the effect of suppressing the implicit instantiation of the entity
4731 // to which they refer.
4733 // FIXME: That's not exactly the same as "might be usable in constant
4734 // expressions", which only allows constexpr variables and const integral
4735 // types, not arbitrary const literal types.
4736 if (TSK == TSK_ExplicitInstantiationDeclaration &&
4737 !Var->mightBeUsableInConstantExpressions(getASTContext()))
4740 // Make sure to pass the instantiated variable to the consumer at the end.
4741 struct PassToConsumerRAII {
4742 ASTConsumer &Consumer;
4745 PassToConsumerRAII(ASTConsumer &Consumer, VarDecl *Var)
4746 : Consumer(Consumer), Var(Var) { }
4748 ~PassToConsumerRAII() {
4749 Consumer.HandleCXXStaticMemberVarInstantiation(Var);
4751 } PassToConsumerRAII(Consumer, Var);
4753 // If we already have a definition, we're done.
4754 if (VarDecl *Def = Var->getDefinition()) {
4755 // We may be explicitly instantiating something we've already implicitly
4757 Def->setTemplateSpecializationKind(Var->getTemplateSpecializationKind(),
4758 PointOfInstantiation);
4762 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
4763 if (Inst.isInvalid() || Inst.isAlreadyInstantiating())
4765 PrettyDeclStackTraceEntry CrashInfo(Context, Var, SourceLocation(),
4766 "instantiating variable definition");
4768 // If we're performing recursive template instantiation, create our own
4769 // queue of pending implicit instantiations that we will instantiate later,
4770 // while we're still within our own instantiation context.
4771 GlobalEagerInstantiationScope GlobalInstantiations(*this,
4772 /*Enabled=*/Recursive);
4774 // Enter the scope of this instantiation. We don't use
4775 // PushDeclContext because we don't have a scope.
4776 ContextRAII PreviousContext(*this, Var->getDeclContext());
4777 LocalInstantiationScope Local(*this);
4779 LocalEagerInstantiationScope LocalInstantiations(*this);
4781 VarDecl *OldVar = Var;
4782 if (Def->isStaticDataMember() && !Def->isOutOfLine()) {
4783 // We're instantiating an inline static data member whose definition was
4784 // provided inside the class.
4785 InstantiateVariableInitializer(Var, Def, TemplateArgs);
4786 } else if (!VarSpec) {
4787 Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(),
4789 } else if (Var->isStaticDataMember() &&
4790 Var->getLexicalDeclContext()->isRecord()) {
4791 // We need to instantiate the definition of a static data member template,
4792 // and all we have is the in-class declaration of it. Instantiate a separate
4793 // declaration of the definition.
4794 TemplateDeclInstantiator Instantiator(*this, Var->getDeclContext(),
4796 Var = cast_or_null<VarDecl>(Instantiator.VisitVarTemplateSpecializationDecl(
4797 VarSpec->getSpecializedTemplate(), Def, nullptr,
4798 VarSpec->getTemplateArgsInfo(), VarSpec->getTemplateArgs().asArray()));
4800 llvm::PointerUnion<VarTemplateDecl *,
4801 VarTemplatePartialSpecializationDecl *> PatternPtr =
4802 VarSpec->getSpecializedTemplateOrPartial();
4803 if (VarTemplatePartialSpecializationDecl *Partial =
4804 PatternPtr.dyn_cast<VarTemplatePartialSpecializationDecl *>())
4805 cast<VarTemplateSpecializationDecl>(Var)->setInstantiationOf(
4806 Partial, &VarSpec->getTemplateInstantiationArgs());
4808 // Merge the definition with the declaration.
4809 LookupResult R(*this, Var->getDeclName(), Var->getLocation(),
4810 LookupOrdinaryName, forRedeclarationInCurContext());
4812 MergeVarDecl(Var, R);
4814 // Attach the initializer.
4815 InstantiateVariableInitializer(Var, Def, TemplateArgs);
4818 // Complete the existing variable's definition with an appropriately
4819 // substituted type and initializer.
4820 Var = CompleteVarTemplateSpecializationDecl(VarSpec, Def, TemplateArgs);
4822 PreviousContext.pop();
4825 PassToConsumerRAII.Var = Var;
4826 Var->setTemplateSpecializationKind(OldVar->getTemplateSpecializationKind(),
4827 OldVar->getPointOfInstantiation());
4830 // This variable may have local implicit instantiations that need to be
4831 // instantiated within this scope.
4832 LocalInstantiations.perform();
4834 GlobalInstantiations.perform();
4838 Sema::InstantiateMemInitializers(CXXConstructorDecl *New,
4839 const CXXConstructorDecl *Tmpl,
4840 const MultiLevelTemplateArgumentList &TemplateArgs) {
4842 SmallVector<CXXCtorInitializer*, 4> NewInits;
4843 bool AnyErrors = Tmpl->isInvalidDecl();
4845 // Instantiate all the initializers.
4846 for (const auto *Init : Tmpl->inits()) {
4847 // Only instantiate written initializers, let Sema re-construct implicit
4849 if (!Init->isWritten())
4852 SourceLocation EllipsisLoc;
4854 if (Init->isPackExpansion()) {
4855 // This is a pack expansion. We should expand it now.
4856 TypeLoc BaseTL = Init->getTypeSourceInfo()->getTypeLoc();
4857 SmallVector<UnexpandedParameterPack, 4> Unexpanded;
4858 collectUnexpandedParameterPacks(BaseTL, Unexpanded);
4859 collectUnexpandedParameterPacks(Init->getInit(), Unexpanded);
4860 bool ShouldExpand = false;
4861 bool RetainExpansion = false;
4862 Optional<unsigned> NumExpansions;
4863 if (CheckParameterPacksForExpansion(Init->getEllipsisLoc(),
4864 BaseTL.getSourceRange(),
4866 TemplateArgs, ShouldExpand,
4870 New->setInvalidDecl();
4873 assert(ShouldExpand && "Partial instantiation of base initializer?");
4875 // Loop over all of the arguments in the argument pack(s),
4876 for (unsigned I = 0; I != *NumExpansions; ++I) {
4877 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
4879 // Instantiate the initializer.
4880 ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs,
4881 /*CXXDirectInit=*/true);
4882 if (TempInit.isInvalid()) {
4887 // Instantiate the base type.
4888 TypeSourceInfo *BaseTInfo = SubstType(Init->getTypeSourceInfo(),
4890 Init->getSourceLocation(),
4891 New->getDeclName());
4897 // Build the initializer.
4898 MemInitResult NewInit = BuildBaseInitializer(BaseTInfo->getType(),
4899 BaseTInfo, TempInit.get(),
4902 if (NewInit.isInvalid()) {
4907 NewInits.push_back(NewInit.get());
4913 // Instantiate the initializer.
4914 ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs,
4915 /*CXXDirectInit=*/true);
4916 if (TempInit.isInvalid()) {
4921 MemInitResult NewInit;
4922 if (Init->isDelegatingInitializer() || Init->isBaseInitializer()) {
4923 TypeSourceInfo *TInfo = SubstType(Init->getTypeSourceInfo(),
4925 Init->getSourceLocation(),
4926 New->getDeclName());
4929 New->setInvalidDecl();
4933 if (Init->isBaseInitializer())
4934 NewInit = BuildBaseInitializer(TInfo->getType(), TInfo, TempInit.get(),
4935 New->getParent(), EllipsisLoc);
4937 NewInit = BuildDelegatingInitializer(TInfo, TempInit.get(),
4938 cast<CXXRecordDecl>(CurContext->getParent()));
4939 } else if (Init->isMemberInitializer()) {
4940 FieldDecl *Member = cast_or_null<FieldDecl>(FindInstantiatedDecl(
4941 Init->getMemberLocation(),
4946 New->setInvalidDecl();
4950 NewInit = BuildMemberInitializer(Member, TempInit.get(),
4951 Init->getSourceLocation());
4952 } else if (Init->isIndirectMemberInitializer()) {
4953 IndirectFieldDecl *IndirectMember =
4954 cast_or_null<IndirectFieldDecl>(FindInstantiatedDecl(
4955 Init->getMemberLocation(),
4956 Init->getIndirectMember(), TemplateArgs));
4958 if (!IndirectMember) {
4960 New->setInvalidDecl();
4964 NewInit = BuildMemberInitializer(IndirectMember, TempInit.get(),
4965 Init->getSourceLocation());
4968 if (NewInit.isInvalid()) {
4970 New->setInvalidDecl();
4972 NewInits.push_back(NewInit.get());
4976 // Assign all the initializers to the new constructor.
4977 ActOnMemInitializers(New,
4978 /*FIXME: ColonLoc */
4984 // TODO: this could be templated if the various decl types used the
4985 // same method name.
4986 static bool isInstantiationOf(ClassTemplateDecl *Pattern,
4987 ClassTemplateDecl *Instance) {
4988 Pattern = Pattern->getCanonicalDecl();
4991 Instance = Instance->getCanonicalDecl();
4992 if (Pattern == Instance) return true;
4993 Instance = Instance->getInstantiatedFromMemberTemplate();
4999 static bool isInstantiationOf(FunctionTemplateDecl *Pattern,
5000 FunctionTemplateDecl *Instance) {
5001 Pattern = Pattern->getCanonicalDecl();
5004 Instance = Instance->getCanonicalDecl();
5005 if (Pattern == Instance) return true;
5006 Instance = Instance->getInstantiatedFromMemberTemplate();
5013 isInstantiationOf(ClassTemplatePartialSpecializationDecl *Pattern,
5014 ClassTemplatePartialSpecializationDecl *Instance) {
5016 = cast<ClassTemplatePartialSpecializationDecl>(Pattern->getCanonicalDecl());
5018 Instance = cast<ClassTemplatePartialSpecializationDecl>(
5019 Instance->getCanonicalDecl());
5020 if (Pattern == Instance)
5022 Instance = Instance->getInstantiatedFromMember();
5028 static bool isInstantiationOf(CXXRecordDecl *Pattern,
5029 CXXRecordDecl *Instance) {
5030 Pattern = Pattern->getCanonicalDecl();
5033 Instance = Instance->getCanonicalDecl();
5034 if (Pattern == Instance) return true;
5035 Instance = Instance->getInstantiatedFromMemberClass();
5041 static bool isInstantiationOf(FunctionDecl *Pattern,
5042 FunctionDecl *Instance) {
5043 Pattern = Pattern->getCanonicalDecl();
5046 Instance = Instance->getCanonicalDecl();
5047 if (Pattern == Instance) return true;
5048 Instance = Instance->getInstantiatedFromMemberFunction();
5054 static bool isInstantiationOf(EnumDecl *Pattern,
5055 EnumDecl *Instance) {
5056 Pattern = Pattern->getCanonicalDecl();
5059 Instance = Instance->getCanonicalDecl();
5060 if (Pattern == Instance) return true;
5061 Instance = Instance->getInstantiatedFromMemberEnum();
5067 static bool isInstantiationOf(UsingShadowDecl *Pattern,
5068 UsingShadowDecl *Instance,
5070 return declaresSameEntity(C.getInstantiatedFromUsingShadowDecl(Instance),
5074 static bool isInstantiationOf(UsingDecl *Pattern, UsingDecl *Instance,
5076 return declaresSameEntity(C.getInstantiatedFromUsingDecl(Instance), Pattern);
5079 template<typename T>
5080 static bool isInstantiationOfUnresolvedUsingDecl(T *Pattern, Decl *Other,
5082 // An unresolved using declaration can instantiate to an unresolved using
5083 // declaration, or to a using declaration or a using declaration pack.
5085 // Multiple declarations can claim to be instantiated from an unresolved
5086 // using declaration if it's a pack expansion. We want the UsingPackDecl
5087 // in that case, not the individual UsingDecls within the pack.
5088 bool OtherIsPackExpansion;
5089 NamedDecl *OtherFrom;
5090 if (auto *OtherUUD = dyn_cast<T>(Other)) {
5091 OtherIsPackExpansion = OtherUUD->isPackExpansion();
5092 OtherFrom = Ctx.getInstantiatedFromUsingDecl(OtherUUD);
5093 } else if (auto *OtherUPD = dyn_cast<UsingPackDecl>(Other)) {
5094 OtherIsPackExpansion = true;
5095 OtherFrom = OtherUPD->getInstantiatedFromUsingDecl();
5096 } else if (auto *OtherUD = dyn_cast<UsingDecl>(Other)) {
5097 OtherIsPackExpansion = false;
5098 OtherFrom = Ctx.getInstantiatedFromUsingDecl(OtherUD);
5102 return Pattern->isPackExpansion() == OtherIsPackExpansion &&
5103 declaresSameEntity(OtherFrom, Pattern);
5106 static bool isInstantiationOfStaticDataMember(VarDecl *Pattern,
5107 VarDecl *Instance) {
5108 assert(Instance->isStaticDataMember());
5110 Pattern = Pattern->getCanonicalDecl();
5113 Instance = Instance->getCanonicalDecl();
5114 if (Pattern == Instance) return true;
5115 Instance = Instance->getInstantiatedFromStaticDataMember();
5121 // Other is the prospective instantiation
5122 // D is the prospective pattern
5123 static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) {
5124 if (auto *UUD = dyn_cast<UnresolvedUsingTypenameDecl>(D))
5125 return isInstantiationOfUnresolvedUsingDecl(UUD, Other, Ctx);
5127 if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(D))
5128 return isInstantiationOfUnresolvedUsingDecl(UUD, Other, Ctx);
5130 if (D->getKind() != Other->getKind())
5133 if (auto *Record = dyn_cast<CXXRecordDecl>(Other))
5134 return isInstantiationOf(cast<CXXRecordDecl>(D), Record);
5136 if (auto *Function = dyn_cast<FunctionDecl>(Other))
5137 return isInstantiationOf(cast<FunctionDecl>(D), Function);
5139 if (auto *Enum = dyn_cast<EnumDecl>(Other))
5140 return isInstantiationOf(cast<EnumDecl>(D), Enum);
5142 if (auto *Var = dyn_cast<VarDecl>(Other))
5143 if (Var->isStaticDataMember())
5144 return isInstantiationOfStaticDataMember(cast<VarDecl>(D), Var);
5146 if (auto *Temp = dyn_cast<ClassTemplateDecl>(Other))
5147 return isInstantiationOf(cast<ClassTemplateDecl>(D), Temp);
5149 if (auto *Temp = dyn_cast<FunctionTemplateDecl>(Other))
5150 return isInstantiationOf(cast<FunctionTemplateDecl>(D), Temp);
5152 if (auto *PartialSpec =
5153 dyn_cast<ClassTemplatePartialSpecializationDecl>(Other))
5154 return isInstantiationOf(cast<ClassTemplatePartialSpecializationDecl>(D),
5157 if (auto *Field = dyn_cast<FieldDecl>(Other)) {
5158 if (!Field->getDeclName()) {
5159 // This is an unnamed field.
5160 return declaresSameEntity(Ctx.getInstantiatedFromUnnamedFieldDecl(Field),
5161 cast<FieldDecl>(D));
5165 if (auto *Using = dyn_cast<UsingDecl>(Other))
5166 return isInstantiationOf(cast<UsingDecl>(D), Using, Ctx);
5168 if (auto *Shadow = dyn_cast<UsingShadowDecl>(Other))
5169 return isInstantiationOf(cast<UsingShadowDecl>(D), Shadow, Ctx);
5171 return D->getDeclName() &&
5172 D->getDeclName() == cast<NamedDecl>(Other)->getDeclName();
5175 template<typename ForwardIterator>
5176 static NamedDecl *findInstantiationOf(ASTContext &Ctx,
5178 ForwardIterator first,
5179 ForwardIterator last) {
5180 for (; first != last; ++first)
5181 if (isInstantiationOf(Ctx, D, *first))
5182 return cast<NamedDecl>(*first);
5187 /// Finds the instantiation of the given declaration context
5188 /// within the current instantiation.
5190 /// \returns NULL if there was an error
5191 DeclContext *Sema::FindInstantiatedContext(SourceLocation Loc, DeclContext* DC,
5192 const MultiLevelTemplateArgumentList &TemplateArgs) {
5193 if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) {
5194 Decl* ID = FindInstantiatedDecl(Loc, D, TemplateArgs, true);
5195 return cast_or_null<DeclContext>(ID);
5199 /// Find the instantiation of the given declaration within the
5200 /// current instantiation.
5202 /// This routine is intended to be used when \p D is a declaration
5203 /// referenced from within a template, that needs to mapped into the
5204 /// corresponding declaration within an instantiation. For example,
5208 /// template<typename T>
5211 /// KnownValue = sizeof(T)
5214 /// bool getKind() const { return KnownValue; }
5217 /// template struct X<int>;
5220 /// In the instantiation of <tt>X<int>::getKind()</tt>, we need to map the
5221 /// \p EnumConstantDecl for \p KnownValue (which refers to
5222 /// <tt>X<T>::<Kind>::KnownValue</tt>) to its instantiation
5223 /// (<tt>X<int>::<Kind>::KnownValue</tt>). \p FindInstantiatedDecl performs
5224 /// this mapping from within the instantiation of <tt>X<int></tt>.
5225 NamedDecl *Sema::FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
5226 const MultiLevelTemplateArgumentList &TemplateArgs,
5227 bool FindingInstantiatedContext) {
5228 DeclContext *ParentDC = D->getDeclContext();
5229 // FIXME: Parmeters of pointer to functions (y below) that are themselves
5230 // parameters (p below) can have their ParentDC set to the translation-unit
5231 // - thus we can not consistently check if the ParentDC of such a parameter
5232 // is Dependent or/and a FunctionOrMethod.
5233 // For e.g. this code, during Template argument deduction tries to
5234 // find an instantiated decl for (T y) when the ParentDC for y is
5235 // the translation unit.
5236 // e.g. template <class T> void Foo(auto (*p)(T y) -> decltype(y())) {}
5237 // float baz(float(*)()) { return 0.0; }
5239 // The better fix here is perhaps to ensure that a ParmVarDecl, by the time
5240 // it gets here, always has a FunctionOrMethod as its ParentDC??
5242 // - as long as we have a ParmVarDecl whose parent is non-dependent and
5243 // whose type is not instantiation dependent, do nothing to the decl
5244 // - otherwise find its instantiated decl.
5245 if (isa<ParmVarDecl>(D) && !ParentDC->isDependentContext() &&
5246 !cast<ParmVarDecl>(D)->getType()->isInstantiationDependentType())
5248 if (isa<ParmVarDecl>(D) || isa<NonTypeTemplateParmDecl>(D) ||
5249 isa<TemplateTypeParmDecl>(D) || isa<TemplateTemplateParmDecl>(D) ||
5250 ((ParentDC->isFunctionOrMethod() ||
5251 isa<OMPDeclareReductionDecl>(ParentDC) ||
5252 isa<OMPDeclareMapperDecl>(ParentDC)) &&
5253 ParentDC->isDependentContext()) ||
5254 (isa<CXXRecordDecl>(D) && cast<CXXRecordDecl>(D)->isLambda())) {
5255 // D is a local of some kind. Look into the map of local
5256 // declarations to their instantiations.
5257 if (CurrentInstantiationScope) {
5258 if (auto Found = CurrentInstantiationScope->findInstantiationOf(D)) {
5259 if (Decl *FD = Found->dyn_cast<Decl *>())
5260 return cast<NamedDecl>(FD);
5262 int PackIdx = ArgumentPackSubstitutionIndex;
5263 assert(PackIdx != -1 &&
5264 "found declaration pack but not pack expanding");
5265 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
5266 return cast<NamedDecl>((*Found->get<DeclArgumentPack *>())[PackIdx]);
5270 // If we're performing a partial substitution during template argument
5271 // deduction, we may not have values for template parameters yet. They
5272 // just map to themselves.
5273 if (isa<NonTypeTemplateParmDecl>(D) || isa<TemplateTypeParmDecl>(D) ||
5274 isa<TemplateTemplateParmDecl>(D))
5277 if (D->isInvalidDecl())
5280 // Normally this function only searches for already instantiated declaration
5281 // however we have to make an exclusion for local types used before
5282 // definition as in the code:
5284 // template<typename T> void f1() {
5285 // void g1(struct x1);
5289 // In this case instantiation of the type of 'g1' requires definition of
5290 // 'x1', which is defined later. Error recovery may produce an enum used
5291 // before definition. In these cases we need to instantiate relevant
5292 // declarations here.
5293 bool NeedInstantiate = false;
5294 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
5295 NeedInstantiate = RD->isLocalClass();
5297 NeedInstantiate = isa<EnumDecl>(D);
5298 if (NeedInstantiate) {
5299 Decl *Inst = SubstDecl(D, CurContext, TemplateArgs);
5300 CurrentInstantiationScope->InstantiatedLocal(D, Inst);
5301 return cast<TypeDecl>(Inst);
5304 // If we didn't find the decl, then we must have a label decl that hasn't
5305 // been found yet. Lazily instantiate it and return it now.
5306 assert(isa<LabelDecl>(D));
5308 Decl *Inst = SubstDecl(D, CurContext, TemplateArgs);
5309 assert(Inst && "Failed to instantiate label??");
5311 CurrentInstantiationScope->InstantiatedLocal(D, Inst);
5312 return cast<LabelDecl>(Inst);
5315 // For variable template specializations, update those that are still
5317 if (VarTemplateSpecializationDecl *VarSpec =
5318 dyn_cast<VarTemplateSpecializationDecl>(D)) {
5319 bool InstantiationDependent = false;
5320 const TemplateArgumentListInfo &VarTemplateArgs =
5321 VarSpec->getTemplateArgsInfo();
5322 if (TemplateSpecializationType::anyDependentTemplateArguments(
5323 VarTemplateArgs, InstantiationDependent))
5324 D = cast<NamedDecl>(
5325 SubstDecl(D, VarSpec->getDeclContext(), TemplateArgs));
5329 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
5330 if (!Record->isDependentContext())
5333 // Determine whether this record is the "templated" declaration describing
5334 // a class template or class template partial specialization.
5335 ClassTemplateDecl *ClassTemplate = Record->getDescribedClassTemplate();
5337 ClassTemplate = ClassTemplate->getCanonicalDecl();
5338 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
5339 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record))
5340 ClassTemplate = PartialSpec->getSpecializedTemplate()->getCanonicalDecl();
5342 // Walk the current context to find either the record or an instantiation of
5344 DeclContext *DC = CurContext;
5345 while (!DC->isFileContext()) {
5346 // If we're performing substitution while we're inside the template
5347 // definition, we'll find our own context. We're done.
5348 if (DC->Equals(Record))
5351 if (CXXRecordDecl *InstRecord = dyn_cast<CXXRecordDecl>(DC)) {
5352 // Check whether we're in the process of instantiating a class template
5353 // specialization of the template we're mapping.
5354 if (ClassTemplateSpecializationDecl *InstSpec
5355 = dyn_cast<ClassTemplateSpecializationDecl>(InstRecord)){
5356 ClassTemplateDecl *SpecTemplate = InstSpec->getSpecializedTemplate();
5357 if (ClassTemplate && isInstantiationOf(ClassTemplate, SpecTemplate))
5361 // Check whether we're in the process of instantiating a member class.
5362 if (isInstantiationOf(Record, InstRecord))
5366 // Move to the outer template scope.
5367 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC)) {
5368 if (FD->getFriendObjectKind() && FD->getDeclContext()->isFileContext()){
5369 DC = FD->getLexicalDeclContext();
5372 // An implicit deduction guide acts as if it's within the class template
5373 // specialization described by its name and first N template params.
5374 auto *Guide = dyn_cast<CXXDeductionGuideDecl>(FD);
5375 if (Guide && Guide->isImplicit()) {
5376 TemplateDecl *TD = Guide->getDeducedTemplate();
5377 // Convert the arguments to an "as-written" list.
5378 TemplateArgumentListInfo Args(Loc, Loc);
5379 for (TemplateArgument Arg : TemplateArgs.getInnermost().take_front(
5380 TD->getTemplateParameters()->size())) {
5381 ArrayRef<TemplateArgument> Unpacked(Arg);
5382 if (Arg.getKind() == TemplateArgument::Pack)
5383 Unpacked = Arg.pack_elements();
5384 for (TemplateArgument UnpackedArg : Unpacked)
5386 getTrivialTemplateArgumentLoc(UnpackedArg, QualType(), Loc));
5388 QualType T = CheckTemplateIdType(TemplateName(TD), Loc, Args);
5391 auto *SubstRecord = T->getAsCXXRecordDecl();
5392 assert(SubstRecord && "class template id not a class type?");
5393 // Check that this template-id names the primary template and not a
5394 // partial or explicit specialization. (In the latter cases, it's
5395 // meaningless to attempt to find an instantiation of D within the
5397 // FIXME: The standard doesn't say what should happen here.
5398 if (FindingInstantiatedContext &&
5399 usesPartialOrExplicitSpecialization(
5400 Loc, cast<ClassTemplateSpecializationDecl>(SubstRecord))) {
5401 Diag(Loc, diag::err_specialization_not_primary_template)
5402 << T << (SubstRecord->getTemplateSpecializationKind() ==
5403 TSK_ExplicitSpecialization);
5411 DC = DC->getParent();
5414 // Fall through to deal with other dependent record types (e.g.,
5415 // anonymous unions in class templates).
5418 if (!ParentDC->isDependentContext())
5421 ParentDC = FindInstantiatedContext(Loc, ParentDC, TemplateArgs);
5425 if (ParentDC != D->getDeclContext()) {
5426 // We performed some kind of instantiation in the parent context,
5427 // so now we need to look into the instantiated parent context to
5428 // find the instantiation of the declaration D.
5430 // If our context used to be dependent, we may need to instantiate
5431 // it before performing lookup into that context.
5432 bool IsBeingInstantiated = false;
5433 if (CXXRecordDecl *Spec = dyn_cast<CXXRecordDecl>(ParentDC)) {
5434 if (!Spec->isDependentContext()) {
5435 QualType T = Context.getTypeDeclType(Spec);
5436 const RecordType *Tag = T->getAs<RecordType>();
5437 assert(Tag && "type of non-dependent record is not a RecordType");
5438 if (Tag->isBeingDefined())
5439 IsBeingInstantiated = true;
5440 if (!Tag->isBeingDefined() &&
5441 RequireCompleteType(Loc, T, diag::err_incomplete_type))
5444 ParentDC = Tag->getDecl();
5448 NamedDecl *Result = nullptr;
5449 // FIXME: If the name is a dependent name, this lookup won't necessarily
5450 // find it. Does that ever matter?
5451 if (auto Name = D->getDeclName()) {
5452 DeclarationNameInfo NameInfo(Name, D->getLocation());
5453 Name = SubstDeclarationNameInfo(NameInfo, TemplateArgs).getName();
5456 DeclContext::lookup_result Found = ParentDC->lookup(Name);
5457 Result = findInstantiationOf(Context, D, Found.begin(), Found.end());
5459 // Since we don't have a name for the entity we're looking for,
5460 // our only option is to walk through all of the declarations to
5461 // find that name. This will occur in a few cases:
5463 // - anonymous struct/union within a template
5464 // - unnamed class/struct/union/enum within a template
5466 // FIXME: Find a better way to find these instantiations!
5467 Result = findInstantiationOf(Context, D,
5468 ParentDC->decls_begin(),
5469 ParentDC->decls_end());
5473 if (isa<UsingShadowDecl>(D)) {
5474 // UsingShadowDecls can instantiate to nothing because of using hiding.
5475 } else if (Diags.hasErrorOccurred()) {
5476 // We've already complained about something, so most likely this
5477 // declaration failed to instantiate. There's no point in complaining
5478 // further, since this is normal in invalid code.
5479 } else if (IsBeingInstantiated) {
5480 // The class in which this member exists is currently being
5481 // instantiated, and we haven't gotten around to instantiating this
5482 // member yet. This can happen when the code uses forward declarations
5483 // of member classes, and introduces ordering dependencies via
5484 // template instantiation.
5485 Diag(Loc, diag::err_member_not_yet_instantiated)
5487 << Context.getTypeDeclType(cast<CXXRecordDecl>(ParentDC));
5488 Diag(D->getLocation(), diag::note_non_instantiated_member_here);
5489 } else if (EnumConstantDecl *ED = dyn_cast<EnumConstantDecl>(D)) {
5490 // This enumeration constant was found when the template was defined,
5491 // but can't be found in the instantiation. This can happen if an
5492 // unscoped enumeration member is explicitly specialized.
5493 EnumDecl *Enum = cast<EnumDecl>(ED->getLexicalDeclContext());
5494 EnumDecl *Spec = cast<EnumDecl>(FindInstantiatedDecl(Loc, Enum,
5496 assert(Spec->getTemplateSpecializationKind() ==
5497 TSK_ExplicitSpecialization);
5498 Diag(Loc, diag::err_enumerator_does_not_exist)
5500 << Context.getTypeDeclType(cast<TypeDecl>(Spec->getDeclContext()));
5501 Diag(Spec->getLocation(), diag::note_enum_specialized_here)
5502 << Context.getTypeDeclType(Spec);
5504 // We should have found something, but didn't.
5505 llvm_unreachable("Unable to find instantiation of declaration!");
5515 /// Performs template instantiation for all implicit template
5516 /// instantiations we have seen until this point.
5517 void Sema::PerformPendingInstantiations(bool LocalOnly) {
5518 while (!PendingLocalImplicitInstantiations.empty() ||
5519 (!LocalOnly && !PendingInstantiations.empty())) {
5520 PendingImplicitInstantiation Inst;
5522 if (PendingLocalImplicitInstantiations.empty()) {
5523 Inst = PendingInstantiations.front();
5524 PendingInstantiations.pop_front();
5526 Inst = PendingLocalImplicitInstantiations.front();
5527 PendingLocalImplicitInstantiations.pop_front();
5530 // Instantiate function definitions
5531 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) {
5532 bool DefinitionRequired = Function->getTemplateSpecializationKind() ==
5533 TSK_ExplicitInstantiationDefinition;
5534 if (Function->isMultiVersion()) {
5535 getASTContext().forEachMultiversionedFunctionVersion(
5536 Function, [this, Inst, DefinitionRequired](FunctionDecl *CurFD) {
5537 InstantiateFunctionDefinition(/*FIXME:*/ Inst.second, CurFD, true,
5538 DefinitionRequired, true);
5539 if (CurFD->isDefined())
5540 CurFD->setInstantiationIsPending(false);
5543 InstantiateFunctionDefinition(/*FIXME:*/ Inst.second, Function, true,
5544 DefinitionRequired, true);
5545 if (Function->isDefined())
5546 Function->setInstantiationIsPending(false);
5551 // Instantiate variable definitions
5552 VarDecl *Var = cast<VarDecl>(Inst.first);
5554 assert((Var->isStaticDataMember() ||
5555 isa<VarTemplateSpecializationDecl>(Var)) &&
5556 "Not a static data member, nor a variable template"
5557 " specialization?");
5559 // Don't try to instantiate declarations if the most recent redeclaration
5561 if (Var->getMostRecentDecl()->isInvalidDecl())
5564 // Check if the most recent declaration has changed the specialization kind
5565 // and removed the need for implicit instantiation.
5566 switch (Var->getMostRecentDecl()
5567 ->getTemplateSpecializationKindForInstantiation()) {
5568 case TSK_Undeclared:
5569 llvm_unreachable("Cannot instantitiate an undeclared specialization.");
5570 case TSK_ExplicitInstantiationDeclaration:
5571 case TSK_ExplicitSpecialization:
5572 continue; // No longer need to instantiate this type.
5573 case TSK_ExplicitInstantiationDefinition:
5574 // We only need an instantiation if the pending instantiation *is* the
5575 // explicit instantiation.
5576 if (Var != Var->getMostRecentDecl())
5579 case TSK_ImplicitInstantiation:
5583 PrettyDeclStackTraceEntry CrashInfo(Context, Var, SourceLocation(),
5584 "instantiating variable definition");
5585 bool DefinitionRequired = Var->getTemplateSpecializationKind() ==
5586 TSK_ExplicitInstantiationDefinition;
5588 // Instantiate static data member definitions or variable template
5590 InstantiateVariableDefinition(/*FIXME:*/ Inst.second, Var, true,
5591 DefinitionRequired, true);
5595 void Sema::PerformDependentDiagnostics(const DeclContext *Pattern,
5596 const MultiLevelTemplateArgumentList &TemplateArgs) {
5597 for (auto DD : Pattern->ddiags()) {
5598 switch (DD->getKind()) {
5599 case DependentDiagnostic::Access:
5600 HandleDependentAccessCheck(*DD, TemplateArgs);